Open and validate a segment file. When `kek` is `Some` the file is read into memory and AES-256-GCM decrypted; the resulting plaintext is used as the backing buffer. An encrypted (`SEGA`) segment without a KEK or a plaintext (`NDAS`) segment with a KEK both return a typed error from the array crate. When `kek` is `None` the file is memory-mapped directly (zero-copy) and must be a plaintext (`NDA
(
path: &Path,
id: String,
expected_schema_hash: u64,
kek: Option<&WalEncryptionKey>,
)
| 69 | /// When `kek` is `None` the file is memory-mapped directly (zero-copy) |
| 70 | /// and must be a plaintext (`NDAS`) segment. |
| 71 | pub fn open( |
| 72 | path: &Path, |
| 73 | id: String, |
| 74 | expected_schema_hash: u64, |
| 75 | kek: Option<&WalEncryptionKey>, |
| 76 | ) -> Result<Self, SegmentHandleError> { |
| 77 | let backing: Arc<Backing> = if let Some(key) = kek { |
| 78 | // Encrypted path: read raw bytes, decrypt via OwnedSegmentReader. |
| 79 | let raw = std::fs::read(path).map_err(|e| SegmentHandleError::Open { |
| 80 | detail: format!("{path:?}: {e}"), |
| 81 | })?; |
| 82 | let owned = |
| 83 | nodedb_array::segment::reader::OwnedSegmentReader::open_with_kek(&raw, Some(key)) |
| 84 | .map_err(|e| SegmentHandleError::Open { |
| 85 | detail: format!("{path:?}: {e}"), |
| 86 | })?; |
| 87 | // Extract the decrypted plaintext bytes for long-term storage. |
| 88 | Arc::new(Backing::Decrypted(Arc::new(owned.into_plaintext()))) |
| 89 | } else { |
| 90 | // Plaintext path: mmap directly. |
| 91 | let file = std::fs::File::open(path).map_err(|e| SegmentHandleError::Open { |
| 92 | detail: format!("{path:?}: {e}"), |
| 93 | })?; |
| 94 | // Safety: the segment file is treated as read-only; we never |
| 95 | // mutate it through the mmap and the file is not shared for |
| 96 | // writing while the handle is alive. |
| 97 | let mmap = unsafe { Mmap::map(&file) }.map_err(|e| SegmentHandleError::Mmap { |
| 98 | detail: format!("{path:?}: {e}"), |
| 99 | })?; |
| 100 | Arc::new(Backing::Mmap(Arc::new(mmap))) |
| 101 | }; |
| 102 | |
| 103 | let (rtree, schema_hash, tile_count) = { |
| 104 | let reader = |
| 105 | SegmentReader::open(backing.bytes()).map_err(|e| SegmentHandleError::Open { |
| 106 | detail: format!("{path:?}: {e}"), |
| 107 | })?; |
| 108 | if reader.schema_hash() != expected_schema_hash { |
| 109 | return Err(SegmentHandleError::SchemaHashMismatch { |
| 110 | array: expected_schema_hash, |
| 111 | seg: reader.schema_hash(), |
| 112 | }); |
| 113 | } |
| 114 | let rtree = HilbertPackedRTree::build(reader.tiles()); |
| 115 | (rtree, reader.schema_hash(), reader.tile_count()) |
| 116 | }; |
| 117 | |
| 118 | Ok(Self { |
| 119 | backing, |
| 120 | rtree: Arc::new(rtree), |
| 121 | schema_hash, |
| 122 | tile_count, |
| 123 | id, |
| 124 | }) |
| 125 | } |
| 126 | |
| 127 | pub fn id(&self) -> &str { |
| 128 | &self.id |
nothing calls this directly
no test coverage detected