1use std::{borrow::Borrow, error::Error as StdError, fmt, str::FromStr, sync::Arc};
7
8use schemars::{JsonSchema, Schema, SchemaGenerator, json_schema};
9use serde::{Deserialize, Deserializer, Serialize, Serializer, de};
10use serde_json::Value;
11use thiserror::Error;
12
13use crate::{
14 BoundedJson, BoundedJsonError, DurationMillis, EventId, FailureId, JsonLimits, JsonLimitsError,
15 SchemaReference,
16};
17
18const FAILURE_IDENTIFIER_PATTERN: &str = "^[a-z][a-z0-9_-]*(\\.[a-z][a-z0-9_-]*)*$";
19
20#[derive(Clone, Debug, Eq, Error, PartialEq)]
22#[non_exhaustive]
23pub enum FailureIdentifierError {
24 #[error("stable failure identifier must not be empty")]
26 Empty,
27
28 #[error("stable failure identifier is {actual} bytes; maximum is {max}")]
30 TooLong {
31 max: usize,
33 actual: usize,
35 },
36
37 #[error("failure identifier segment must start with lowercase ASCII at offset {index}")]
39 InvalidSegmentStart {
40 index: usize,
42 },
43
44 #[error("stable failure identifier contains an invalid byte at offset {index}")]
46 InvalidByte {
47 index: usize,
49 },
50}
51
52fn validate_failure_identifier(value: &str) -> Result<(), FailureIdentifierError> {
53 const MAX_LEN: usize = 128;
54
55 if value.is_empty() {
56 return Err(FailureIdentifierError::Empty);
57 }
58 if value.len() > MAX_LEN {
59 return Err(FailureIdentifierError::TooLong {
60 max: MAX_LEN,
61 actual: value.len(),
62 });
63 }
64
65 let mut at_segment_start = true;
66 for (index, byte) in value.bytes().enumerate() {
67 if at_segment_start {
68 if !byte.is_ascii_lowercase() {
69 return Err(FailureIdentifierError::InvalidSegmentStart { index });
70 }
71 at_segment_start = false;
72 } else if byte == b'.' {
73 at_segment_start = true;
74 } else if !byte.is_ascii_lowercase()
75 && !byte.is_ascii_digit()
76 && !matches!(byte, b'_' | b'-')
77 {
78 return Err(FailureIdentifierError::InvalidByte { index });
79 }
80 }
81
82 if at_segment_start {
83 return Err(FailureIdentifierError::InvalidSegmentStart { index: value.len() });
84 }
85
86 Ok(())
87}
88
89macro_rules! define_failure_identifier {
90 ($name:ident, $visitor:ident, $documentation:literal) => {
91 #[doc = $documentation]
92 #[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
93 pub struct $name(Box<str>);
94
95 impl $name {
96 pub const MAX_LEN: usize = 128;
98
99 pub fn new(value: impl Into<String>) -> Result<Self, FailureIdentifierError> {
106 let value = value.into();
107 validate_failure_identifier(&value)?;
108 Ok(Self(value.into_boxed_str()))
109 }
110
111 #[must_use]
113 pub fn as_str(&self) -> &str {
114 &self.0
115 }
116 }
117
118 impl AsRef<str> for $name {
119 fn as_ref(&self) -> &str {
120 self.as_str()
121 }
122 }
123
124 impl Borrow<str> for $name {
125 fn borrow(&self) -> &str {
126 self.as_str()
127 }
128 }
129
130 impl fmt::Debug for $name {
131 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
132 formatter
133 .debug_tuple(stringify!($name))
134 .field(&self.as_str())
135 .finish()
136 }
137 }
138
139 impl fmt::Display for $name {
140 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
141 formatter.write_str(self.as_str())
142 }
143 }
144
145 impl FromStr for $name {
146 type Err = FailureIdentifierError;
147
148 fn from_str(value: &str) -> Result<Self, Self::Err> {
149 Self::new(value)
150 }
151 }
152
153 impl TryFrom<String> for $name {
154 type Error = FailureIdentifierError;
155
156 fn try_from(value: String) -> Result<Self, Self::Error> {
157 Self::new(value)
158 }
159 }
160
161 impl TryFrom<&str> for $name {
162 type Error = FailureIdentifierError;
163
164 fn try_from(value: &str) -> Result<Self, Self::Error> {
165 Self::new(value)
166 }
167 }
168
169 impl From<$name> for String {
170 fn from(value: $name) -> Self {
171 value.0.into()
172 }
173 }
174
175 impl Serialize for $name {
176 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
177 where
178 S: Serializer,
179 {
180 serializer.serialize_str(self.as_str())
181 }
182 }
183
184 impl<'de> Deserialize<'de> for $name {
185 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
186 where
187 D: Deserializer<'de>,
188 {
189 deserializer.deserialize_string($visitor)
190 }
191 }
192
193 struct $visitor;
194
195 impl de::Visitor<'_> for $visitor {
196 type Value = $name;
197
198 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
199 formatter.write_str("a lowercase segmented stable failure identifier")
200 }
201
202 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
203 where
204 E: de::Error,
205 {
206 $name::try_from(value).map_err(E::custom)
207 }
208
209 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
210 where
211 E: de::Error,
212 {
213 $name::try_from(value).map_err(E::custom)
214 }
215 }
216
217 impl JsonSchema for $name {
218 fn schema_name() -> std::borrow::Cow<'static, str> {
219 stringify!($name).into()
220 }
221
222 fn schema_id() -> std::borrow::Cow<'static, str> {
223 concat!(module_path!(), "::", stringify!($name)).into()
224 }
225
226 fn json_schema(_: &mut SchemaGenerator) -> Schema {
227 json_schema!({
228 "type": "string",
229 "minLength": 1,
230 "maxLength": 128,
231 "pattern": FAILURE_IDENTIFIER_PATTERN
232 })
233 }
234
235 fn inline_schema() -> bool {
236 true
237 }
238 }
239 };
240}
241
242define_failure_identifier!(
243 FailureCode,
244 FailureCodeVisitor,
245 "A stable, machine-readable failure code owned by an application or adapter."
246);
247define_failure_identifier!(
248 FailureOrigin,
249 FailureOriginVisitor,
250 "A stable component or dependency namespace that originated a failure."
251);
252
253#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
259pub struct FailureMessage(Box<str>);
260
261impl FailureMessage {
262 pub const MAX_BYTES: usize = 1024;
264
265 pub fn new(value: impl Into<String>) -> Result<Self, FailureMessageError> {
273 let value = value.into();
274 validate_failure_message(&value)?;
275 Ok(Self(value.into_boxed_str()))
276 }
277
278 #[must_use]
280 pub fn as_str(&self) -> &str {
281 &self.0
282 }
283
284 #[must_use]
286 pub fn len_bytes(&self) -> usize {
287 self.0.len()
288 }
289}
290
291impl AsRef<str> for FailureMessage {
292 fn as_ref(&self) -> &str {
293 self.as_str()
294 }
295}
296
297impl Borrow<str> for FailureMessage {
298 fn borrow(&self) -> &str {
299 self.as_str()
300 }
301}
302
303impl fmt::Debug for FailureMessage {
304 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
305 formatter
306 .debug_struct("FailureMessage")
307 .field("utf8_bytes", &self.len_bytes())
308 .finish_non_exhaustive()
309 }
310}
311
312impl fmt::Display for FailureMessage {
313 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
314 formatter.write_str(self.as_str())
315 }
316}
317
318impl FromStr for FailureMessage {
319 type Err = FailureMessageError;
320
321 fn from_str(value: &str) -> Result<Self, Self::Err> {
322 Self::new(value)
323 }
324}
325
326impl TryFrom<String> for FailureMessage {
327 type Error = FailureMessageError;
328
329 fn try_from(value: String) -> Result<Self, Self::Error> {
330 Self::new(value)
331 }
332}
333
334impl TryFrom<&str> for FailureMessage {
335 type Error = FailureMessageError;
336
337 fn try_from(value: &str) -> Result<Self, Self::Error> {
338 Self::new(value)
339 }
340}
341
342impl From<FailureMessage> for String {
343 fn from(value: FailureMessage) -> Self {
344 value.0.into()
345 }
346}
347
348impl Serialize for FailureMessage {
349 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
350 where
351 S: Serializer,
352 {
353 serializer.serialize_str(self.as_str())
354 }
355}
356
357impl<'de> Deserialize<'de> for FailureMessage {
358 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
359 where
360 D: Deserializer<'de>,
361 {
362 deserializer.deserialize_string(FailureMessageVisitor)
363 }
364}
365
366struct FailureMessageVisitor;
367
368impl de::Visitor<'_> for FailureMessageVisitor {
369 type Value = FailureMessage;
370
371 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
372 formatter.write_str("a bounded public-safe single-line failure message")
373 }
374
375 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
376 where
377 E: de::Error,
378 {
379 FailureMessage::try_from(value).map_err(E::custom)
380 }
381
382 fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
383 where
384 E: de::Error,
385 {
386 FailureMessage::try_from(value).map_err(E::custom)
387 }
388}
389
390impl JsonSchema for FailureMessage {
391 fn schema_name() -> std::borrow::Cow<'static, str> {
392 "FailureMessage".into()
393 }
394
395 fn schema_id() -> std::borrow::Cow<'static, str> {
396 concat!(module_path!(), "::FailureMessage").into()
397 }
398
399 fn json_schema(_: &mut SchemaGenerator) -> Schema {
400 json_schema!({
401 "type": "string",
402 "minLength": 1,
403 "maxLength": 1024,
404 "description": "A public-safe single-line message bounded to 1024 UTF-8 bytes. StateKnot additionally rejects leading/trailing whitespace, controls, bidirectional formatting controls, Unicode line separators, and Unicode noncharacters at runtime. Shape validation cannot prove that the caller omitted secrets."
405 })
406 }
407
408 fn inline_schema() -> bool {
409 true
410 }
411}
412
413#[derive(Clone, Debug, Eq, Error, PartialEq)]
415#[non_exhaustive]
416pub enum FailureMessageError {
417 #[error("failure message must not be empty")]
419 Empty,
420
421 #[error("failure message is {actual} bytes; maximum is {max}")]
423 TooLong {
424 max: usize,
426 actual: usize,
428 },
429
430 #[error("failure message must not contain leading or trailing whitespace")]
432 SurroundingWhitespace,
433
434 #[error("failure message contains a disallowed scalar at byte offset {index}")]
436 DisallowedScalar {
437 index: usize,
439 },
440}
441
442fn validate_failure_message(value: &str) -> Result<(), FailureMessageError> {
443 if value.is_empty() {
444 return Err(FailureMessageError::Empty);
445 }
446 if value.len() > FailureMessage::MAX_BYTES {
447 return Err(FailureMessageError::TooLong {
448 max: FailureMessage::MAX_BYTES,
449 actual: value.len(),
450 });
451 }
452 if value.chars().next().is_some_and(char::is_whitespace)
453 || value.chars().next_back().is_some_and(char::is_whitespace)
454 {
455 return Err(FailureMessageError::SurroundingWhitespace);
456 }
457 if let Some((index, _)) = value.char_indices().find(|(_, scalar)| {
458 scalar.is_control()
459 || is_bidi_formatting_control(*scalar)
460 || matches!(scalar, '\u{2028}' | '\u{2029}')
461 || is_unicode_noncharacter(*scalar)
462 }) {
463 return Err(FailureMessageError::DisallowedScalar { index });
464 }
465 Ok(())
466}
467
468const fn is_unicode_noncharacter(value: char) -> bool {
469 let code_point = value as u32;
470 (code_point >= 0xfdd0 && code_point <= 0xfdef) || code_point & 0xfffe == 0xfffe
471}
472
473const fn is_bidi_formatting_control(value: char) -> bool {
474 matches!(
475 value,
476 '\u{061c}'
477 | '\u{200e}'
478 | '\u{200f}'
479 | '\u{202a}'..='\u{202e}'
480 | '\u{2066}'..='\u{2069}'
481 )
482}
483
484#[derive(Clone, Copy, Debug, Deserialize, Eq, Hash, JsonSchema, PartialEq, Serialize)]
486#[serde(rename_all = "snake_case")]
487pub enum FailureCategory {
488 InvalidInput,
490 Unauthenticated,
492 PermissionDenied,
494 PolicyDenied,
496 NotFound,
498 Conflict,
500 Unsupported,
502 RateLimited,
504 DeadlineExceeded,
506 Cancelled,
508 DependencyUnavailable,
510 DataCorruption,
512 AmbiguousExternalOutcome,
514 Internal,
516}
517
518#[derive(Clone, Copy, Debug, Eq, Hash, JsonSchema, PartialEq, Serialize)]
524#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
525pub enum RetryAdvice {
526 Never,
528 SafeAfter {
530 delay: DurationMillis,
532 },
533 ReconcileFirst,
535}
536
537impl RetryAdvice {
538 #[must_use]
540 pub const fn safe_after_delay(self) -> Option<DurationMillis> {
541 match self {
542 Self::SafeAfter { delay } => Some(delay),
543 Self::Never | Self::ReconcileFirst => None,
544 }
545 }
546
547 #[must_use]
549 pub const fn requires_reconciliation(self) -> bool {
550 matches!(self, Self::ReconcileFirst)
551 }
552}
553
554impl<'de> Deserialize<'de> for RetryAdvice {
555 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
556 where
557 D: Deserializer<'de>,
558 {
559 deserializer.deserialize_map(RetryAdviceVisitor)
560 }
561}
562
563struct RetryAdviceVisitor;
564
565impl<'de> de::Visitor<'de> for RetryAdviceVisitor {
566 type Value = RetryAdvice;
567
568 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
569 formatter.write_str("a closed retry-advice object")
570 }
571
572 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
573 where
574 A: de::MapAccess<'de>,
575 {
576 let mut kind = None;
577 let mut delay = None;
578
579 while let Some(field) = map.next_key::<RetryAdviceField>()? {
580 match field {
581 RetryAdviceField::Kind => {
582 if kind.is_some() {
583 return Err(de::Error::duplicate_field("kind"));
584 }
585 kind = Some(map.next_value::<RetryAdviceKind>()?);
586 }
587 RetryAdviceField::Delay => {
588 if delay.is_some() {
589 return Err(de::Error::duplicate_field("delay"));
590 }
591 delay = Some(map.next_value::<DurationMillis>()?);
592 }
593 }
594 }
595
596 match (kind.ok_or_else(|| de::Error::missing_field("kind"))?, delay) {
597 (RetryAdviceKind::Never, None) => Ok(RetryAdvice::Never),
598 (RetryAdviceKind::SafeAfter, Some(delay)) => Ok(RetryAdvice::SafeAfter { delay }),
599 (RetryAdviceKind::ReconcileFirst, None) => Ok(RetryAdvice::ReconcileFirst),
600 (RetryAdviceKind::SafeAfter, None) => Err(de::Error::missing_field("delay")),
601 (RetryAdviceKind::Never | RetryAdviceKind::ReconcileFirst, Some(_)) => {
602 Err(de::Error::unknown_field("delay", &["kind"]))
603 }
604 }
605 }
606}
607
608enum RetryAdviceField {
609 Kind,
610 Delay,
611}
612
613impl<'de> Deserialize<'de> for RetryAdviceField {
614 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
615 where
616 D: Deserializer<'de>,
617 {
618 deserializer.deserialize_identifier(RetryAdviceFieldVisitor)
619 }
620}
621
622struct RetryAdviceFieldVisitor;
623
624impl de::Visitor<'_> for RetryAdviceFieldVisitor {
625 type Value = RetryAdviceField;
626
627 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
628 formatter.write_str("`kind` or `delay`")
629 }
630
631 fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
632 where
633 E: de::Error,
634 {
635 match value {
636 "kind" => Ok(RetryAdviceField::Kind),
637 "delay" => Ok(RetryAdviceField::Delay),
638 _ => Err(E::unknown_field(value, &["kind", "delay"])),
639 }
640 }
641}
642
643#[derive(Deserialize)]
644#[serde(rename_all = "snake_case")]
645enum RetryAdviceKind {
646 Never,
647 SafeAfter,
648 ReconcileFirst,
649}
650
651#[derive(Clone, Eq, JsonSchema, PartialEq, Serialize)]
658#[serde(deny_unknown_fields)]
659pub struct FailureDetails {
660 schema: SchemaReference,
661 value: BoundedJson,
662}
663
664impl FailureDetails {
665 pub const MAX_JSON_BYTES: usize = 16 * 1024;
667 pub const MAX_JSON_DEPTH: usize = 8;
669 pub const MAX_JSON_CONTAINER_ENTRIES: usize = 64;
671 pub const MAX_JSON_NODES: usize = 512;
673 pub const MAX_JSON_STRING_BYTES: usize = 4 * 1024;
675 pub const MAX_JSON_OBJECT_KEY_BYTES: usize = 128;
677
678 pub fn try_new(
685 schema: SchemaReference,
686 value: BoundedJson,
687 ) -> Result<Self, FailureDetailsError> {
688 let limits = failure_details_json_limits()?;
689 let value = BoundedJson::try_from_value_with_limits(value.into_value(), limits)
690 .map_err(FailureDetailsError::json)?;
691 Ok(Self { schema, value })
692 }
693
694 pub fn try_from_value(
704 schema: SchemaReference,
705 value: Value,
706 ) -> Result<Self, FailureDetailsError> {
707 let limits = failure_details_json_limits()?;
708 let value = BoundedJson::try_from_value_with_limits(value, limits)
709 .map_err(FailureDetailsError::json)?;
710 Ok(Self { schema, value })
711 }
712
713 #[must_use]
715 pub const fn schema(&self) -> &SchemaReference {
716 &self.schema
717 }
718
719 #[must_use]
721 pub const fn value(&self) -> &BoundedJson {
722 &self.value
723 }
724
725 #[must_use]
727 pub fn into_parts(self) -> (SchemaReference, BoundedJson) {
728 (self.schema, self.value)
729 }
730}
731
732impl fmt::Debug for FailureDetails {
733 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
734 formatter
735 .debug_struct("FailureDetails")
736 .field("schema", &self.schema)
737 .field("value", &self.value)
738 .finish_non_exhaustive()
739 }
740}
741
742impl<'de> Deserialize<'de> for FailureDetails {
743 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
744 where
745 D: Deserializer<'de>,
746 {
747 #[derive(Deserialize)]
748 #[serde(deny_unknown_fields)]
749 struct Wire {
750 schema: SchemaReference,
751 value: BoundedJson,
752 }
753
754 let wire = Wire::deserialize(deserializer)?;
755 Self::try_new(wire.schema, wire.value).map_err(de::Error::custom)
756 }
757}
758
759fn failure_details_json_limits() -> Result<JsonLimits, FailureDetailsError> {
760 JsonLimits::try_new(
761 FailureDetails::MAX_JSON_BYTES,
762 FailureDetails::MAX_JSON_DEPTH,
763 FailureDetails::MAX_JSON_CONTAINER_ENTRIES,
764 FailureDetails::MAX_JSON_NODES,
765 FailureDetails::MAX_JSON_STRING_BYTES,
766 FailureDetails::MAX_JSON_OBJECT_KEY_BYTES,
767 )
768 .map_err(FailureDetailsError::limits_configuration)
769}
770
771#[derive(Clone, Debug, Eq, Error, PartialEq)]
773#[non_exhaustive]
774pub enum FailureDetailsError {
775 #[error("failure details JSON limits are internally invalid: {source}")]
777 LimitsConfiguration {
778 #[source]
780 source: JsonLimitsError,
781 },
782
783 #[error("failure details violate JSON safety limits: {source}")]
785 Json {
786 #[source]
788 source: BoundedJsonError,
789 },
790}
791
792impl FailureDetailsError {
793 const fn limits_configuration(source: JsonLimitsError) -> Self {
794 Self::LimitsConfiguration { source }
795 }
796
797 const fn json(source: BoundedJsonError) -> Self {
798 Self::Json { source }
799 }
800}
801
802#[derive(Clone, Debug, Eq, Error, PartialEq)]
804#[non_exhaustive]
805pub enum FailureBuildError {
806 #[error("ambiguous external outcomes must use reconcile-first advice")]
808 AmbiguousOutcomeRequiresReconciliation,
809
810 #[error("reconcile-first advice is reserved for ambiguous external outcomes")]
812 ReconciliationRequiresAmbiguousOutcome,
813}
814
815type PrivateSource = dyn StdError + Send + Sync + 'static;
816
817#[derive(Clone)]
824pub struct Failure {
825 id: FailureId,
826 category: FailureCategory,
827 code: FailureCode,
828 origin: FailureOrigin,
829 message: FailureMessage,
830 retry_advice: RetryAdvice,
831 details: Option<FailureDetails>,
832 caused_by_event_id: Option<EventId>,
833 private_source: Option<Arc<PrivateSource>>,
834}
835
836impl Failure {
837 pub fn new(
847 id: FailureId,
848 category: FailureCategory,
849 code: FailureCode,
850 origin: FailureOrigin,
851 message: FailureMessage,
852 retry_advice: RetryAdvice,
853 ) -> Result<Self, FailureBuildError> {
854 validate_failure_recovery(category, retry_advice)?;
855 Ok(Self {
856 id,
857 category,
858 code,
859 origin,
860 message,
861 retry_advice,
862 details: None,
863 caused_by_event_id: None,
864 private_source: None,
865 })
866 }
867
868 #[must_use]
870 pub fn with_details(mut self, details: FailureDetails) -> Self {
871 self.details = Some(details);
872 self
873 }
874
875 #[must_use]
877 pub fn with_caused_by_event(mut self, event_id: EventId) -> Self {
878 self.caused_by_event_id = Some(event_id);
879 self
880 }
881
882 #[must_use]
884 pub fn with_private_source<E>(mut self, source: E) -> Self
885 where
886 E: StdError + Send + Sync + 'static,
887 {
888 self.private_source = Some(Arc::new(source));
889 self
890 }
891
892 #[must_use]
894 pub fn with_shared_private_source(mut self, source: Arc<PrivateSource>) -> Self {
895 self.private_source = Some(source);
896 self
897 }
898
899 #[must_use]
901 pub const fn id(&self) -> FailureId {
902 self.id
903 }
904
905 #[must_use]
907 pub const fn category(&self) -> FailureCategory {
908 self.category
909 }
910
911 #[must_use]
913 pub const fn code(&self) -> &FailureCode {
914 &self.code
915 }
916
917 #[must_use]
919 pub const fn origin(&self) -> &FailureOrigin {
920 &self.origin
921 }
922
923 #[must_use]
925 pub const fn message(&self) -> &FailureMessage {
926 &self.message
927 }
928
929 #[must_use]
931 pub const fn retry_advice(&self) -> RetryAdvice {
932 self.retry_advice
933 }
934
935 #[must_use]
937 pub const fn details(&self) -> Option<&FailureDetails> {
938 self.details.as_ref()
939 }
940
941 #[must_use]
943 pub const fn caused_by_event_id(&self) -> Option<EventId> {
944 self.caused_by_event_id
945 }
946
947 #[must_use]
949 pub const fn has_private_source(&self) -> bool {
950 self.private_source.is_some()
951 }
952
953 #[must_use]
955 pub fn private_source(&self) -> Option<&PrivateSource> {
956 self.private_source.as_deref()
957 }
958}
959
960fn validate_failure_recovery(
961 category: FailureCategory,
962 retry_advice: RetryAdvice,
963) -> Result<(), FailureBuildError> {
964 match (category, retry_advice) {
965 (FailureCategory::AmbiguousExternalOutcome, RetryAdvice::ReconcileFirst) => Ok(()),
966 (FailureCategory::AmbiguousExternalOutcome, _) => {
967 Err(FailureBuildError::AmbiguousOutcomeRequiresReconciliation)
968 }
969 (_, RetryAdvice::ReconcileFirst) => {
970 Err(FailureBuildError::ReconciliationRequiresAmbiguousOutcome)
971 }
972 _ => Ok(()),
973 }
974}
975
976impl fmt::Debug for Failure {
977 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
978 formatter
979 .debug_struct("Failure")
980 .field("id", &self.id)
981 .field("category", &self.category)
982 .field("code", &self.code)
983 .field("origin", &self.origin)
984 .field("message_utf8_bytes", &self.message.len_bytes())
985 .field("retry_advice", &self.retry_advice)
986 .field("has_details", &self.details.is_some())
987 .field("caused_by_event_id", &self.caused_by_event_id)
988 .field("has_private_source", &self.private_source.is_some())
989 .finish_non_exhaustive()
990 }
991}
992
993impl fmt::Display for Failure {
994 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
995 fmt::Display::fmt(&self.message, formatter)
996 }
997}
998
999impl StdError for Failure {}
1000
1001#[derive(Deserialize, JsonSchema)]
1002#[serde(deny_unknown_fields)]
1003struct FailureWire {
1004 id: FailureId,
1005 category: FailureCategory,
1006 code: FailureCode,
1007 origin: FailureOrigin,
1008 message: FailureMessage,
1009 retry_advice: RetryAdvice,
1010 #[serde(default)]
1011 details: Option<FailureDetails>,
1012 #[serde(default)]
1013 caused_by_event_id: Option<EventId>,
1014}
1015
1016#[derive(Serialize)]
1017struct FailureWireRef<'a> {
1018 id: FailureId,
1019 category: FailureCategory,
1020 code: &'a FailureCode,
1021 origin: &'a FailureOrigin,
1022 message: &'a FailureMessage,
1023 retry_advice: RetryAdvice,
1024 #[serde(skip_serializing_if = "Option::is_none")]
1025 details: Option<&'a FailureDetails>,
1026 #[serde(skip_serializing_if = "Option::is_none")]
1027 caused_by_event_id: Option<EventId>,
1028}
1029
1030impl Serialize for Failure {
1031 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1032 where
1033 S: Serializer,
1034 {
1035 FailureWireRef {
1036 id: self.id,
1037 category: self.category,
1038 code: &self.code,
1039 origin: &self.origin,
1040 message: &self.message,
1041 retry_advice: self.retry_advice,
1042 details: self.details.as_ref(),
1043 caused_by_event_id: self.caused_by_event_id,
1044 }
1045 .serialize(serializer)
1046 }
1047}
1048
1049impl<'de> Deserialize<'de> for Failure {
1050 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1051 where
1052 D: Deserializer<'de>,
1053 {
1054 let wire = FailureWire::deserialize(deserializer)?;
1055 let mut failure = Self::new(
1056 wire.id,
1057 wire.category,
1058 wire.code,
1059 wire.origin,
1060 wire.message,
1061 wire.retry_advice,
1062 )
1063 .map_err(de::Error::custom)?;
1064 failure.details = wire.details;
1065 failure.caused_by_event_id = wire.caused_by_event_id;
1066 Ok(failure)
1067 }
1068}
1069
1070impl JsonSchema for Failure {
1071 fn schema_name() -> std::borrow::Cow<'static, str> {
1072 "Failure".into()
1073 }
1074
1075 fn schema_id() -> std::borrow::Cow<'static, str> {
1076 concat!(module_path!(), "::Failure").into()
1077 }
1078
1079 fn json_schema(generator: &mut SchemaGenerator) -> Schema {
1080 FailureWire::json_schema(generator)
1081 }
1082}
1083
1084#[cfg(test)]
1085mod tests {
1086 use super::*;
1087 use crate::{Digest, SchemaId, Version};
1088 use serde_json::{from_value, json, to_value};
1089
1090 fn schema_reference() -> SchemaReference {
1091 SchemaReference::new(
1092 "https://stateknot.github.io/schema/failure-details/1.0.0"
1093 .parse::<SchemaId>()
1094 .unwrap(),
1095 Version::new(1, 0, 0),
1096 Digest::sha256(b"failure details schema"),
1097 )
1098 }
1099
1100 fn failure(category: FailureCategory, retry_advice: RetryAdvice) -> Failure {
1101 Failure::new(
1102 FailureId::generate(),
1103 category,
1104 "dependency.rate_limited".parse().unwrap(),
1105 "provider.openai".parse().unwrap(),
1106 "The dependency is temporarily unavailable."
1107 .parse()
1108 .unwrap(),
1109 retry_advice,
1110 )
1111 .unwrap()
1112 }
1113
1114 #[test]
1115 fn stable_failure_identifiers_enforce_the_segmented_grammar() {
1116 for value in [
1117 "a",
1118 "rate_limited",
1119 "provider.openai",
1120 "stateknot.tool-runtime_v2",
1121 ] {
1122 assert_eq!(value.parse::<FailureCode>().unwrap().as_str(), value);
1123 assert_eq!(value.parse::<FailureOrigin>().unwrap().as_str(), value);
1124 }
1125
1126 for value in [
1127 "",
1128 "A",
1129 "2provider",
1130 ".provider",
1131 "provider.",
1132 "provider..openai",
1133 "provider/OpenAI",
1134 "provider:openai",
1135 "provider.é",
1136 ] {
1137 assert!(value.parse::<FailureCode>().is_err(), "accepted {value:?}");
1138 assert!(
1139 value.parse::<FailureOrigin>().is_err(),
1140 "accepted {value:?}"
1141 );
1142 }
1143
1144 let too_long = "a".repeat(FailureCode::MAX_LEN + 1);
1145 assert_eq!(
1146 too_long.parse::<FailureCode>(),
1147 Err(FailureIdentifierError::TooLong {
1148 max: FailureCode::MAX_LEN,
1149 actual: FailureCode::MAX_LEN + 1,
1150 })
1151 );
1152 }
1153
1154 #[test]
1155 fn public_messages_are_bounded_single_line_values_with_redacted_debug() {
1156 let message = FailureMessage::new("请求暂时无法完成。").unwrap();
1157 assert_eq!(message.as_str(), "请求暂时无法完成。");
1158 assert_eq!(message.to_string(), "请求暂时无法完成。");
1159 assert!(!format!("{message:?}").contains("请求"));
1160
1161 for value in [
1162 "",
1163 " padded",
1164 "padded ",
1165 "two\nlines",
1166 "tab\tinside",
1167 "line\u{2028}separator",
1168 "bidi\u{202e}override",
1169 "noncharacter\u{fdd0}",
1170 ] {
1171 assert!(FailureMessage::new(value).is_err(), "accepted {value:?}");
1172 }
1173
1174 assert_eq!(
1175 FailureMessage::new("a".repeat(FailureMessage::MAX_BYTES + 1)),
1176 Err(FailureMessageError::TooLong {
1177 max: FailureMessage::MAX_BYTES,
1178 actual: FailureMessage::MAX_BYTES + 1,
1179 })
1180 );
1181 }
1182
1183 #[test]
1184 fn categories_and_retry_advice_have_closed_canonical_wire_forms() {
1185 let categories = [
1186 (FailureCategory::InvalidInput, "invalid_input"),
1187 (FailureCategory::Unauthenticated, "unauthenticated"),
1188 (FailureCategory::PermissionDenied, "permission_denied"),
1189 (FailureCategory::PolicyDenied, "policy_denied"),
1190 (FailureCategory::NotFound, "not_found"),
1191 (FailureCategory::Conflict, "conflict"),
1192 (FailureCategory::Unsupported, "unsupported"),
1193 (FailureCategory::RateLimited, "rate_limited"),
1194 (FailureCategory::DeadlineExceeded, "deadline_exceeded"),
1195 (FailureCategory::Cancelled, "cancelled"),
1196 (
1197 FailureCategory::DependencyUnavailable,
1198 "dependency_unavailable",
1199 ),
1200 (FailureCategory::DataCorruption, "data_corruption"),
1201 (
1202 FailureCategory::AmbiguousExternalOutcome,
1203 "ambiguous_external_outcome",
1204 ),
1205 (FailureCategory::Internal, "internal"),
1206 ];
1207 for (category, text) in categories {
1208 assert_eq!(to_value(category).unwrap(), json!(text));
1209 assert_eq!(
1210 from_value::<FailureCategory>(json!(text)).unwrap(),
1211 category
1212 );
1213 }
1214 assert!(from_value::<FailureCategory>(json!("unknown")).is_err());
1215
1216 let retry_forms = [
1217 (RetryAdvice::Never, json!({ "kind": "never" })),
1218 (
1219 RetryAdvice::SafeAfter {
1220 delay: DurationMillis::new(250).unwrap(),
1221 },
1222 json!({ "kind": "safe_after", "delay": "250" }),
1223 ),
1224 (
1225 RetryAdvice::ReconcileFirst,
1226 json!({ "kind": "reconcile_first" }),
1227 ),
1228 ];
1229 for (advice, value) in retry_forms {
1230 assert_eq!(to_value(advice).unwrap(), value);
1231 assert_eq!(from_value::<RetryAdvice>(value).unwrap(), advice);
1232 }
1233 assert!(from_value::<RetryAdvice>(json!({ "kind": "never", "delay": "1" })).is_err());
1234 assert!(from_value::<RetryAdvice>(json!({ "kind": "retry" })).is_err());
1235 }
1236
1237 #[test]
1238 fn failure_details_revalidate_every_tighter_json_dimension() {
1239 let valid = FailureDetails::try_from_value(
1240 schema_reference(),
1241 json!({ "field": "region", "reason": "unsupported" }),
1242 )
1243 .unwrap();
1244 assert_eq!(valid.value().as_value()["field"], "region");
1245 assert!(!format!("{valid:?}").contains("unsupported"));
1246
1247 let long_string = Value::String("a".repeat(FailureDetails::MAX_JSON_STRING_BYTES + 1));
1248 assert!(matches!(
1249 FailureDetails::try_from_value(schema_reference(), long_string),
1250 Err(FailureDetailsError::Json {
1251 source: BoundedJsonError::StringTooLong { .. }
1252 })
1253 ));
1254
1255 let many_entries = Value::Array(
1256 (0..=FailureDetails::MAX_JSON_CONTAINER_ENTRIES)
1257 .map(|value| json!(value))
1258 .collect(),
1259 );
1260 assert!(matches!(
1261 FailureDetails::try_from_value(schema_reference(), many_entries),
1262 Err(FailureDetailsError::Json {
1263 source: BoundedJsonError::TooManyContainerEntries { .. }
1264 })
1265 ));
1266
1267 let mut nested = Value::Null;
1268 for _ in 0..=FailureDetails::MAX_JSON_DEPTH {
1269 nested = Value::Array(vec![nested]);
1270 }
1271 assert!(matches!(
1272 FailureDetails::try_from_value(schema_reference(), nested),
1273 Err(FailureDetailsError::Json {
1274 source: BoundedJsonError::NestingTooDeep { .. }
1275 })
1276 ));
1277
1278 let oversized_compact = Value::Array(
1279 (0..5)
1280 .map(|_| Value::String("a".repeat(FailureDetails::MAX_JSON_STRING_BYTES)))
1281 .collect(),
1282 );
1283 assert!(matches!(
1284 FailureDetails::try_from_value(schema_reference(), oversized_compact),
1285 Err(FailureDetailsError::Json {
1286 source: BoundedJsonError::CompactRepresentationTooLarge { .. }
1287 })
1288 ));
1289
1290 let too_many_nodes = Value::Array(
1291 (0..FailureDetails::MAX_JSON_CONTAINER_ENTRIES)
1292 .map(|_| Value::Array((0..8).map(|_| Value::Null).collect()))
1293 .collect(),
1294 );
1295 assert!(matches!(
1296 FailureDetails::try_from_value(schema_reference(), too_many_nodes),
1297 Err(FailureDetailsError::Json {
1298 source: BoundedJsonError::TooManyNodes { .. }
1299 })
1300 ));
1301
1302 let mut oversized_key = serde_json::Map::new();
1303 oversized_key.insert(
1304 "k".repeat(FailureDetails::MAX_JSON_OBJECT_KEY_BYTES + 1),
1305 Value::Null,
1306 );
1307 assert!(matches!(
1308 FailureDetails::try_from_value(schema_reference(), Value::Object(oversized_key)),
1309 Err(FailureDetailsError::Json {
1310 source: BoundedJsonError::ObjectKeyTooLong { .. }
1311 })
1312 ));
1313
1314 let limits = failure_details_json_limits().unwrap();
1315 assert_eq!(limits.max_bytes(), FailureDetails::MAX_JSON_BYTES);
1316 assert_eq!(limits.max_depth(), FailureDetails::MAX_JSON_DEPTH);
1317 assert_eq!(
1318 limits.max_container_entries(),
1319 FailureDetails::MAX_JSON_CONTAINER_ENTRIES
1320 );
1321 assert_eq!(limits.max_nodes(), FailureDetails::MAX_JSON_NODES);
1322 assert_eq!(
1323 limits.max_string_bytes(),
1324 FailureDetails::MAX_JSON_STRING_BYTES
1325 );
1326 assert_eq!(
1327 limits.max_object_key_bytes(),
1328 FailureDetails::MAX_JSON_OBJECT_KEY_BYTES
1329 );
1330 }
1331
1332 #[test]
1333 fn ambiguous_outcomes_and_reconciliation_are_an_exact_pair() {
1334 assert!(
1335 Failure::new(
1336 FailureId::generate(),
1337 FailureCategory::AmbiguousExternalOutcome,
1338 "tool.outcome_unknown".parse().unwrap(),
1339 "tool.payments".parse().unwrap(),
1340 "The payment outcome must be reconciled.".parse().unwrap(),
1341 RetryAdvice::ReconcileFirst,
1342 )
1343 .is_ok()
1344 );
1345
1346 assert_eq!(
1347 Failure::new(
1348 FailureId::generate(),
1349 FailureCategory::AmbiguousExternalOutcome,
1350 "tool.outcome_unknown".parse().unwrap(),
1351 "tool.payments".parse().unwrap(),
1352 "The payment outcome must be reconciled.".parse().unwrap(),
1353 RetryAdvice::Never,
1354 )
1355 .unwrap_err(),
1356 FailureBuildError::AmbiguousOutcomeRequiresReconciliation
1357 );
1358 assert_eq!(
1359 Failure::new(
1360 FailureId::generate(),
1361 FailureCategory::Internal,
1362 "runtime.invariant".parse().unwrap(),
1363 "stateknot.runtime".parse().unwrap(),
1364 "The operation could not be completed.".parse().unwrap(),
1365 RetryAdvice::ReconcileFirst,
1366 )
1367 .unwrap_err(),
1368 FailureBuildError::ReconciliationRequiresAmbiguousOutcome
1369 );
1370 }
1371
1372 #[derive(Debug, Error)]
1373 #[error("private database diagnostics: password=secret")]
1374 struct PrivateDiagnostic;
1375
1376 #[test]
1377 fn wire_debug_and_public_display_never_expose_private_diagnostics() {
1378 let details =
1379 FailureDetails::try_from_value(schema_reference(), json!({ "safe": "public detail" }))
1380 .unwrap();
1381 let event_id = EventId::generate();
1382 let failure = failure(FailureCategory::DependencyUnavailable, RetryAdvice::Never)
1383 .with_details(details)
1384 .with_caused_by_event(event_id)
1385 .with_private_source(PrivateDiagnostic);
1386
1387 let encoded = to_value(&failure).unwrap();
1388 assert_eq!(encoded["caused_by_event_id"], event_id.to_string());
1389 assert!(encoded.get("private_source").is_none());
1390 assert!(!encoded.to_string().contains("password"));
1391
1392 let debug = format!("{failure:?}");
1393 assert!(!debug.contains("password"));
1394 assert!(!debug.contains("public detail"));
1395 assert_eq!(
1396 failure.to_string(),
1397 "The dependency is temporarily unavailable."
1398 );
1399 assert!(StdError::source(&failure).is_none());
1400 assert!(failure.private_source().is_some());
1401
1402 let decoded = from_value::<Failure>(encoded).unwrap();
1403 assert!(!decoded.has_private_source());
1404 assert_eq!(decoded.caused_by_event_id(), Some(event_id));
1405 assert_eq!(decoded.category(), failure.category());
1406 }
1407
1408 #[test]
1409 fn deserialization_rejects_private_or_unknown_fields_and_bad_invariants() {
1410 let base = to_value(failure(FailureCategory::Internal, RetryAdvice::Never)).unwrap();
1411 let mut with_source = base.clone();
1412 with_source["private_source"] = json!("secret");
1413 assert!(from_value::<Failure>(with_source).is_err());
1414
1415 let mut unknown = base.clone();
1416 unknown["extension"] = json!(true);
1417 assert!(from_value::<Failure>(unknown).is_err());
1418
1419 let mut invalid = base;
1420 invalid["category"] = json!("ambiguous_external_outcome");
1421 assert!(from_value::<Failure>(invalid).is_err());
1422 }
1423
1424 #[test]
1425 fn schemas_close_failure_objects_and_exclude_private_sources() {
1426 let schema = to_value(schemars::schema_for!(Failure)).unwrap();
1427 assert_eq!(schema["type"], "object");
1428 assert_eq!(schema["additionalProperties"], false);
1429 assert!(schema["properties"].get("private_source").is_none());
1430 assert!(schema["properties"].get("details").is_some());
1431
1432 let details_schema = to_value(schemars::schema_for!(FailureDetails)).unwrap();
1433 assert_eq!(details_schema["type"], "object");
1434 assert_eq!(details_schema["additionalProperties"], false);
1435
1436 let retry_schema = to_value(schemars::schema_for!(RetryAdvice)).unwrap();
1437 let variants = retry_schema["oneOf"].as_array().unwrap();
1438 assert_eq!(variants.len(), 3);
1439 assert!(
1440 variants
1441 .iter()
1442 .all(|variant| variant["additionalProperties"] == false),
1443 "retry schema was not closed: {retry_schema}"
1444 );
1445
1446 let code_schema = to_value(schemars::schema_for!(FailureCode)).unwrap();
1447 assert_eq!(code_schema["pattern"], FAILURE_IDENTIFIER_PATTERN);
1448 assert_eq!(code_schema["maxLength"], FailureCode::MAX_LEN);
1449
1450 let message_schema = to_value(schemars::schema_for!(FailureMessage)).unwrap();
1451 assert_eq!(message_schema["maxLength"], FailureMessage::MAX_BYTES);
1452 }
1453}