Skip to main content

oxide_batch_core/
component_state.rs

1//! Bounded, versioned, checksummed component-owned durable state.
2//!
3//! This is the M6 `ItemStream` state contract (Gate C of the M6 design-gate
4//! evidence): a namespaced envelope distinct from [`crate::Checkpoint`] and
5//! [`crate::ExecutionContext`], adding a checksum-before-decode boundary and a
6//! codec identity/version axis that is separate from the application schema
7//! identity/version axis. It reuses [`crate::StateLimits`],
8//! [`crate::StateSchemaId`], [`crate::StateSchemaVersion`],
9//! [`crate::StateSchemaUpgrade`], and [`crate::VersionedStateCodec`] unchanged
10//! for the application-schema axis, and the crate's one schema-upgrade-chain
11//! algorithm ([`crate::state`]'s `upgrade_schema_chain`) rather than a second
12//! migration implementation.
13
14use std::error::Error;
15use std::fmt;
16use std::marker::PhantomData;
17use std::num::NonZeroU32;
18use std::sync::Arc;
19
20use serde_json::Value;
21use sha2::{Digest, Sha256};
22
23use crate::definition::ComponentStreamIdentity;
24use crate::state::{json_depth, upgrade_schema_chain};
25use crate::{
26    DurableStateKind, StateCodecError, StateError, StateLimits, StateSchemaId, StateSchemaVersion,
27    VersionedStateCodec,
28};
29
30const MAX_TOKEN_BYTES: usize = 128;
31/// The most directed codec-version upgrades one decode may apply.
32///
33/// Matches the schema-axis bound in [`crate::state`] so neither axis can be
34/// used to build an unbounded migration chain.
35const MAX_UPGRADE_CHAIN: usize = 64;
36
37/// A validated application-owned codec identifier.
38///
39/// Distinct from [`StateSchemaId`]: the schema axis identifies the
40/// application-level shape of the payload, while the codec axis identifies
41/// the encoding/versioning scheme a component uses to read and write it. The
42/// two must not be conflated -- an unknown codec fails closed independently
43/// of whether the schema is recognized.
44#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
45pub struct CodecId(String);
46
47impl CodecId {
48    /// Validates a stable codec identifier.
49    ///
50    /// # Errors
51    ///
52    /// Returns [`ComponentStateError`] when the identifier is empty, exceeds
53    /// 128 UTF-8 bytes, has surrounding whitespace, or contains a control
54    /// character.
55    pub fn new(value: impl Into<String>) -> Result<Self, ComponentStateError> {
56        let value = value.into();
57        if value.is_empty() {
58            return Err(ComponentStateError::EmptyCodecId);
59        }
60        if value.len() > MAX_TOKEN_BYTES {
61            return Err(ComponentStateError::CodecIdTooLong {
62                max_bytes: MAX_TOKEN_BYTES,
63            });
64        }
65        if value.trim() != value || value.chars().any(char::is_control) {
66            return Err(ComponentStateError::Malformed);
67        }
68        Ok(Self(value))
69    }
70
71    /// Borrows the validated identifier.
72    #[must_use]
73    pub fn as_str(&self) -> &str {
74        &self.0
75    }
76}
77
78impl fmt::Debug for CodecId {
79    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
80        // Codec identity is explicitly safe diagnostic metadata (Gate C), so
81        // this is the one durable-state identity newtype in this crate that
82        // does not redact its Debug output.
83        formatter.debug_tuple("CodecId").field(&self.0).finish()
84    }
85}
86
87impl fmt::Display for CodecId {
88    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
89        formatter.write_str(self.as_str())
90    }
91}
92
93/// A nonzero application codec version.
94#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
95pub struct CodecVersion(NonZeroU32);
96
97impl CodecVersion {
98    /// Constructs a nonzero codec version.
99    ///
100    /// # Errors
101    ///
102    /// Returns [`ComponentStateError::ZeroCodecVersion`] when `value` is zero.
103    pub fn new(value: u32) -> Result<Self, ComponentStateError> {
104        NonZeroU32::new(value)
105            .map(Self)
106            .ok_or(ComponentStateError::ZeroCodecVersion)
107    }
108
109    /// Returns the numeric codec version.
110    #[must_use]
111    pub const fn get(self) -> u32 {
112        self.0.get()
113    }
114}
115
116/// One directed codec-version upgrade a component declares.
117///
118/// Mirrors [`crate::StateSchemaUpgrade`] exactly, on the codec-version axis
119/// rather than the application-schema axis: edges strictly increase the
120/// version and at most one edge may leave any version.
121#[derive(Clone, Copy)]
122pub struct CodecVersionUpgrade {
123    from: CodecVersion,
124    to: CodecVersion,
125    apply: fn(&[u8]) -> Result<Vec<u8>, StateCodecError>,
126}
127
128impl CodecVersionUpgrade {
129    /// Declares a directed upgrade between two codec versions.
130    ///
131    /// # Errors
132    ///
133    /// Returns [`ComponentStateError::NonIncreasingCodecUpgrade`] when `to`
134    /// does not exceed `from`.
135    pub fn new(
136        from: CodecVersion,
137        to: CodecVersion,
138        apply: fn(&[u8]) -> Result<Vec<u8>, StateCodecError>,
139    ) -> Result<Self, ComponentStateError> {
140        if to <= from {
141            return Err(ComponentStateError::NonIncreasingCodecUpgrade);
142        }
143        Ok(Self { from, to, apply })
144    }
145
146    /// Returns the version this upgrade reads.
147    #[must_use]
148    pub const fn from(&self) -> CodecVersion {
149        self.from
150    }
151
152    /// Returns the version this upgrade produces.
153    #[must_use]
154    pub const fn to(&self) -> CodecVersion {
155        self.to
156    }
157}
158
159impl fmt::Debug for CodecVersionUpgrade {
160    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
161        formatter
162            .debug_struct("CodecVersionUpgrade")
163            .field("from", &self.from)
164            .field("to", &self.to)
165            .finish_non_exhaustive()
166    }
167}
168
169/// The checksum algorithm identity and version protecting a component-state
170/// envelope.
171///
172/// Carried as its own versioned field (Gate C) so a future algorithm change is
173/// a migration, not a silent reinterpretation of existing durable bytes.
174#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
175#[non_exhaustive]
176pub enum ChecksumAlgorithm {
177    /// SHA-256 over the canonical checksum input.
178    Sha256,
179}
180
181impl ChecksumAlgorithm {
182    /// The algorithm this build produces for a freshly encoded envelope.
183    pub const CURRENT: Self = Self::Sha256;
184
185    const fn identifier(self) -> u16 {
186        match self {
187            Self::Sha256 => 1,
188        }
189    }
190
191    const fn algorithm_version(self) -> u16 {
192        match self {
193            Self::Sha256 => 1,
194        }
195    }
196
197    const fn resolve(identifier: u16, version: u16) -> Option<Self> {
198        match (identifier, version) {
199            (1, 1) => Some(Self::Sha256),
200            _ => None,
201        }
202    }
203
204    fn digest(self, input: &[u8]) -> [u8; 32] {
205        match self {
206            Self::Sha256 => Sha256::digest(input).into(),
207        }
208    }
209}
210
211/// Declared sensitivity of one component's durable-state contract.
212///
213/// One source of truth: this is declared once by
214/// [`ComponentStateCodec::sensitivity`] and is never duplicated as a second,
215/// independently maintained envelope field. Absent an explicit non-sensitive
216/// declaration, component state is [`Self::Sensitive`] (fail-safe).
217#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
218#[non_exhaustive]
219pub enum StateSensitivity {
220    /// The state's payload must never appear in diagnostics.
221    #[default]
222    Sensitive,
223    /// The component has explicitly declared its payload safe to surface in
224    /// authorized diagnostic projections.
225    NonSensitive,
226}
227
228/// Whether a component can honestly claim restartability.
229///
230/// Independent of whether a *reader* checkpoint exists: a component with
231/// required durable state that cannot be reconstructed must not be marked
232/// restartable merely because the reader's own checkpoint is present.
233#[derive(Clone, Copy, Debug, Eq, PartialEq)]
234#[non_exhaustive]
235pub enum RestartabilityDeclaration {
236    /// No required state, or required state is durably persisted or fully
237    /// reconstructible without persistence.
238    Restartable,
239    /// Required state exists, persistence is disabled or unavailable, and the
240    /// state is not reconstructible.
241    NotRestartable,
242}
243
244/// A content-identified pointer to an external state blob.
245///
246/// Opaque bytes, not a payload: this is a hash, never the sensitive state
247/// itself, so it is safe to display.
248#[derive(Clone, Copy, Eq, Hash, PartialEq)]
249pub struct ContentIdentity([u8; 32]);
250
251impl ContentIdentity {
252    /// Constructs a content identity from its raw bytes.
253    #[must_use]
254    pub const fn from_bytes(bytes: [u8; 32]) -> Self {
255        Self(bytes)
256    }
257
258    /// Returns the SHA-256 content identity of `bytes`.
259    #[must_use]
260    pub fn of(bytes: &[u8]) -> Self {
261        Self(Sha256::digest(bytes).into())
262    }
263
264    /// Borrows the raw content-identity bytes.
265    #[must_use]
266    pub const fn as_bytes(&self) -> &[u8; 32] {
267        &self.0
268    }
269}
270
271impl fmt::Debug for ContentIdentity {
272    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
273        write!(formatter, "ContentIdentity({})", hex_encode(&self.0))
274    }
275}
276
277fn hex_encode(bytes: &[u8]) -> String {
278    use fmt::Write as _;
279    let mut out = String::with_capacity(bytes.len() * 2);
280    for byte in bytes {
281        let _ = write!(out, "{byte:02x}");
282    }
283    out
284}
285
286/// A bounded reference to a large component-state blob held outside the
287/// durable envelope's inline metadata.
288///
289/// No adapter (S3, Azure, GCS, ...) ships with this contract; `#144` provides
290/// only the capability/model boundary an adapter would later implement
291/// against.
292#[derive(Clone, Copy, Debug, Eq, PartialEq)]
293pub struct ExternalStateReference {
294    content_id: ContentIdentity,
295    encoded_len: u64,
296}
297
298impl ExternalStateReference {
299    /// Constructs a bounded external-state reference.
300    #[must_use]
301    pub const fn new(content_id: ContentIdentity, encoded_len: u64) -> Self {
302        Self {
303            content_id,
304            encoded_len,
305        }
306    }
307
308    /// Returns the content identity of the referenced blob.
309    #[must_use]
310    pub const fn content_id(&self) -> ContentIdentity {
311        self.content_id
312    }
313
314    /// Returns the declared encoded length of the referenced blob.
315    #[must_use]
316    pub const fn encoded_len(&self) -> u64 {
317        self.encoded_len
318    }
319
320    /// Verifies that resolved bytes match this reference's declared content
321    /// identity.
322    ///
323    /// A caller resolving an external reference through an
324    /// [`ExternalStateStore`] must call this before trusting the resolved
325    /// bytes: missing content is [`ExternalStateError::ContentMissing`] from
326    /// the store itself, while resolved-but-mismatched content is caught
327    /// here rather than silently accepted.
328    ///
329    /// # Errors
330    ///
331    /// Returns [`ComponentStateError::ExternalReferenceContentMismatch`] when
332    /// `bytes`'s content identity does not match [`Self::content_id`].
333    pub fn verify(&self, bytes: &[u8]) -> Result<(), ComponentStateError> {
334        if ContentIdentity::of(bytes) == self.content_id {
335            Ok(())
336        } else {
337            Err(ComponentStateError::ExternalReferenceContentMismatch)
338        }
339    }
340}
341
342/// A capability an adapter may implement to resolve and store external
343/// component state.
344///
345/// ADR-0008-shaped: a generic trait with an explicit call lifetime and an
346/// opaque future return, matching the item-component contract's conventions.
347/// No concrete adapter ships with `#144`.
348pub trait ExternalStateStore: Send + Sync {
349    /// Resolves the bytes a reference identifies.
350    ///
351    /// # Errors
352    ///
353    /// Returns [`ExternalStateError::ContentMissing`] when the referenced
354    /// content cannot be found, or
355    /// [`ExternalStateError::ContentMismatch`] when the resolved bytes do not
356    /// match the declared content identity.
357    fn resolve<'a>(
358        &'a self,
359        reference: &'a ExternalStateReference,
360    ) -> impl Future<Output = Result<Vec<u8>, ExternalStateError>> + Send + 'a;
361
362    /// Stores `bytes` and returns their bounded, content-identified reference.
363    ///
364    /// # Errors
365    ///
366    /// Returns [`ExternalStateError::StoreFailed`] when the adapter cannot
367    /// durably retain the bytes.
368    fn store<'a>(
369        &'a self,
370        bytes: &'a [u8],
371    ) -> impl Future<Output = Result<ExternalStateReference, ExternalStateError>> + Send + 'a;
372}
373
374/// Stable, value-redacted external-state-store failure.
375#[derive(Clone, Copy, Debug, Eq, PartialEq)]
376#[non_exhaustive]
377pub enum ExternalStateError {
378    /// The referenced content does not exist in the store.
379    ContentMissing,
380    /// The resolved bytes do not match the declared content identity.
381    ContentMismatch,
382    /// The store could not durably retain the supplied bytes.
383    StoreFailed,
384}
385
386impl fmt::Display for ExternalStateError {
387    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
388        formatter.write_str(match self {
389            Self::ContentMissing => "external component state content is missing",
390            Self::ContentMismatch => "external component state content identity mismatch",
391            Self::StoreFailed => "external component state store failed",
392        })
393    }
394}
395
396impl Error for ExternalStateError {}
397
398/// The bounded representation a component-state payload unambiguously is.
399///
400/// Never a silent third, unbounded form: a payload is either inline bytes
401/// bounded by [`StateLimits`], or a bounded external reference identified by
402/// content identity.
403#[derive(Clone, Debug, Eq, PartialEq)]
404pub enum ComponentStatePayload {
405    /// Bounded inline payload bytes (an encoded JSON object).
406    Inline(Vec<u8>),
407    /// A bounded external reference to out-of-band state.
408    External(ExternalStateReference),
409}
410
411#[derive(Clone, Eq, PartialEq)]
412enum StoredPayload {
413    /// The exact codec-produced bytes, never reserialized through
414    /// [`serde_json::Value`].
415    ///
416    /// Holding a parsed `Value` here (the M6 PR's original shape) let two
417    /// byte-identical-in-meaning-but-not-in-bytes encodings (whitespace, key
418    /// order) silently change the bytes a later checksum or decode observed.
419    /// Retaining the raw bytes exactly is what makes the checksum in
420    /// [`ComponentStateEnvelope`] a checksum of what is actually returned by
421    /// [`ComponentStateEnvelope::payload`] and consumed by
422    /// [`ComponentStateEnvelope::decode`], not of a re-encoding of it.
423    Inline(Vec<u8>),
424    External(ExternalStateReference),
425}
426
427/// The full durable envelope for one committed component-state namespace.
428///
429/// Every identity field is validated, and the checksum is verified against
430/// the raw payload bytes, before any application decode or migration step
431/// runs.
432#[derive(Clone, Eq, PartialEq)]
433pub struct ComponentStateEnvelope {
434    namespace: ComponentStreamIdentity,
435    schema_id: StateSchemaId,
436    schema_version: StateSchemaVersion,
437    codec_id: CodecId,
438    codec_version: CodecVersion,
439    checksum_algorithm: ChecksumAlgorithm,
440    checksum: [u8; 32],
441    payload: StoredPayload,
442    encoded_len: usize,
443}
444
445fn canonical_checksum_input(
446    namespace: &ComponentStreamIdentity,
447    schema_id: &StateSchemaId,
448    schema_version: StateSchemaVersion,
449    codec_id: &CodecId,
450    codec_version: CodecVersion,
451    payload_marker: &[u8],
452) -> Vec<u8> {
453    let mut input = Vec::with_capacity(64 + payload_marker.len());
454    input.extend_from_slice(b"oxide-batch.component-state\0");
455    input.extend_from_slice(namespace.as_str().as_bytes());
456    input.push(0);
457    input.extend_from_slice(schema_id.as_str().as_bytes());
458    input.push(0);
459    input.extend_from_slice(&schema_version.get().to_be_bytes());
460    input.extend_from_slice(codec_id.as_str().as_bytes());
461    input.push(0);
462    input.extend_from_slice(&codec_version.get().to_be_bytes());
463    input.extend_from_slice(payload_marker);
464    input
465}
466
467fn inline_payload_marker(bytes: &[u8]) -> Vec<u8> {
468    let mut marker = Vec::with_capacity(1 + bytes.len());
469    marker.push(0);
470    marker.extend_from_slice(bytes);
471    marker
472}
473
474fn external_payload_marker(reference: &ExternalStateReference) -> Vec<u8> {
475    let mut marker = Vec::with_capacity(1 + 32 + 8);
476    marker.push(1);
477    marker.extend_from_slice(reference.content_id().as_bytes());
478    marker.extend_from_slice(&reference.encoded_len().to_be_bytes());
479    marker
480}
481
482/// Holds a payload produced by a declared codec-version upgrade to the
483/// envelope's own shape and to the durable hard ceilings.
484///
485/// Mirrors [`crate::state`]'s `check_upgraded` on the codec-version axis: an
486/// upgrade is application code running between two framework checks, so a
487/// transform that returns a non-object, invalid JSON, or an unbounded payload
488/// fails here rather than reaching the codec.
489fn check_upgraded_component_state(payload: &[u8]) -> Result<(), ComponentStateError> {
490    const HARD_MAXIMUM_BYTES: usize = 1024 * 1024;
491    const HARD_MAXIMUM_DEPTH: usize = 64;
492    if payload.len() > HARD_MAXIMUM_BYTES {
493        return Err(ComponentStateError::TooLarge {
494            max_bytes: HARD_MAXIMUM_BYTES,
495        });
496    }
497    let value: Value =
498        serde_json::from_slice(payload).map_err(|_| ComponentStateError::PayloadNotObject)?;
499    if !value.is_object() {
500        return Err(ComponentStateError::PayloadNotObject);
501    }
502    if json_depth(&value) > HARD_MAXIMUM_DEPTH {
503        return Err(ComponentStateError::TooDeep {
504            max_depth: HARD_MAXIMUM_DEPTH,
505        });
506    }
507    Ok(())
508}
509
510fn upgrade_codec_chain<T>(
511    recorded: CodecVersion,
512    codec: &(impl ComponentStateCodec<T> + ?Sized),
513    mut payload: Vec<u8>,
514) -> Result<Vec<u8>, ComponentStateError> {
515    let current = codec.codec_version();
516    let upgrades = codec.codec_upgrades();
517    let mut version = recorded;
518    let mut applied = 0_usize;
519    while version < current {
520        let mut edges = upgrades.iter().filter(|upgrade| upgrade.from == version);
521        let edge = edges
522            .next()
523            .ok_or(ComponentStateError::NoCodecUpgradePath {
524                found: version.get(),
525                current: current.get(),
526            })?;
527        if edges.next().is_some() {
528            return Err(ComponentStateError::AmbiguousCodecUpgrade {
529                from: version.get(),
530            });
531        }
532        if edge.to > current {
533            return Err(ComponentStateError::CodecUpgradeOvershootsCurrent {
534                to: edge.to.get(),
535                current: current.get(),
536            });
537        }
538        applied += 1;
539        if applied > MAX_UPGRADE_CHAIN {
540            return Err(ComponentStateError::CodecUpgradeChainTooLong {
541                max_upgrades: MAX_UPGRADE_CHAIN,
542            });
543        }
544        payload = (edge.apply)(&payload).map_err(ComponentStateError::Codec)?;
545        check_upgraded_component_state(&payload)?;
546        version = edge.to;
547    }
548    Ok(payload)
549}
550
551fn map_schema_chain_error(error: &StateError) -> ComponentStateError {
552    match error {
553        StateError::SchemaMismatch { .. } => ComponentStateError::SchemaMismatch,
554        StateError::UnsupportedSchemaVersion { found, current, .. } => {
555            ComponentStateError::UnsupportedSchemaVersion {
556                found: found.get(),
557                current: current.get(),
558            }
559        }
560        StateError::NoUpgradePath { found, current, .. } => {
561            ComponentStateError::NoSchemaUpgradePath {
562                found: found.get(),
563                current: current.get(),
564            }
565        }
566        StateError::AmbiguousUpgrade { from, .. } => {
567            ComponentStateError::AmbiguousSchemaUpgrade { from: from.get() }
568        }
569        StateError::UpgradeOvershootsCurrent { to, current, .. } => {
570            ComponentStateError::SchemaUpgradeOvershootsCurrent {
571                to: to.get(),
572                current: current.get(),
573            }
574        }
575        StateError::UpgradeChainTooLong { max_upgrades, .. } => {
576            ComponentStateError::SchemaUpgradeChainTooLong {
577                max_upgrades: *max_upgrades,
578            }
579        }
580        StateError::TooLarge { max_bytes, .. } => ComponentStateError::TooLarge {
581            max_bytes: *max_bytes,
582        },
583        StateError::TooDeep { max_depth, .. } => ComponentStateError::TooDeep {
584            max_depth: *max_depth,
585        },
586        StateError::Codec(inner) => ComponentStateError::Codec(*inner),
587        _ => ComponentStateError::Malformed,
588    }
589}
590
591impl ComponentStateEnvelope {
592    /// Encodes a current typed value as a bounded inline envelope.
593    ///
594    /// Never falls back to an external reference: an oversized or over-deep
595    /// candidate fails rather than being silently inlined or silently stored
596    /// elsewhere. A caller that wants external representation constructs one
597    /// explicitly with [`Self::external`].
598    ///
599    /// # Errors
600    ///
601    /// Returns a redacted codec, bounds, or shape failure.
602    pub fn encode<T>(
603        namespace: ComponentStreamIdentity,
604        value: &T,
605        codec: &(impl ComponentStateCodec<T> + ?Sized),
606        limits: StateLimits,
607    ) -> Result<Self, ComponentStateError> {
608        let payload_bytes = codec.encode(value).map_err(ComponentStateError::Codec)?;
609        if payload_bytes.len() > limits.maximum_bytes() {
610            return Err(ComponentStateError::TooLarge {
611                max_bytes: limits.maximum_bytes(),
612            });
613        }
614        let schema_id = codec.schema_id().clone();
615        let schema_version = codec.current_version();
616        let codec_id = codec.codec_id().clone();
617        let codec_version = codec.codec_version();
618        let checksum_algorithm = ChecksumAlgorithm::CURRENT;
619        let checksum = checksum_algorithm.digest(&canonical_checksum_input(
620            &namespace,
621            &schema_id,
622            schema_version,
623            &codec_id,
624            codec_version,
625            &inline_payload_marker(&payload_bytes),
626        ));
627        let payload_value: Value = serde_json::from_slice(&payload_bytes)
628            .map_err(|_| ComponentStateError::InvalidPayload)?;
629        if !payload_value.is_object() {
630            return Err(ComponentStateError::PayloadNotObject);
631        }
632        if json_depth(&payload_value) > limits.maximum_depth() {
633            return Err(ComponentStateError::TooDeep {
634                max_depth: limits.maximum_depth(),
635            });
636        }
637        let encoded_len = payload_bytes.len();
638        Ok(Self {
639            namespace,
640            schema_id,
641            schema_version,
642            codec_id,
643            codec_version,
644            checksum_algorithm,
645            checksum,
646            payload: StoredPayload::Inline(payload_bytes),
647            encoded_len,
648        })
649    }
650
651    /// Constructs a validated inline envelope from already-transformed payload bytes.
652    ///
653    /// The compatible-upgrade path uses this after the selected pure
654    /// transformer returns. Codec identity/version are preserved while the
655    /// application schema identity/version and checksum move to the declared
656    /// target contract.
657    ///
658    /// # Errors
659    ///
660    /// Returns a redacted bounds or JSON-shape failure.
661    #[doc(hidden)]
662    pub fn from_transformed_inline(
663        source: &Self,
664        schema_id: StateSchemaId,
665        schema_version: StateSchemaVersion,
666        payload: Vec<u8>,
667        limits: StateLimits,
668    ) -> Result<Self, ComponentStateError> {
669        if source.is_external() {
670            return Err(ComponentStateError::Malformed);
671        }
672        if payload.len() > limits.maximum_bytes() {
673            return Err(ComponentStateError::TooLarge {
674                max_bytes: limits.maximum_bytes(),
675            });
676        }
677        let payload_value: Value =
678            serde_json::from_slice(&payload).map_err(|_| ComponentStateError::InvalidPayload)?;
679        if !payload_value.is_object() {
680            return Err(ComponentStateError::PayloadNotObject);
681        }
682        if json_depth(&payload_value) > limits.maximum_depth() {
683            return Err(ComponentStateError::TooDeep {
684                max_depth: limits.maximum_depth(),
685            });
686        }
687        let checksum_algorithm = source.checksum_algorithm;
688        let checksum = checksum_algorithm.digest(&canonical_checksum_input(
689            &source.namespace,
690            &schema_id,
691            schema_version,
692            &source.codec_id,
693            source.codec_version,
694            &inline_payload_marker(&payload),
695        ));
696        let encoded_len = payload.len();
697        Ok(Self {
698            namespace: source.namespace.clone(),
699            schema_id,
700            schema_version,
701            codec_id: source.codec_id.clone(),
702            codec_version: source.codec_version,
703            checksum_algorithm,
704            checksum,
705            payload: StoredPayload::Inline(payload),
706            encoded_len,
707        })
708    }
709
710    /// Constructs an envelope wrapping an already-stored external reference.
711    ///
712    /// The caller is responsible for having already stored the bytes through
713    /// an [`ExternalStateStore`] and for supplying the identity/version the
714    /// reference was encoded under.
715    #[must_use]
716    pub fn external(
717        namespace: ComponentStreamIdentity,
718        schema_id: StateSchemaId,
719        schema_version: StateSchemaVersion,
720        codec_id: CodecId,
721        codec_version: CodecVersion,
722        reference: ExternalStateReference,
723    ) -> Self {
724        let checksum_algorithm = ChecksumAlgorithm::CURRENT;
725        let checksum = checksum_algorithm.digest(&canonical_checksum_input(
726            &namespace,
727            &schema_id,
728            schema_version,
729            &codec_id,
730            codec_version,
731            &external_payload_marker(&reference),
732        ));
733        Self {
734            namespace,
735            schema_id,
736            schema_version,
737            codec_id,
738            codec_version,
739            checksum_algorithm,
740            checksum,
741            payload: StoredPayload::External(reference),
742            encoded_len: 0,
743        }
744    }
745
746    /// Validates raw durable columns and reconstructs an undecoded envelope.
747    ///
748    /// The checksum is verified against the raw payload bytes before any JSON
749    /// parsing, schema/codec compatibility check, or migration step runs. A
750    /// mismatch never invokes decode, never invokes migration, and never
751    /// substitutes empty or default state.
752    ///
753    /// # Errors
754    ///
755    /// Returns a redacted identity, checksum, bounds, or shape failure.
756    #[allow(clippy::too_many_arguments)]
757    pub fn from_durable(
758        namespace: ComponentStreamIdentity,
759        schema_id: &str,
760        schema_version: u32,
761        codec_id: &str,
762        codec_version: u32,
763        checksum_algorithm: u16,
764        checksum_algorithm_version: u16,
765        checksum: [u8; 32],
766        payload: ComponentStatePayload,
767        limits: StateLimits,
768    ) -> Result<Self, ComponentStateError> {
769        let schema_id =
770            StateSchemaId::new(schema_id).map_err(|_| ComponentStateError::Malformed)?;
771        let schema_version =
772            StateSchemaVersion::new(schema_version).map_err(|_| ComponentStateError::Malformed)?;
773        let codec_id = CodecId::new(codec_id)?;
774        let codec_version = CodecVersion::new(codec_version)?;
775        let algorithm = ChecksumAlgorithm::resolve(checksum_algorithm, checksum_algorithm_version)
776            .ok_or(ComponentStateError::ChecksumAlgorithmUnsupported {
777                algorithm: checksum_algorithm,
778                version: checksum_algorithm_version,
779            })?;
780
781        let (marker, size_check) = match &payload {
782            ComponentStatePayload::Inline(bytes) => {
783                (inline_payload_marker(bytes), Some(bytes.len()))
784            }
785            ComponentStatePayload::External(reference) => {
786                (external_payload_marker(reference), None)
787            }
788        };
789        if let Some(len) = size_check
790            && len > limits.maximum_bytes()
791        {
792            return Err(ComponentStateError::TooLarge {
793                max_bytes: limits.maximum_bytes(),
794            });
795        }
796
797        // Checksum is verified here, against the raw bytes, before any JSON
798        // parse, schema/codec match, or migration step below.
799        let expected = algorithm.digest(&canonical_checksum_input(
800            &namespace,
801            &schema_id,
802            schema_version,
803            &codec_id,
804            codec_version,
805            &marker,
806        ));
807        if expected != checksum {
808            return Err(ComponentStateError::ChecksumMismatch);
809        }
810
811        let (stored, encoded_len) = match payload {
812            ComponentStatePayload::Inline(bytes) => {
813                let value: Value =
814                    serde_json::from_slice(&bytes).map_err(|_| ComponentStateError::Malformed)?;
815                if !value.is_object() {
816                    return Err(ComponentStateError::PayloadNotObject);
817                }
818                if json_depth(&value) > limits.maximum_depth() {
819                    return Err(ComponentStateError::TooDeep {
820                        max_depth: limits.maximum_depth(),
821                    });
822                }
823                let encoded_len = bytes.len();
824                (StoredPayload::Inline(bytes), encoded_len)
825            }
826            ComponentStatePayload::External(reference) => (StoredPayload::External(reference), 0),
827        };
828
829        Ok(Self {
830            namespace,
831            schema_id,
832            schema_version,
833            codec_id,
834            codec_version,
835            checksum_algorithm: algorithm,
836            checksum,
837            payload: stored,
838            encoded_len,
839        })
840    }
841
842    /// Decodes the retained inline payload through `codec`.
843    ///
844    /// Applies the schema-axis migration chain (delegated to the same
845    /// algorithm [`crate::Checkpoint`]/[`crate::ExecutionContext`] use) and
846    /// then the codec-version migration chain, in that order, before calling
847    /// the codec's own decode.
848    ///
849    /// # Errors
850    ///
851    /// Returns [`ComponentStateError::ExternalReferenceMissing`] when the
852    /// payload is an unresolved external reference (resolve it through an
853    /// [`ExternalStateStore`] and decode the resolved bytes with the
854    /// component's own codec instead), or a redacted identity,
855    /// compatibility, or codec failure.
856    pub fn decode<T>(
857        &self,
858        codec: &(impl ComponentStateCodec<T> + ?Sized),
859    ) -> Result<T, ComponentStateError> {
860        if self.codec_id != *codec.codec_id() {
861            return Err(ComponentStateError::UnknownCodec);
862        }
863        if self.schema_id != *codec.schema_id() {
864            return Err(ComponentStateError::SchemaMismatch);
865        }
866        let current_schema = codec.current_version();
867        if self.schema_version > current_schema {
868            return Err(ComponentStateError::UnsupportedSchemaVersion {
869                found: self.schema_version.get(),
870                current: current_schema.get(),
871            });
872        }
873        let current_codec = codec.codec_version();
874        if self.codec_version > current_codec {
875            return Err(ComponentStateError::UnsupportedCodecVersion {
876                found: self.codec_version.get(),
877                current: current_codec.get(),
878            });
879        }
880        let Self {
881            payload: StoredPayload::Inline(bytes),
882            ..
883        } = self
884        else {
885            return Err(ComponentStateError::ExternalReferenceMissing);
886        };
887        let payload_bytes = bytes.clone();
888        let payload_bytes = upgrade_schema_chain(
889            DurableStateKind::ComponentState,
890            self.schema_version,
891            codec,
892            payload_bytes,
893        )
894        .map_err(|error| map_schema_chain_error(&error))?;
895        let payload_bytes = upgrade_codec_chain(self.codec_version, codec, payload_bytes)?;
896        codec
897            .decode(&payload_bytes)
898            .map_err(ComponentStateError::Codec)
899    }
900
901    /// Validates and migrates this envelope to `codec`'s current schema and
902    /// codec versions, without decoding to an application type.
903    ///
904    /// This is the pre-`open` enforcement point (Gate C): the runtime calls
905    /// this through a registered stream's [`StreamStateContract`] before
906    /// [`crate::ItemStream::open`](../oxide_batch/trait.ItemStream.html#tymethod.open)
907    /// ever runs, so an unknown/newer schema or codec, or a migration
908    /// failure, is rejected before any application code sees the envelope.
909    /// An external-reference payload has no inline bytes to migrate. Current
910    /// schema and codec versions are accepted; older external versions fail
911    /// closed until a resolution/migration capability exists.
912    ///
913    /// # Errors
914    ///
915    /// Returns a redacted identity, compatibility, or migration failure
916    /// without invoking the codec's own decode step. Older external schema or
917    /// codec versions report that external migration is unsupported because
918    /// this method cannot resolve their out-of-band bytes.
919    pub fn validated_for_open<T>(
920        &self,
921        codec: &(impl ComponentStateCodec<T> + ?Sized),
922    ) -> Result<Self, ComponentStateError> {
923        if self.codec_id != *codec.codec_id() {
924            return Err(ComponentStateError::UnknownCodec);
925        }
926        if self.schema_id != *codec.schema_id() {
927            return Err(ComponentStateError::SchemaMismatch);
928        }
929        let current_schema = codec.current_version();
930        if self.schema_version > current_schema {
931            return Err(ComponentStateError::UnsupportedSchemaVersion {
932                found: self.schema_version.get(),
933                current: current_schema.get(),
934            });
935        }
936        let current_codec = codec.codec_version();
937        if self.codec_version > current_codec {
938            return Err(ComponentStateError::UnsupportedCodecVersion {
939                found: self.codec_version.get(),
940                current: current_codec.get(),
941            });
942        }
943        if matches!(self.payload, StoredPayload::External(_)) {
944            if self.schema_version < current_schema {
945                return Err(ComponentStateError::ExternalSchemaMigrationUnsupported {
946                    found: self.schema_version.get(),
947                    current: current_schema.get(),
948                });
949            }
950            if self.codec_version < current_codec {
951                return Err(ComponentStateError::ExternalCodecMigrationUnsupported {
952                    found: self.codec_version.get(),
953                    current: current_codec.get(),
954                });
955            }
956            return Ok(self.clone());
957        }
958        let Self {
959            payload: StoredPayload::Inline(bytes),
960            ..
961        } = self
962        else {
963            return Ok(self.clone());
964        };
965        let migrated = upgrade_schema_chain(
966            DurableStateKind::ComponentState,
967            self.schema_version,
968            codec,
969            bytes.clone(),
970        )
971        .map_err(|error| map_schema_chain_error(&error))?;
972        let migrated = upgrade_codec_chain(self.codec_version, codec, migrated)?;
973        if migrated == *bytes {
974            return Ok(self.clone());
975        }
976        let checksum_algorithm = ChecksumAlgorithm::CURRENT;
977        let checksum = checksum_algorithm.digest(&canonical_checksum_input(
978            &self.namespace,
979            &self.schema_id,
980            current_schema,
981            &self.codec_id,
982            current_codec,
983            &inline_payload_marker(&migrated),
984        ));
985        let encoded_len = migrated.len();
986        Ok(Self {
987            namespace: self.namespace.clone(),
988            schema_id: self.schema_id.clone(),
989            schema_version: current_schema,
990            codec_id: self.codec_id.clone(),
991            codec_version: current_codec,
992            checksum_algorithm,
993            checksum,
994            payload: StoredPayload::Inline(migrated),
995            encoded_len,
996        })
997    }
998
999    /// Borrows the owner-scoped namespace.
1000    #[must_use]
1001    pub const fn namespace(&self) -> &ComponentStreamIdentity {
1002        &self.namespace
1003    }
1004
1005    /// Borrows the validated application schema identifier.
1006    #[must_use]
1007    pub const fn schema_id(&self) -> &StateSchemaId {
1008        &self.schema_id
1009    }
1010
1011    /// Returns the retained application schema version.
1012    #[must_use]
1013    pub const fn schema_version(&self) -> StateSchemaVersion {
1014        self.schema_version
1015    }
1016
1017    /// Borrows the validated codec identifier.
1018    #[must_use]
1019    pub const fn codec_id(&self) -> &CodecId {
1020        &self.codec_id
1021    }
1022
1023    /// Returns the retained codec version.
1024    #[must_use]
1025    pub const fn codec_version(&self) -> CodecVersion {
1026        self.codec_version
1027    }
1028
1029    /// Returns whether this envelope's payload is inline or external.
1030    #[must_use]
1031    pub const fn is_external(&self) -> bool {
1032        matches!(self.payload, StoredPayload::External(_))
1033    }
1034
1035    /// Returns the checksum algorithm identifier protecting this envelope.
1036    #[must_use]
1037    pub const fn checksum_algorithm(&self) -> u16 {
1038        self.checksum_algorithm.identifier()
1039    }
1040
1041    /// Returns the checksum algorithm version protecting this envelope.
1042    #[must_use]
1043    pub const fn checksum_algorithm_version(&self) -> u16 {
1044        self.checksum_algorithm.algorithm_version()
1045    }
1046
1047    /// Returns the checksum value protecting this envelope.
1048    ///
1049    /// An authorized persistence adapter uses this alongside
1050    /// [`Self::checksum_algorithm`]/[`Self::checksum_algorithm_version`] to
1051    /// write the durable checksum column; [`Self::from_durable`] recomputes
1052    /// and verifies it from the same inputs on read.
1053    #[must_use]
1054    pub const fn checksum(&self) -> [u8; 32] {
1055        self.checksum
1056    }
1057
1058    /// Returns the bounded payload representation an authorized persistence
1059    /// adapter durably stores.
1060    ///
1061    /// # Errors
1062    ///
1063    /// Returns a redacted format failure if the retained inline value cannot
1064    /// be serialized. This does not happen for a payload this type itself
1065    /// already validated.
1066    pub fn payload(&self) -> Result<ComponentStatePayload, ComponentStateError> {
1067        match &self.payload {
1068            StoredPayload::Inline(bytes) => Ok(ComponentStatePayload::Inline(bytes.clone())),
1069            StoredPayload::External(reference) => Ok(ComponentStatePayload::External(*reference)),
1070        }
1071    }
1072
1073    /// Returns the validated inline payload byte size, or the declared
1074    /// external blob size.
1075    #[must_use]
1076    pub fn encoded_len(&self) -> usize {
1077        match &self.payload {
1078            StoredPayload::External(reference) => {
1079                usize::try_from(reference.encoded_len()).unwrap_or(usize::MAX)
1080            }
1081            StoredPayload::Inline(_) => self.encoded_len,
1082        }
1083    }
1084}
1085
1086impl fmt::Debug for ComponentStateEnvelope {
1087    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1088        formatter
1089            .debug_struct("ComponentStateEnvelope")
1090            .field("namespace", &self.namespace)
1091            .field("schema_id", &self.schema_id)
1092            .field("schema_version", &self.schema_version)
1093            .field("codec_id", &self.codec_id)
1094            .field("codec_version", &self.codec_version)
1095            .field("checksum_algorithm", &self.checksum_algorithm)
1096            .field("checksum", &"<redacted>")
1097            .field("is_external", &self.is_external())
1098            .field("encoded_len", &self.encoded_len())
1099            .field("payload", &"<redacted>")
1100            .finish()
1101    }
1102}
1103
1104/// A component-state codec: the application-schema axis (via the
1105/// [`VersionedStateCodec`] supertrait) plus the codec identity/version axis,
1106/// sensitivity classification, and restartability declaration.
1107///
1108/// Any existing [`VersionedStateCodec`] implementation becomes a
1109/// `ComponentStateCodec` unchanged by wrapping it in [`DefaultComponentCodec`]
1110/// -- this trait is additive, not a replacement.
1111pub trait ComponentStateCodec<T>: VersionedStateCodec<T> {
1112    /// Returns the stable codec identifier.
1113    fn codec_id(&self) -> &CodecId;
1114
1115    /// Returns the version emitted when encoding.
1116    fn codec_version(&self) -> CodecVersion;
1117
1118    /// Declares the directed codec-version upgrades this codec can apply.
1119    fn codec_upgrades(&self) -> &[CodecVersionUpgrade] {
1120        &[]
1121    }
1122
1123    /// Declares this component's state sensitivity.
1124    ///
1125    /// Defaults to [`StateSensitivity::Sensitive`] (fail-safe).
1126    fn sensitivity(&self) -> StateSensitivity {
1127        StateSensitivity::Sensitive
1128    }
1129
1130    /// Declares whether this component can honestly claim restartability.
1131    fn restartability(&self) -> RestartabilityDeclaration;
1132}
1133
1134/// Wraps an existing [`VersionedStateCodec`] as a [`ComponentStateCodec`]
1135/// without requiring a second codec implementation.
1136pub struct DefaultComponentCodec<C> {
1137    schema: C,
1138    codec_id: CodecId,
1139    codec_version: CodecVersion,
1140    codec_upgrades: Vec<CodecVersionUpgrade>,
1141    sensitivity: StateSensitivity,
1142    restartability: RestartabilityDeclaration,
1143}
1144
1145impl<C> DefaultComponentCodec<C> {
1146    /// Wraps `schema` with the codec identity/version and restartability
1147    /// declaration this component requires.
1148    #[must_use]
1149    pub const fn new(
1150        schema: C,
1151        codec_id: CodecId,
1152        codec_version: CodecVersion,
1153        restartability: RestartabilityDeclaration,
1154    ) -> Self {
1155        Self {
1156            schema,
1157            codec_id,
1158            codec_version,
1159            codec_upgrades: Vec::new(),
1160            sensitivity: StateSensitivity::Sensitive,
1161            restartability,
1162        }
1163    }
1164
1165    /// Declares the directed codec-version upgrades this codec can apply.
1166    #[must_use]
1167    pub fn with_codec_upgrades(mut self, upgrades: Vec<CodecVersionUpgrade>) -> Self {
1168        self.codec_upgrades = upgrades;
1169        self
1170    }
1171
1172    /// Declares this component's state sensitivity.
1173    #[must_use]
1174    pub const fn with_sensitivity(mut self, sensitivity: StateSensitivity) -> Self {
1175        self.sensitivity = sensitivity;
1176        self
1177    }
1178}
1179
1180impl<T, C: VersionedStateCodec<T>> VersionedStateCodec<T> for DefaultComponentCodec<C> {
1181    fn schema_id(&self) -> &StateSchemaId {
1182        self.schema.schema_id()
1183    }
1184
1185    fn current_version(&self) -> StateSchemaVersion {
1186        self.schema.current_version()
1187    }
1188
1189    fn upgrades(&self) -> &[crate::StateSchemaUpgrade] {
1190        self.schema.upgrades()
1191    }
1192
1193    fn encode(&self, value: &T) -> Result<Vec<u8>, StateCodecError> {
1194        self.schema.encode(value)
1195    }
1196
1197    fn decode(&self, payload: &[u8]) -> Result<T, StateCodecError> {
1198        self.schema.decode(payload)
1199    }
1200}
1201
1202impl<T, C: VersionedStateCodec<T>> ComponentStateCodec<T> for DefaultComponentCodec<C> {
1203    fn codec_id(&self) -> &CodecId {
1204        &self.codec_id
1205    }
1206
1207    fn codec_version(&self) -> CodecVersion {
1208        self.codec_version
1209    }
1210
1211    fn codec_upgrades(&self) -> &[CodecVersionUpgrade] {
1212        &self.codec_upgrades
1213    }
1214
1215    fn sensitivity(&self) -> StateSensitivity {
1216        self.sensitivity
1217    }
1218
1219    fn restartability(&self) -> RestartabilityDeclaration {
1220        self.restartability
1221    }
1222}
1223
1224mod stream_contract_sealed {
1225    use super::{
1226        CodecId, ComponentStateEnvelope, ComponentStateError, RestartabilityDeclaration,
1227        StateSchemaId,
1228    };
1229
1230    /// The dyn-compatible mirror a registered stream's codec/schema contract
1231    /// is erased behind. Nothing here is exported: the only implementor is
1232    /// the blanket impl in this module, so a runtime never introspects
1233    /// opaque application state to enforce Gate C -- the registration
1234    /// supplies this contract explicitly instead.
1235    pub trait StreamStateContractObject: Send + Sync {
1236        fn schema_id(&self) -> &StateSchemaId;
1237        fn codec_id(&self) -> &CodecId;
1238        fn restartability(&self) -> RestartabilityDeclaration;
1239        fn validate_for_open(
1240            &self,
1241            envelope: &ComponentStateEnvelope,
1242        ) -> Result<ComponentStateEnvelope, ComponentStateError>;
1243    }
1244}
1245
1246struct CodecContract<T, C> {
1247    codec: C,
1248    // `fn() -> T` rather than `T` so this struct is `Send + Sync` regardless
1249    // of `T`: the codec never actually produces a `T` here, it only proves
1250    // one exists on the other side of `ComponentStateCodec<T>`.
1251    marker: PhantomData<fn() -> T>,
1252}
1253
1254impl<T, C: ComponentStateCodec<T> + Send + Sync> stream_contract_sealed::StreamStateContractObject
1255    for CodecContract<T, C>
1256{
1257    fn schema_id(&self) -> &StateSchemaId {
1258        self.codec.schema_id()
1259    }
1260
1261    fn codec_id(&self) -> &CodecId {
1262        self.codec.codec_id()
1263    }
1264
1265    fn restartability(&self) -> RestartabilityDeclaration {
1266        self.codec.restartability()
1267    }
1268
1269    fn validate_for_open(
1270        &self,
1271        envelope: &ComponentStateEnvelope,
1272    ) -> Result<ComponentStateEnvelope, ComponentStateError> {
1273        envelope.validated_for_open(&self.codec)
1274    }
1275}
1276
1277/// The codec/schema/restartability contract a registered `ItemStream`
1278/// carries, bound to the runtime at registration time.
1279///
1280/// Gate C requires the runtime to validate a registered stream's expected
1281/// schema and codec identity/version, apply declared migrations, and reject
1282/// unknown-newer versions -- all *before* the application's `open` runs --
1283/// without introspecting the stream's opaque internal state. This is the
1284/// small, explicit descriptor that makes that possible: it preserves the
1285/// existing separation between the stream's logical identity
1286/// ([`crate::definition::ComponentStreamIdentity`]), its runtime
1287/// implementation (`ItemStream`/`BoxedStream`), and its state contract (this
1288/// type), which the stream's own [`ComponentStateCodec`] already declares.
1289pub struct StreamStateContract(Arc<dyn stream_contract_sealed::StreamStateContractObject>);
1290
1291impl StreamStateContract {
1292    /// Captures `codec`'s schema/codec identity, versions, and
1293    /// restartability declaration as a type-erased contract.
1294    pub fn new<T, C>(codec: C) -> Self
1295    where
1296        C: ComponentStateCodec<T> + Send + Sync + 'static,
1297        T: 'static,
1298    {
1299        Self(Arc::new(CodecContract {
1300            codec,
1301            marker: PhantomData,
1302        }))
1303    }
1304
1305    /// Borrows the expected application schema identifier.
1306    #[must_use]
1307    pub fn schema_id(&self) -> &StateSchemaId {
1308        self.0.schema_id()
1309    }
1310
1311    /// Borrows the expected codec identifier.
1312    #[must_use]
1313    pub fn codec_id(&self) -> &CodecId {
1314        self.0.codec_id()
1315    }
1316
1317    /// Returns the declared restartability of the stream this contract
1318    /// belongs to.
1319    #[must_use]
1320    pub fn restartability(&self) -> RestartabilityDeclaration {
1321        self.0.restartability()
1322    }
1323
1324    /// Validates and migrates `envelope` to this contract's current schema
1325    /// and codec versions before the runtime may call `open` with it.
1326    ///
1327    /// # Errors
1328    ///
1329    /// Returns the redacted identity, compatibility, or migration failure
1330    /// [`ComponentStateEnvelope::validated_for_open`] would.
1331    pub fn validate_for_open(
1332        &self,
1333        envelope: &ComponentStateEnvelope,
1334    ) -> Result<ComponentStateEnvelope, ComponentStateError> {
1335        self.0.validate_for_open(envelope)
1336    }
1337}
1338
1339impl fmt::Debug for StreamStateContract {
1340    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1341        formatter
1342            .debug_struct("StreamStateContract")
1343            .field("schema_id", &self.schema_id())
1344            .field("codec_id", &self.codec_id())
1345            .field("restartability", &self.restartability())
1346            .finish()
1347    }
1348}
1349
1350/// Stable, value-redacted component-state validation failure.
1351///
1352/// No variant carries payload data: every field is a scalar identity or
1353/// bound, mirroring [`StateError`]'s own redaction discipline.
1354#[derive(Clone, Debug, Eq, PartialEq)]
1355#[non_exhaustive]
1356pub enum ComponentStateError {
1357    /// A codec identifier was empty.
1358    EmptyCodecId,
1359    /// A codec identifier exceeded its UTF-8 byte limit.
1360    CodecIdTooLong {
1361        /// Maximum accepted UTF-8 bytes.
1362        max_bytes: usize,
1363    },
1364    /// A codec version was zero.
1365    ZeroCodecVersion,
1366    /// A declared codec-version upgrade did not strictly increase the
1367    /// version.
1368    NonIncreasingCodecUpgrade,
1369    /// A serialized value exceeded its configured byte limit.
1370    TooLarge {
1371        /// Configured maximum bytes.
1372        max_bytes: usize,
1373    },
1374    /// A serialized value exceeded its configured JSON depth.
1375    TooDeep {
1376        /// Configured maximum depth.
1377        max_depth: usize,
1378    },
1379    /// The bytes were not a valid envelope payload.
1380    Malformed,
1381    /// The envelope schema does not match the selected codec.
1382    SchemaMismatch,
1383    /// Durable data was produced by a newer application schema.
1384    UnsupportedSchemaVersion {
1385        /// Version observed in durable data.
1386        found: u32,
1387        /// Current version supported by the selected codec.
1388        current: u32,
1389    },
1390    /// The codec declares no directed schema upgrade reaching its current
1391    /// version.
1392    NoSchemaUpgradePath {
1393        /// Version the chain stalled at.
1394        found: u32,
1395        /// Current version supported by the selected codec.
1396        current: u32,
1397    },
1398    /// Two declared schema upgrades leave the same version.
1399    AmbiguousSchemaUpgrade {
1400        /// Version left by more than one declared upgrade.
1401        from: u32,
1402    },
1403    /// A declared schema upgrade produces a version past the codec's current
1404    /// version.
1405    SchemaUpgradeOvershootsCurrent {
1406        /// Version the rejected edge produces.
1407        to: u32,
1408        /// Current version supported by the selected codec.
1409        current: u32,
1410    },
1411    /// The resolved schema-upgrade chain exceeded its bound.
1412    SchemaUpgradeChainTooLong {
1413        /// Most upgrades one decode may apply.
1414        max_upgrades: usize,
1415    },
1416    /// The envelope's codec identity does not match the selected codec.
1417    UnknownCodec,
1418    /// Durable data was produced by a newer codec version.
1419    UnsupportedCodecVersion {
1420        /// Version observed in durable data.
1421        found: u32,
1422        /// Current version supported by the selected codec.
1423        current: u32,
1424    },
1425    /// An older external payload cannot be migrated without resolving its
1426    /// out-of-band bytes.
1427    ExternalSchemaMigrationUnsupported {
1428        /// Version recorded in the external envelope.
1429        found: u32,
1430        /// Current version supported by the selected codec.
1431        current: u32,
1432    },
1433    /// An older external payload cannot be migrated without resolving its
1434    /// out-of-band bytes.
1435    ExternalCodecMigrationUnsupported {
1436        /// Version recorded in the external envelope.
1437        found: u32,
1438        /// Current version supported by the selected codec.
1439        current: u32,
1440    },
1441    /// The codec declares no directed codec-version upgrade reaching its
1442    /// current version.
1443    NoCodecUpgradePath {
1444        /// Version the chain stalled at.
1445        found: u32,
1446        /// Current version supported by the selected codec.
1447        current: u32,
1448    },
1449    /// Two declared codec-version upgrades leave the same version.
1450    AmbiguousCodecUpgrade {
1451        /// Version left by more than one declared upgrade.
1452        from: u32,
1453    },
1454    /// A declared codec-version upgrade produces a version past the codec's
1455    /// current version.
1456    CodecUpgradeOvershootsCurrent {
1457        /// Version the rejected edge produces.
1458        to: u32,
1459        /// Current version supported by the selected codec.
1460        current: u32,
1461    },
1462    /// The resolved codec-upgrade chain exceeded its bound.
1463    CodecUpgradeChainTooLong {
1464        /// Most upgrades one decode may apply.
1465        max_upgrades: usize,
1466    },
1467    /// The declared checksum algorithm identity/version is not supported.
1468    ChecksumAlgorithmUnsupported {
1469        /// Algorithm identifier observed in durable data.
1470        algorithm: u16,
1471        /// Algorithm version observed in durable data.
1472        version: u16,
1473    },
1474    /// The computed checksum does not match the recorded checksum.
1475    ///
1476    /// No decode and no migration were attempted.
1477    ChecksumMismatch,
1478    /// The payload is an external reference that has not been resolved.
1479    ExternalReferenceMissing,
1480    /// Resolved external content did not match its declared content
1481    /// identity.
1482    ExternalReferenceContentMismatch,
1483    /// The application payload was not valid JSON.
1484    InvalidPayload,
1485    /// The application payload was valid JSON but not an object.
1486    PayloadNotObject,
1487    /// The application codec rejected the payload without exposing its
1488    /// value.
1489    Codec(StateCodecError),
1490}
1491
1492impl fmt::Display for ComponentStateError {
1493    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1494        match self {
1495            Self::EmptyCodecId => {
1496                formatter.write_str("component state codec identifier must not be empty")
1497            }
1498            Self::CodecIdTooLong { max_bytes } => {
1499                write!(
1500                    formatter,
1501                    "component state codec identifier exceeds {max_bytes} UTF-8 bytes"
1502                )
1503            }
1504            Self::ZeroCodecVersion => {
1505                formatter.write_str("component state codec version must be nonzero")
1506            }
1507            Self::NonIncreasingCodecUpgrade => {
1508                formatter.write_str("component state codec upgrade must increase the version")
1509            }
1510            Self::TooLarge { max_bytes } => {
1511                write!(formatter, "component state exceeds {max_bytes} bytes")
1512            }
1513            Self::TooDeep { max_depth } => {
1514                write!(formatter, "component state exceeds JSON depth {max_depth}")
1515            }
1516            Self::Malformed => formatter.write_str("component state is malformed"),
1517            Self::SchemaMismatch => {
1518                formatter.write_str("component state schema does not match the component")
1519            }
1520            Self::UnsupportedSchemaVersion { .. } => {
1521                formatter.write_str("component state schema version is unsupported")
1522            }
1523            Self::NoSchemaUpgradePath { .. } => {
1524                formatter.write_str("component state schema version has no upgrade path")
1525            }
1526            Self::AmbiguousSchemaUpgrade { .. } => {
1527                formatter.write_str("component state schema upgrade is ambiguous")
1528            }
1529            Self::SchemaUpgradeOvershootsCurrent { .. } => {
1530                formatter.write_str("component state schema upgrade passes the current version")
1531            }
1532            Self::SchemaUpgradeChainTooLong { max_upgrades } => {
1533                write!(
1534                    formatter,
1535                    "component state schema upgrade chain exceeds {max_upgrades} upgrades"
1536                )
1537            }
1538            Self::UnknownCodec => formatter.write_str("component state codec is unknown"),
1539            Self::UnsupportedCodecVersion { .. } => {
1540                formatter.write_str("component state codec version is unsupported")
1541            }
1542            Self::ExternalSchemaMigrationUnsupported { .. } => {
1543                formatter.write_str("external component state schema migration is unsupported")
1544            }
1545            Self::ExternalCodecMigrationUnsupported { .. } => {
1546                formatter.write_str("external component state codec migration is unsupported")
1547            }
1548            Self::NoCodecUpgradePath { .. } => {
1549                formatter.write_str("component state codec version has no upgrade path")
1550            }
1551            Self::AmbiguousCodecUpgrade { .. } => {
1552                formatter.write_str("component state codec upgrade is ambiguous")
1553            }
1554            Self::CodecUpgradeOvershootsCurrent { .. } => {
1555                formatter.write_str("component state codec upgrade passes the current version")
1556            }
1557            Self::CodecUpgradeChainTooLong { max_upgrades } => {
1558                write!(
1559                    formatter,
1560                    "component state codec upgrade chain exceeds {max_upgrades} upgrades"
1561                )
1562            }
1563            Self::ChecksumAlgorithmUnsupported { .. } => {
1564                formatter.write_str("component state checksum algorithm is unsupported")
1565            }
1566            Self::ChecksumMismatch => {
1567                formatter.write_str("component state checksum does not match")
1568            }
1569            Self::ExternalReferenceMissing => {
1570                formatter.write_str("component state external reference is missing")
1571            }
1572            Self::ExternalReferenceContentMismatch => {
1573                formatter.write_str("component state external content identity mismatch")
1574            }
1575            Self::InvalidPayload => {
1576                formatter.write_str("component state payload is not valid JSON")
1577            }
1578            Self::PayloadNotObject => {
1579                formatter.write_str("component state payload must be a JSON object")
1580            }
1581            Self::Codec(error) => error.fmt(formatter),
1582        }
1583    }
1584}
1585
1586impl Error for ComponentStateError {
1587    fn source(&self) -> Option<&(dyn Error + 'static)> {
1588        match self {
1589            Self::Codec(error) => Some(error),
1590            _ => None,
1591        }
1592    }
1593}