Skip to main content

brep_kernel/io/
snapshot.rs

1//! Native serialized exact-BREP snapshot — the parts-library fast lane.
2//!
3//! Serializes a set of EVALUATED solids (full topology, exact NURBS geometry,
4//! every deterministic face/edge name, and the scene-metadata records stamped
5//! against those names) into one base64 string, and restores them exactly.
6//! This is the `partsLibrary.snapshot` payload of the assemblies build spec
7//! (§2.1/§10.1): inserting a component decodes this straight into resident
8//! kernel structs — no sub-part history execution, no STEP-import-style
9//! reconstruction or validation gate.
10//!
11//! **Format.** A byte container framed over the existing [`encode_solid`] flat
12//! `f64` codec, base64-wrapped for JSON embedding. Reusing the flat codec
13//! (rather than a serde-derive binary layer) keeps the dependency allowlist of
14//! the published crate unchanged and pins an EXPLICIT wire layout: a struct
15//! field reorder cannot silently change the format, and every `f64` round-trips
16//! bit-exact through `to_le_bytes`. Layout (integers u32 little-endian):
17//!
18//! ```text
19//! magic "BREPSNAP" | format version | solid count
20//! per solid: name (len+utf8) | SolidNames JSON (len+utf8) | f64 count | f64s (LE)
21//! metadata record count
22//! per record: entity name (len+utf8) | record JSON (len+utf8)
23//! trailer: FNV-1a 64 checksum of every preceding byte
24//! ```
25//!
26//! The checksum makes ANY byte corruption detectable — without it a bit-flip
27//! inside a control-point coordinate would decode into silently different
28//! geometry instead of the clean `Err` the self-heal lane keys off.
29//!
30//! **Failure frame.** The snapshot is a CACHE; the embedded part document is
31//! the durable source. The format does not survive kernel refactors — it fails
32//! DETECTABLY instead: any unreadable, truncated, corrupted, or
33//! version-mismatched payload returns a clean `Err` (never a panic), which the
34//! ACOMP self-heal lane answers by re-executing the embedded document and
35//! re-snapshotting.
36//!
37//! **…except where the payload IS the document — a DURABILITY commitment.** A
38//! natively-imported part (`IMPORT3D` with `inputParams.nativeBrep`) has NO
39//! parametric history behind it and does not retain the source file it was read
40//! from: this container holds the only copy of that geometry. There is nothing
41//! to self-heal FROM, so an unreadable payload there is LOST GEOMETRY, not a
42//! slow rebuild. This container and [`crate::SOLID_CODEC_VERSION`] are therefore
43//! a **durable format**, not a disposable cache: a version bump must ship a
44//! READER for the previous version (or a migration that rewrites old payloads),
45//! and a layout change that cannot be read forward is a breaking change to saved
46//! user documents. Cheap insurance while the format is at version 1; expensive
47//! to retrofit after the first field file. The clean-`Err` contract above still
48//! holds — it is the detection mechanism, no longer the whole answer.
49//!
50//! **Metadata seam.** [`restore_solids`] RETURNS the captured metadata records
51//! without stamping them into the scene-metadata store: the ACOMP lane must
52//! namespace entity names (`ACOMP2:…`) before calling
53//! `scene_metadata::merge_record`, and only it knows the instance prefix.
54
55use crate::topology::BrepSolid;
56use crate::{decode_solid, encode_solid, SolidNames};
57use std::collections::BTreeMap;
58
59/// Bumped whenever the container layout changes. A mismatch is always a clean
60/// `Err` — the self-heal signal for a snapshot whose part document can be
61/// re-executed. For a payload that IS the document (`nativeBrep`) that `Err` is
62/// unrecoverable, so per the durability commitment in the module doc a bump MUST
63/// ship a reader for the previous version, or a migration.
64pub const SNAPSHOT_FORMAT_VERSION: u32 = 1;
65
66const MAGIC: &[u8; 8] = b"BREPSNAP";
67
68/// One restored solid: its scene name plus the exact topology/geometry.
69#[derive(Debug, Clone)]
70pub struct RestoredSolid {
71    pub name: String,
72    pub solid: BrepSolid,
73}
74
75/// The output of [`restore_solids`]: solids in snapshot order plus the
76/// captured scene-metadata records (`entity name -> own record`), NOT stamped
77/// into the store — see the metadata seam in the module doc.
78#[derive(Debug, Clone)]
79pub struct RestoredSnapshot {
80    pub solids: Vec<RestoredSolid>,
81    pub metadata: Vec<(String, serde_json::Map<String, serde_json::Value>)>,
82}
83
84// ---------------------------------------------------------------------------
85// Snapshot (encode)
86// ---------------------------------------------------------------------------
87
88/// Serialize `(name, solid)` pairs into one base64 snapshot payload. Captures
89/// each entity's OWN scene-metadata record (solid name + every face/edge name)
90/// alongside the geometry, so a stamped part restores with its metadata. The
91/// payload is byte-deterministic for identical input (solids in caller order,
92/// metadata sorted by name).
93pub fn snapshot_solids(solids: &[(&str, &BrepSolid)]) -> Result<String, String> {
94    let mut out = Vec::with_capacity(1024);
95    out.extend_from_slice(MAGIC);
96    push_u32(&mut out, SNAPSHOT_FORMAT_VERSION);
97    push_count(&mut out, solids.len())?;
98    let mut metadata = BTreeMap::<String, String>::new();
99    let mut capture = |name: &str| -> Result<(), String> {
100        if let Some(record) = crate::feature_pipeline::scene_metadata::own_record(name) {
101            let json = serde_json::to_string(&record)
102                .map_err(|error| format!("snapshot: metadata record for '{name}': {error}"))?;
103            metadata.insert(name.to_string(), json);
104        }
105        Ok(())
106    };
107    for (name, solid) in solids {
108        let (data, names) = encode_solid(solid)?;
109        let names_json = serde_json::to_string(&names)
110            .map_err(|error| format!("snapshot: names for '{name}': {error}"))?;
111        push_str(&mut out, name)?;
112        push_str(&mut out, &names_json)?;
113        push_count(&mut out, data.len())?;
114        for value in &data {
115            out.extend_from_slice(&value.to_le_bytes());
116        }
117        capture(name)?;
118        for face_name in names.faces.values() {
119            capture(face_name)?;
120        }
121        for edge_name in names.edges.values() {
122            capture(edge_name)?;
123        }
124    }
125    push_count(&mut out, metadata.len())?;
126    for (name, record_json) in &metadata {
127        push_str(&mut out, name)?;
128        push_str(&mut out, record_json)?;
129    }
130    Ok(seal(out))
131}
132
133/// Append the container checksum and base64-wrap — the single encode exit.
134fn seal(mut container: Vec<u8>) -> String {
135    let digest = fnv1a(&container);
136    container.extend_from_slice(&digest.to_le_bytes());
137    base64_encode(&container)
138}
139
140/// FNV-1a 64 over the container bytes — cheap, dependency-free corruption
141/// detection (not cryptographic; the payload is a local cache, not an input
142/// trust boundary).
143fn fnv1a(bytes: &[u8]) -> u64 {
144    let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
145    for &byte in bytes {
146        hash ^= byte as u64;
147        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
148    }
149    hash
150}
151
152/// [`snapshot_solids`] over RESIDENT solids — the shape the parts-library lane
153/// holds after running a sub-part history (`AddedSolid.name` + handle).
154pub fn snapshot_resident_solids(named_handles: &[(String, u32)]) -> Result<String, String> {
155    let mut owned = Vec::with_capacity(named_handles.len());
156    for (name, handle) in named_handles {
157        let solid = crate::with_registered_solid_str(*handle, |solid| Ok(solid.clone()))?;
158        owned.push((name.as_str(), solid));
159    }
160    let borrowed: Vec<(&str, &BrepSolid)> = owned
161        .iter()
162        .map(|(name, solid)| (*name, solid))
163        .collect();
164    snapshot_solids(&borrowed)
165}
166
167// ---------------------------------------------------------------------------
168// Restore (decode) — O(payload), straight into kernel structs
169// ---------------------------------------------------------------------------
170
171/// Restore a snapshot payload exactly. Every failure mode (bad base64, wrong
172/// magic, version mismatch, truncation, corrupted geometry) is a clean `Err`.
173pub fn restore_solids(payload: &str) -> Result<RestoredSnapshot, String> {
174    let bytes = base64_decode(payload)?;
175    // Checksum first: any corruption anywhere fails here with one clear error.
176    if bytes.len() < MAGIC.len() + 8 {
177        return Err("snapshot: payload too short".into());
178    }
179    let (body, trailer) = bytes.split_at(bytes.len() - 8);
180    let stored = u64::from_le_bytes(trailer.try_into().expect("8-byte trailer"));
181    if fnv1a(body) != stored {
182        return Err("snapshot: payload checksum mismatch (corrupted)".into());
183    }
184    let mut reader = ByteReader {
185        data: body,
186        cursor: 0,
187    };
188    if reader.take(MAGIC.len())? != MAGIC {
189        return Err("snapshot: not a BREP snapshot payload (bad magic)".into());
190    }
191    let version = reader.u32()?;
192    if version != SNAPSHOT_FORMAT_VERSION {
193        return Err(format!(
194            "snapshot: unsupported format version {version} (expected {SNAPSHOT_FORMAT_VERSION})"
195        ));
196    }
197    let solid_count = reader.u32()? as usize;
198    let mut solids = Vec::with_capacity(solid_count.min(1024));
199    for _ in 0..solid_count {
200        let name = reader.string()?;
201        let names_json = reader.string()?;
202        let names: SolidNames = serde_json::from_str(&names_json)
203            .map_err(|error| format!("snapshot: names for '{name}': {error}"))?;
204        let data = reader.f64_vec()?;
205        let solid = decode_solid(&data, &names)
206            .map_err(|error| format!("snapshot: solid '{name}': {error}"))?;
207        solids.push(RestoredSolid { name, solid });
208    }
209    let record_count = reader.u32()? as usize;
210    let mut metadata = Vec::with_capacity(record_count.min(4096));
211    for _ in 0..record_count {
212        let name = reader.string()?;
213        let record_json = reader.string()?;
214        let record: serde_json::Map<String, serde_json::Value> =
215            serde_json::from_str(&record_json)
216                .map_err(|error| format!("snapshot: metadata record for '{name}': {error}"))?;
217        metadata.push((name, record));
218    }
219    if reader.cursor != body.len() {
220        return Err("snapshot: trailing bytes after payload".into());
221    }
222    Ok(RestoredSnapshot { solids, metadata })
223}
224
225// ---------------------------------------------------------------------------
226// Byte framing
227// ---------------------------------------------------------------------------
228
229fn push_u32(out: &mut Vec<u8>, value: u32) {
230    out.extend_from_slice(&value.to_le_bytes());
231}
232
233fn push_count(out: &mut Vec<u8>, count: usize) -> Result<(), String> {
234    let value: u32 = count
235        .try_into()
236        .map_err(|_| format!("snapshot: count {count} exceeds u32"))?;
237    push_u32(out, value);
238    Ok(())
239}
240
241fn push_str(out: &mut Vec<u8>, text: &str) -> Result<(), String> {
242    push_count(out, text.len())?;
243    out.extend_from_slice(text.as_bytes());
244    Ok(())
245}
246
247struct ByteReader<'a> {
248    data: &'a [u8],
249    cursor: usize,
250}
251
252impl<'a> ByteReader<'a> {
253    fn take(&mut self, count: usize) -> Result<&'a [u8], String> {
254        let end = self
255            .cursor
256            .checked_add(count)
257            .ok_or("snapshot: truncated payload")?;
258        let slice = self
259            .data
260            .get(self.cursor..end)
261            .ok_or("snapshot: truncated payload")?;
262        self.cursor = end;
263        Ok(slice)
264    }
265
266    fn u32(&mut self) -> Result<u32, String> {
267        let raw = self.take(4)?;
268        Ok(u32::from_le_bytes([raw[0], raw[1], raw[2], raw[3]]))
269    }
270
271    fn string(&mut self) -> Result<String, String> {
272        let length = self.u32()? as usize;
273        let raw = self.take(length)?;
274        String::from_utf8(raw.to_vec()).map_err(|_| "snapshot: invalid UTF-8 string".into())
275    }
276
277    fn f64_vec(&mut self) -> Result<Vec<f64>, String> {
278        let count = self.u32()? as usize;
279        let raw = self.take(
280            count
281                .checked_mul(8)
282                .ok_or("snapshot: truncated payload")?,
283        )?;
284        Ok(raw
285            .chunks_exact(8)
286            .map(|chunk| {
287                f64::from_le_bytes([
288                    chunk[0], chunk[1], chunk[2], chunk[3], chunk[4], chunk[5], chunk[6], chunk[7],
289                ])
290            })
291            .collect())
292    }
293}
294
295// ---------------------------------------------------------------------------
296// Base64 (standard alphabet, padded) — kept local: the published crate's
297// dependency allowlist stays unchanged, and the decoder must be strict
298// (reject stray characters / bad length / misplaced padding, never panic).
299// ---------------------------------------------------------------------------
300
301const B64_ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
302
303fn base64_encode(bytes: &[u8]) -> String {
304    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
305    for chunk in bytes.chunks(3) {
306        let b0 = chunk[0] as u32;
307        let b1 = chunk.get(1).copied().unwrap_or(0) as u32;
308        let b2 = chunk.get(2).copied().unwrap_or(0) as u32;
309        let triple = (b0 << 16) | (b1 << 8) | b2;
310        out.push(B64_ALPHABET[(triple >> 18) as usize & 63] as char);
311        out.push(B64_ALPHABET[(triple >> 12) as usize & 63] as char);
312        out.push(if chunk.len() > 1 {
313            B64_ALPHABET[(triple >> 6) as usize & 63] as char
314        } else {
315            '='
316        });
317        out.push(if chunk.len() > 2 {
318            B64_ALPHABET[triple as usize & 63] as char
319        } else {
320            '='
321        });
322    }
323    out
324}
325
326fn base64_value(byte: u8) -> Result<u32, String> {
327    match byte {
328        b'A'..=b'Z' => Ok((byte - b'A') as u32),
329        b'a'..=b'z' => Ok((byte - b'a') as u32 + 26),
330        b'0'..=b'9' => Ok((byte - b'0') as u32 + 52),
331        b'+' => Ok(62),
332        b'/' => Ok(63),
333        _ => Err(format!(
334            "snapshot: invalid base64 character 0x{byte:02x}"
335        )),
336    }
337}
338
339fn base64_decode(text: &str) -> Result<Vec<u8>, String> {
340    let bytes = text.as_bytes();
341    if bytes.len() % 4 != 0 {
342        return Err("snapshot: base64 length must be a multiple of 4".into());
343    }
344    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
345    for (index, quad) in bytes.chunks_exact(4).enumerate() {
346        let is_last = (index + 1) * 4 == bytes.len();
347        // Padding is legal only as the final one or two characters.
348        let padding = match (quad[2], quad[3]) {
349            (b'=', b'=') if is_last => 2,
350            (_, b'=') if is_last && quad[2] != b'=' => 1,
351            (b'=', _) => return Err("snapshot: misplaced base64 padding".into()),
352            _ => 0,
353        };
354        if quad[0] == b'=' || quad[1] == b'=' {
355            return Err("snapshot: misplaced base64 padding".into());
356        }
357        let mut triple = base64_value(quad[0])? << 18 | base64_value(quad[1])? << 12;
358        if padding < 2 {
359            triple |= base64_value(quad[2])? << 6;
360        }
361        if padding < 1 {
362            triple |= base64_value(quad[3])?;
363        }
364        out.push((triple >> 16) as u8);
365        if padding < 2 {
366            out.push((triple >> 8) as u8);
367        }
368        if padding < 1 {
369            out.push(triple as u8);
370        }
371    }
372    Ok(out)
373}
374