Deserialize a provenance graph from bytes, returning the graph and its hash. The hash is computed over the input bytes (the entire serialized form).
(data: &[u8])
| 276 | /// |
| 277 | /// The hash is computed over the input bytes (the entire serialized form). |
| 278 | pub fn deserialize(data: &[u8]) -> Result<(Self, Hash), ProvenanceGraphError> { |
| 279 | if data.len() < MAGIC.len() + 1 { |
| 280 | return Err(ProvenanceGraphError::Codec { |
| 281 | reason: format!( |
| 282 | "data too short: {} bytes (minimum {})", |
| 283 | data.len(), |
| 284 | MAGIC.len() + 1 |
| 285 | ), |
| 286 | }); |
| 287 | } |
| 288 | |
| 289 | if &data[..4] != MAGIC { |
| 290 | return Err(ProvenanceGraphError::Codec { |
| 291 | reason: format!("invalid magic: expected {:?}, got {:?}", MAGIC, &data[..4]), |
| 292 | }); |
| 293 | } |
| 294 | |
| 295 | // Peek at the version byte without fully deserializing. |
| 296 | // The first field in the postcard payload is `version: u8`. |
| 297 | let version_byte = data[4]; |
| 298 | |
| 299 | if version_byte > SCHEMA_VERSION { |
| 300 | return Err(ProvenanceGraphError::UnsupportedVersion { |
| 301 | version: version_byte, |
| 302 | max_supported: SCHEMA_VERSION, |
| 303 | }); |
| 304 | } |
| 305 | |
| 306 | let graph: Self = if version_byte <= 1 { |
| 307 | // v1 payload: no `profile` field. Deserialize into the v1 shim |
| 308 | // struct (identical to the current struct minus `profile`) and |
| 309 | // upgrade to v2 in-memory with `profile: None`. |
| 310 | let v1: ProvenanceGraphV1 = |
| 311 | postcard::from_bytes(&data[4..]).map_err(|e| ProvenanceGraphError::Codec { |
| 312 | reason: format!("postcard deserialize failed (v1): {}", e), |
| 313 | })?; |
| 314 | ProvenanceGraph { |
| 315 | version: SCHEMA_VERSION, |
| 316 | timestamp: v1.timestamp, |
| 317 | session_id: v1.session_id, |
| 318 | agent_name: v1.agent_name, |
| 319 | agent_display_name: v1.agent_display_name, |
| 320 | agent_vendor: v1.agent_vendor, |
| 321 | nodes: v1.nodes, |
| 322 | edges: v1.edges, |
| 323 | changes_explained: v1.changes_explained, |
| 324 | previous: v1.previous, |
| 325 | stats: v1.stats, |
| 326 | profile: None, |
| 327 | plan_id: None, |
| 328 | todos: Vec::new(), |
| 329 | } |
| 330 | } else if version_byte == 2 { |
| 331 | let v2: ProvenanceGraphV2 = |
| 332 | postcard::from_bytes(&data[4..]).map_err(|e| ProvenanceGraphError::Codec { |
| 333 | reason: format!("postcard deserialize failed (v2): {}", e), |
| 334 | })?; |
| 335 | ProvenanceGraph { |