1use 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;
31const MAX_UPGRADE_CHAIN: usize = 64;
36
37#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
45pub struct CodecId(String);
46
47impl CodecId {
48 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 #[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 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#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
95pub struct CodecVersion(NonZeroU32);
96
97impl CodecVersion {
98 pub fn new(value: u32) -> Result<Self, ComponentStateError> {
104 NonZeroU32::new(value)
105 .map(Self)
106 .ok_or(ComponentStateError::ZeroCodecVersion)
107 }
108
109 #[must_use]
111 pub const fn get(self) -> u32 {
112 self.0.get()
113 }
114}
115
116#[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 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 #[must_use]
148 pub const fn from(&self) -> CodecVersion {
149 self.from
150 }
151
152 #[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#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
175#[non_exhaustive]
176pub enum ChecksumAlgorithm {
177 Sha256,
179}
180
181impl ChecksumAlgorithm {
182 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#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
218#[non_exhaustive]
219pub enum StateSensitivity {
220 #[default]
222 Sensitive,
223 NonSensitive,
226}
227
228#[derive(Clone, Copy, Debug, Eq, PartialEq)]
234#[non_exhaustive]
235pub enum RestartabilityDeclaration {
236 Restartable,
239 NotRestartable,
242}
243
244#[derive(Clone, Copy, Eq, Hash, PartialEq)]
249pub struct ContentIdentity([u8; 32]);
250
251impl ContentIdentity {
252 #[must_use]
254 pub const fn from_bytes(bytes: [u8; 32]) -> Self {
255 Self(bytes)
256 }
257
258 #[must_use]
260 pub fn of(bytes: &[u8]) -> Self {
261 Self(Sha256::digest(bytes).into())
262 }
263
264 #[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#[derive(Clone, Copy, Debug, Eq, PartialEq)]
293pub struct ExternalStateReference {
294 content_id: ContentIdentity,
295 encoded_len: u64,
296}
297
298impl ExternalStateReference {
299 #[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 #[must_use]
310 pub const fn content_id(&self) -> ContentIdentity {
311 self.content_id
312 }
313
314 #[must_use]
316 pub const fn encoded_len(&self) -> u64 {
317 self.encoded_len
318 }
319
320 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
342pub trait ExternalStateStore: Send + Sync {
349 fn resolve<'a>(
358 &'a self,
359 reference: &'a ExternalStateReference,
360 ) -> impl Future<Output = Result<Vec<u8>, ExternalStateError>> + Send + 'a;
361
362 fn store<'a>(
369 &'a self,
370 bytes: &'a [u8],
371 ) -> impl Future<Output = Result<ExternalStateReference, ExternalStateError>> + Send + 'a;
372}
373
374#[derive(Clone, Copy, Debug, Eq, PartialEq)]
376#[non_exhaustive]
377pub enum ExternalStateError {
378 ContentMissing,
380 ContentMismatch,
382 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#[derive(Clone, Debug, Eq, PartialEq)]
404pub enum ComponentStatePayload {
405 Inline(Vec<u8>),
407 External(ExternalStateReference),
409}
410
411#[derive(Clone, Eq, PartialEq)]
412enum StoredPayload {
413 Inline(Vec<u8>),
424 External(ExternalStateReference),
425}
426
427#[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
482fn 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 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 #[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 #[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 #[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 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 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 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 #[must_use]
1001 pub const fn namespace(&self) -> &ComponentStreamIdentity {
1002 &self.namespace
1003 }
1004
1005 #[must_use]
1007 pub const fn schema_id(&self) -> &StateSchemaId {
1008 &self.schema_id
1009 }
1010
1011 #[must_use]
1013 pub const fn schema_version(&self) -> StateSchemaVersion {
1014 self.schema_version
1015 }
1016
1017 #[must_use]
1019 pub const fn codec_id(&self) -> &CodecId {
1020 &self.codec_id
1021 }
1022
1023 #[must_use]
1025 pub const fn codec_version(&self) -> CodecVersion {
1026 self.codec_version
1027 }
1028
1029 #[must_use]
1031 pub const fn is_external(&self) -> bool {
1032 matches!(self.payload, StoredPayload::External(_))
1033 }
1034
1035 #[must_use]
1037 pub const fn checksum_algorithm(&self) -> u16 {
1038 self.checksum_algorithm.identifier()
1039 }
1040
1041 #[must_use]
1043 pub const fn checksum_algorithm_version(&self) -> u16 {
1044 self.checksum_algorithm.algorithm_version()
1045 }
1046
1047 #[must_use]
1054 pub const fn checksum(&self) -> [u8; 32] {
1055 self.checksum
1056 }
1057
1058 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 #[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
1104pub trait ComponentStateCodec<T>: VersionedStateCodec<T> {
1112 fn codec_id(&self) -> &CodecId;
1114
1115 fn codec_version(&self) -> CodecVersion;
1117
1118 fn codec_upgrades(&self) -> &[CodecVersionUpgrade] {
1120 &[]
1121 }
1122
1123 fn sensitivity(&self) -> StateSensitivity {
1127 StateSensitivity::Sensitive
1128 }
1129
1130 fn restartability(&self) -> RestartabilityDeclaration;
1132}
1133
1134pub 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 #[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 #[must_use]
1167 pub fn with_codec_upgrades(mut self, upgrades: Vec<CodecVersionUpgrade>) -> Self {
1168 self.codec_upgrades = upgrades;
1169 self
1170 }
1171
1172 #[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 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 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
1277pub struct StreamStateContract(Arc<dyn stream_contract_sealed::StreamStateContractObject>);
1290
1291impl StreamStateContract {
1292 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 #[must_use]
1307 pub fn schema_id(&self) -> &StateSchemaId {
1308 self.0.schema_id()
1309 }
1310
1311 #[must_use]
1313 pub fn codec_id(&self) -> &CodecId {
1314 self.0.codec_id()
1315 }
1316
1317 #[must_use]
1320 pub fn restartability(&self) -> RestartabilityDeclaration {
1321 self.0.restartability()
1322 }
1323
1324 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#[derive(Clone, Debug, Eq, PartialEq)]
1355#[non_exhaustive]
1356pub enum ComponentStateError {
1357 EmptyCodecId,
1359 CodecIdTooLong {
1361 max_bytes: usize,
1363 },
1364 ZeroCodecVersion,
1366 NonIncreasingCodecUpgrade,
1369 TooLarge {
1371 max_bytes: usize,
1373 },
1374 TooDeep {
1376 max_depth: usize,
1378 },
1379 Malformed,
1381 SchemaMismatch,
1383 UnsupportedSchemaVersion {
1385 found: u32,
1387 current: u32,
1389 },
1390 NoSchemaUpgradePath {
1393 found: u32,
1395 current: u32,
1397 },
1398 AmbiguousSchemaUpgrade {
1400 from: u32,
1402 },
1403 SchemaUpgradeOvershootsCurrent {
1406 to: u32,
1408 current: u32,
1410 },
1411 SchemaUpgradeChainTooLong {
1413 max_upgrades: usize,
1415 },
1416 UnknownCodec,
1418 UnsupportedCodecVersion {
1420 found: u32,
1422 current: u32,
1424 },
1425 ExternalSchemaMigrationUnsupported {
1428 found: u32,
1430 current: u32,
1432 },
1433 ExternalCodecMigrationUnsupported {
1436 found: u32,
1438 current: u32,
1440 },
1441 NoCodecUpgradePath {
1444 found: u32,
1446 current: u32,
1448 },
1449 AmbiguousCodecUpgrade {
1451 from: u32,
1453 },
1454 CodecUpgradeOvershootsCurrent {
1457 to: u32,
1459 current: u32,
1461 },
1462 CodecUpgradeChainTooLong {
1464 max_upgrades: usize,
1466 },
1467 ChecksumAlgorithmUnsupported {
1469 algorithm: u16,
1471 version: u16,
1473 },
1474 ChecksumMismatch,
1478 ExternalReferenceMissing,
1480 ExternalReferenceContentMismatch,
1483 InvalidPayload,
1485 PayloadNotObject,
1487 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}