nv_redfish_core/
repair.rs1use std::error::Error as StdError;
26use std::fmt;
27use std::sync::Arc;
28
29use serde::Deserialize;
30use serde_json::Value;
31
32use crate::ActionError;
33use crate::BmcError;
34use crate::BmcErrorClass;
35use crate::Raw;
36
37pub trait Repair: Send + Sync {
39 fn repair(&self, document: &mut Value);
41}
42
43#[derive(Debug, Clone, Copy, Default)]
45pub struct NoRepair;
46
47impl Repair for NoRepair {
48 fn repair(&self, _: &mut Value) {}
49}
50
51pub type DecodeError = serde_path_to_error::Error<serde_json::Error>;
54
55#[derive(Debug)]
57pub enum RepairError<E> {
58 Transport(E),
60 Decode(DecodeError),
62}
63
64impl<E: BmcError> RepairError<E> {
65 #[must_use]
68 pub fn from_transport(error: E) -> Self {
69 error
70 .into_decode_error()
71 .map_or_else(Self::Transport, Self::Decode)
72 }
73}
74
75impl<E: fmt::Display> fmt::Display for RepairError<E> {
76 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77 match self {
78 Self::Transport(error) => write!(f, "BMC error: {error}"),
79 Self::Decode(error) => write!(f, "document did not deserialize: {error}"),
80 }
81 }
82}
83
84impl<E: StdError + 'static> StdError for RepairError<E> {
85 fn source(&self) -> Option<&(dyn StdError + 'static)> {
86 match self {
87 Self::Transport(error) => Some(error),
88 Self::Decode(error) => Some(error),
89 }
90 }
91}
92
93impl<E: BmcError + 'static> BmcError for RepairError<E> {
94 fn error_class(&self) -> BmcErrorClass {
95 match self {
96 Self::Transport(error) => error.error_class(),
97 Self::Decode(_) => BmcErrorClass::ResponseParse,
98 }
99 }
100
101 fn response_body(&self) -> Option<&str> {
102 match self {
103 Self::Transport(error) => error.response_body(),
104 Self::Decode(_) => None,
105 }
106 }
107
108 fn into_decode_error(self) -> Result<DecodeError, Self> {
109 match self {
110 Self::Transport(error) => error.into_decode_error().map_err(Self::Transport),
111 Self::Decode(error) => Ok(error),
112 }
113 }
114}
115
116impl<E: ActionError> ActionError for RepairError<E> {
117 fn not_supported() -> Self {
118 Self::Transport(E::not_supported())
119 }
120}
121
122pub fn decode<T>(document: Value) -> Result<T, DecodeError>
129where
130 T: for<'de> Deserialize<'de>,
131{
132 serde_path_to_error::deserialize(document)
133}
134
135pub fn decode_raw<T, E>(
142 raw: Result<Arc<Raw>, E>,
143 repair: &impl Repair,
144) -> Result<Arc<T>, RepairError<E>>
145where
146 T: for<'de> Deserialize<'de>,
147{
148 let raw = raw.map_err(RepairError::Transport)?;
149 let mut document = Arc::try_unwrap(raw).map_or_else(|raw| raw.value().clone(), Raw::into_value);
151 repair.repair(&mut document);
152 decode(document).map(Arc::new).map_err(RepairError::Decode)
153}