Skip to main content

frequenz_microgrid_component_graph/
error.rs

1// License: MIT
2// Copyright © 2024 Frequenz Energy-as-a-Service GmbH
3
4//! This module defines the [`Error`] struct and the [`ErrorKind`] enum, which
5//! represent errors that can occur in the library, along with
6//! [`ValidationError`] for the individual failures collected while validating a
7//! graph.
8
9/// The kind of an [`Error`].
10///
11/// Marked `#[non_exhaustive]`: matching on this enum from outside the crate
12/// must include a wildcard arm, so future kinds can be added without a
13/// breaking change.
14#[derive(Debug, Clone, PartialEq)]
15#[non_exhaustive]
16pub enum ErrorKind {
17    /// No component was found for a given component ID.
18    ComponentNotFound,
19
20    /// An internal invariant of the library was violated. This indicates a bug.
21    Internal,
22
23    /// A component is invalid, e.g. it has an unspecified category and a
24    /// connection.
25    InvalidComponent,
26
27    /// A connection between two components is invalid.
28    InvalidConnection,
29
30    /// The graph is structurally invalid, e.g. it has no grid component,
31    /// several grid components, or a duplicate component ID.
32    InvalidGraph,
33
34    /// One or more checks failed while validating an otherwise well-formed
35    /// graph. Holds every [`ValidationError`] that was collected.
36    ValidationErrors(Vec<ValidationError>),
37}
38
39impl std::fmt::Display for ErrorKind {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        let name = match self {
42            Self::ComponentNotFound => "ComponentNotFound",
43            Self::Internal => "Internal",
44            Self::InvalidComponent => "InvalidComponent",
45            Self::InvalidConnection => "InvalidConnection",
46            Self::InvalidGraph => "InvalidGraph",
47            Self::ValidationErrors(_) => "ValidationErrors",
48        };
49        f.write_str(name)
50    }
51}
52
53/// An error that can occur during the creation or traversal of a
54/// [ComponentGraph][crate::ComponentGraph].
55#[derive(Debug, Clone, PartialEq)]
56pub struct Error {
57    kind: ErrorKind,
58    desc: String,
59}
60
61impl Error {
62    /// Returns the [`ErrorKind`] of this error.
63    pub fn kind(&self) -> &ErrorKind {
64        &self.kind
65    }
66
67    /// If this is an [`ErrorKind::ValidationErrors`], returns the collected
68    /// failures; otherwise returns the error unchanged. Any other kind arising
69    /// during validation signals an internal inconsistency rather than a
70    /// topology failure (e.g. a graph lookup returning `ComponentNotFound`), so
71    /// it is propagated to abort validation rather than collected.
72    pub(crate) fn into_validation_errors(self) -> Result<Vec<ValidationError>, Error> {
73        match self.kind {
74            ErrorKind::ValidationErrors(errors) => Ok(errors),
75            kind => Err(Error {
76                kind,
77                desc: self.desc,
78            }),
79        }
80    }
81}
82
83/// Constructors for [`Error`].
84impl Error {
85    /// Creates a new [`Error`] with the `ComponentNotFound` kind and the given
86    /// description.
87    pub(crate) fn component_not_found(desc: impl Into<String>) -> Self {
88        Self {
89            kind: ErrorKind::ComponentNotFound,
90            desc: desc.into(),
91        }
92    }
93
94    /// Creates a new [`Error`] with the `Internal` kind and the given
95    /// description.
96    pub(crate) fn internal(desc: impl Into<String>) -> Self {
97        Self {
98            kind: ErrorKind::Internal,
99            desc: desc.into(),
100        }
101    }
102
103    /// Creates a new [`Error`] with the `InvalidComponent` kind and the given
104    /// description.
105    pub(crate) fn invalid_component(desc: impl Into<String>) -> Self {
106        Self {
107            kind: ErrorKind::InvalidComponent,
108            desc: desc.into(),
109        }
110    }
111
112    /// Creates a new [`Error`] with the `InvalidConnection` kind and the given
113    /// description.
114    pub(crate) fn invalid_connection(desc: impl Into<String>) -> Self {
115        Self {
116            kind: ErrorKind::InvalidConnection,
117            desc: desc.into(),
118        }
119    }
120
121    /// Creates a new [`Error`] with the `InvalidGraph` kind and the given
122    /// description.
123    pub(crate) fn invalid_graph(desc: impl Into<String>) -> Self {
124        Self {
125            kind: ErrorKind::InvalidGraph,
126            desc: desc.into(),
127        }
128    }
129
130    /// Creates a new [`Error`] with the `ValidationErrors` kind from the
131    /// collected validation failures.
132    pub(crate) fn validation_errors(errors: Vec<ValidationError>) -> Self {
133        // The failures carry their own descriptions, so `desc` is unused for
134        // this kind; `Display` formats the collected errors directly.
135        Self {
136            kind: ErrorKind::ValidationErrors(errors),
137            desc: String::new(),
138        }
139    }
140}
141
142impl std::fmt::Display for Error {
143    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
144        match &self.kind {
145            ErrorKind::ValidationErrors(errors) => {
146                write!(f, "Graph validation failed:")?;
147                for error in errors {
148                    write!(f, "\n    {error}")?;
149                }
150                Ok(())
151            }
152            kind => write!(f, "{kind}: {}", self.desc),
153        }
154    }
155}
156
157impl std::error::Error for Error {}
158
159/// A single failure found while validating a
160/// [`ComponentGraph`][crate::ComponentGraph]'s topology.
161///
162/// Validation collects every failure rather than stopping at the first one, so
163/// a single graph can yield many of these (see [`ErrorKind::ValidationErrors`]).
164/// Besides a human-readable [`message`][Self::message], each failure exposes the
165/// [`component_ids`][Self::component_ids] it involves, so callers can act on the
166/// affected components without parsing the message text.
167#[derive(Debug, Clone, PartialEq)]
168pub struct ValidationError {
169    message: String,
170    component_ids: Vec<u64>,
171}
172
173impl ValidationError {
174    /// Creates a new validation error from a message and the IDs of the
175    /// components it involves.
176    pub(crate) fn new(message: impl Into<String>, component_ids: impl Into<Vec<u64>>) -> Self {
177        Self {
178            message: message.into(),
179            component_ids: component_ids.into(),
180        }
181    }
182
183    /// A human-readable description of the failure.
184    pub fn message(&self) -> &str {
185        &self.message
186    }
187
188    /// The IDs of the components involved in the failure.
189    pub fn component_ids(&self) -> &[u64] {
190        &self.component_ids
191    }
192}
193
194impl std::fmt::Display for ValidationError {
195    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196        f.write_str(&self.message)
197    }
198}
199
200impl std::error::Error for ValidationError {}
201
202impl From<ValidationError> for Error {
203    fn from(error: ValidationError) -> Self {
204        Error::validation_errors(vec![error])
205    }
206}
207
208#[cfg(test)]
209mod tests {
210    use super::*;
211
212    #[test]
213    fn validation_error_exposes_its_message_and_components() {
214        let error = ValidationError::new("boom", [3u64, 4]);
215        assert_eq!(error.message(), "boom");
216        assert_eq!(error.component_ids(), &[3, 4]);
217        // `Display` is just the message.
218        assert_eq!(error.to_string(), "boom");
219    }
220
221    #[test]
222    fn leaf_error_display_is_unchanged() {
223        assert_eq!(
224            Error::invalid_graph("No grid component found.").to_string(),
225            "InvalidGraph: No grid component found."
226        );
227    }
228
229    #[test]
230    fn validation_errors_display_lists_each_failure() {
231        let error = Error::validation_errors(vec![
232            ValidationError::new("first problem", [1u64]),
233            ValidationError::new("second problem", [2u64, 3]),
234        ]);
235        assert_eq!(
236            error.to_string(),
237            "Graph validation failed:\n    first problem\n    second problem"
238        );
239    }
240
241    #[test]
242    fn into_validation_errors_unwraps_the_collected_failures() {
243        let error: Error = ValidationError::new("boom", [1u64]).into();
244        assert_eq!(
245            error.into_validation_errors(),
246            Ok(vec![ValidationError::new("boom", [1u64])])
247        );
248    }
249
250    #[test]
251    fn into_validation_errors_passes_other_kinds_through() {
252        assert_eq!(
253            Error::internal("bug").into_validation_errors(),
254            Err(Error::internal("bug"))
255        );
256    }
257}