Skip to main content

nv_redfish_core/
repair.rs

1// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Repairing documents before they are deserialized.
17//!
18//! A [`Repair`] rewrites a document a device sent so it matches the schema
19//! type it is read as. A [`Bmc`](crate::Bmc) applies it through
20//! [`Bmc::get_repaired`](crate::Bmc::get_repaired) and its siblings: a
21//! transport that deserializes documents itself repairs in the same pass,
22//! and any other reads the document as [`Raw`] and hands it to
23//! [`decode_raw`].
24
25use 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
37/// A rewrite of documents before they are deserialized.
38pub trait Repair: Send + Sync {
39    /// Rewrites `document` in place.
40    fn repair(&self, document: &mut Value);
41}
42
43/// The document as it came: the repair of a read that asks for none.
44#[derive(Debug, Clone, Copy, Default)]
45pub struct NoRepair;
46
47impl Repair for NoRepair {
48    fn repair(&self, _: &mut Value) {}
49}
50
51/// A document that did not deserialize, with the path to the property that
52/// failed.
53pub type DecodeError = serde_path_to_error::Error<serde_json::Error>;
54
55/// What a repaired read can fail with.
56#[derive(Debug)]
57pub enum RepairError<E> {
58    /// The transport failed.
59    Transport(E),
60    /// The document, repaired, did not deserialize into the type asked for.
61    Decode(DecodeError),
62}
63
64impl<E: BmcError> RepairError<E> {
65    /// A transport's failure, with its own failure to deserialize a
66    /// document reported as [`Self::Decode`].
67    #[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
122/// Deserializes `document` into `T`, recording the path to the property
123/// that failed.
124///
125/// # Errors
126///
127/// `document` does not deserialize into `T`.
128pub 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
135/// Repairs a document read as [`Raw`] and deserializes it into `T`: the
136/// repaired read of a transport that does not deserialize documents itself.
137///
138/// # Errors
139///
140/// The read failed, or the repaired document did not deserialize into `T`.
141pub 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    // A transport that does not cache hands over the only reference.
150    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}