Decode a `SessionEnvelope` from `HashedChange.metadata` bytes. Validates the magic prefix and schema version before deserializing. # Errors Returns `AgentError::EnvelopeCodecError` if: - The data is too short - The magic prefix doesn't match - The schema version is unsupported - Postcard deserialization fails
(data: &[u8])
| 252 | /// - The schema version is unsupported |
| 253 | /// - Postcard deserialization fails |
| 254 | pub fn decode(data: &[u8]) -> AgentResult<Self> { |
| 255 | if data.len() < MAGIC.len() + 1 { |
| 256 | return Err(AgentError::EnvelopeCodecError { |
| 257 | reason: format!( |
| 258 | "data too short: {} bytes (minimum {})", |
| 259 | data.len(), |
| 260 | MAGIC.len() + 1 |
| 261 | ), |
| 262 | }); |
| 263 | } |
| 264 | |
| 265 | // Check magic |
| 266 | if &data[..4] != MAGIC { |
| 267 | return Err(AgentError::EnvelopeCodecError { |
| 268 | reason: format!("invalid magic: expected {:?}, got {:?}", MAGIC, &data[..4]), |
| 269 | }); |
| 270 | } |
| 271 | |
| 272 | // Deserialize payload (includes schema_version field) |
| 273 | let envelope: Self = |
| 274 | postcard::from_bytes(&data[4..]).map_err(|e| AgentError::EnvelopeCodecError { |
| 275 | reason: format!("postcard deserialize failed: {}", e), |
| 276 | })?; |
| 277 | |
| 278 | // Check version from the deserialized struct |
| 279 | if envelope.schema_version > SCHEMA_VERSION { |
| 280 | return Err(AgentError::EnvelopeCodecError { |
| 281 | reason: format!( |
| 282 | "unsupported schema version: {} (max supported: {})", |
| 283 | envelope.schema_version, SCHEMA_VERSION |
| 284 | ), |
| 285 | }); |
| 286 | } |
| 287 | |
| 288 | Ok(envelope) |
| 289 | } |
| 290 | |
| 291 | /// Check whether a byte slice looks like a `SessionEnvelope`. |
| 292 | /// |