Skip to main content

feldera_types/
error.rs

1use crate::secret_redaction::secret_redactor;
2use actix_web::ResponseError;
3use actix_web::http::StatusCode;
4use log::{error, info};
5use serde::{Deserialize, Serialize};
6use serde_json::Value as JsonValue;
7use std::{borrow::Cow, error::Error as StdError};
8use tracing::Level;
9use utoipa::ToSchema;
10pub const MAX_REPORTED_PARSE_ERRORS: usize = 1_000;
11
12/// Information returned by REST API endpoints on error.
13#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq, ToSchema)]
14pub struct ErrorResponse {
15    /// Human-readable error message.
16    #[schema(example = "Explanation of the error that occurred.")]
17    pub message: String,
18    /// Error code is a string that specifies this error type.
19    #[schema(example = "CodeSpecifyingErrorType")]
20    pub error_code: Cow<'static, str>,
21    /// Detailed error metadata.
22    /// The contents of this field is determined by `error_code`.
23    #[schema(value_type = Value)]
24    pub details: JsonValue,
25}
26
27/// Error trait which internal errors must implement such that it
28/// can be transformed to a complete JSON error response.
29///
30/// An error that is also an HTTP response, an actix `ResponseError`, converts to an
31/// [`ErrorResponse`] that is logged by its status code.
32pub trait DetailedError: StdError + Serialize {
33    /// Identifying name of the error.
34    fn error_code(&self) -> Cow<'static, str>;
35
36    /// The level to log the error at.
37    fn log_level(&self) -> Level {
38        Level::ERROR
39    }
40}
41
42/// An error from the engine that runs a pipeline's circuit, where the engine's own error type
43/// is unknown: inside the pipeline controller's errors. It reports what a [`DetailedError`]
44/// reports, and it serializes behind a pointer.
45pub trait EngineError: StdError + erased_serde::Serialize + Send + Sync + 'static {
46    /// Identifying name of the error, as [`DetailedError::error_code`] gives it.
47    fn error_code(&self) -> Cow<'static, str>;
48
49    /// The kind of the I/O error that caused this error, if an I/O error did.
50    fn io_error_kind(&self) -> Option<std::io::ErrorKind> {
51        None
52    }
53}
54
55erased_serde::serialize_trait_object!(EngineError);
56
57impl<E> From<&E> for ErrorResponse
58where
59    E: DetailedError + ResponseError,
60{
61    /// Transform the detailed error to a complete JSON error response.
62    /// - The message is retrieved using `to_string()` (available due to trait `StdError`)
63    /// - The status code determines the level of the log statement during this function
64    ///   (available due to trait `ResponseError`)
65    /// - The details are retrieved by serializing to JSON (available due to trait `Serialize`)
66    fn from(error: &E) -> ErrorResponse {
67        Self::from_error(error)
68    }
69}
70
71impl ErrorResponse {
72    pub fn from_error<E>(error: &E) -> Self
73    where
74        E: DetailedError + ResponseError,
75    {
76        // Transform the error into a response
77        let response = Self::from_error_nolog(error);
78
79        // Log based on the status code
80        if error.status_code().is_success() {
81            // The status code should not be successful for an error response
82            error!(
83                "[HTTP error (caused by implementation)] expected error but got success status code {} {}: {}",
84                error.status_code(),
85                response.error_code,
86                response.message
87            );
88        } else if error.status_code().is_client_error() {
89            // Client-caused error responses
90            info!(
91                "[HTTP error (caused by client)] {} {}: {}",
92                error.status_code(),
93                response.error_code,
94                response.message
95            );
96        } else if error.status_code() == StatusCode::SERVICE_UNAVAILABLE {
97            info!(
98                "[HTTP error] {} {}: {}",
99                error.status_code(),
100                response.error_code,
101                response.message
102            );
103        } else {
104            // All other status responses should not occur in the implementation,
105            // and thus are logged as errors. Many of the implementation errors are
106            // represented as Internal Server Errors (500).
107            error!(
108                "[HTTP error (caused by implementation)] {} {}: {}",
109                error.status_code(),
110                response.error_code,
111                response.message
112            );
113        }
114
115        // Print error backtrace if available for an internal server error
116        if error.status_code() == StatusCode::INTERNAL_SERVER_ERROR
117            && let Some(backtrace) = response
118                .details
119                .get("backtrace")
120                .and_then(JsonValue::as_str)
121        {
122            error!("Error backtrace:\n{backtrace}");
123        }
124
125        response
126    }
127
128    pub fn from_error_nolog<E>(error: &E) -> Self
129    where
130        E: DetailedError,
131    {
132        // A resolved secret value that the error copied shows as its reference.
133        let redactor = secret_redactor();
134        let message = redactor.redact(&error.to_string()).into_owned();
135        let error_code = error.error_code();
136        let mut details = serde_json::to_value(error).unwrap_or_else(|e| {
137            JsonValue::String(format!("Failed to serialize error. Details: '{e}'"))
138        });
139        redactor.redact_json(&mut details);
140
141        Self {
142            message,
143            error_code,
144            details,
145        }
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::{DetailedError, ErrorResponse};
152    use crate::secret_redaction::secret_redactor;
153    use serde::Serialize;
154    use serde_json::json;
155    use std::borrow::Cow;
156    use thiserror::Error as ThisError;
157
158    #[derive(Debug, Serialize, ThisError)]
159    #[error("connection to {uri} refused")]
160    struct ConnectError {
161        uri: String,
162    }
163
164    impl DetailedError for ConnectError {
165        fn error_code(&self) -> Cow<'static, str> {
166            Cow::from("ConnectError")
167        }
168    }
169
170    /// The message and the details of a response show a resolved secret as
171    /// its reference.
172    #[test]
173    fn response_shows_the_secret_reference_not_the_value() {
174        let uri = "postgres://feldera:response-test-secret@db:5432/app";
175        secret_redactor().register("${secret:kubernetes:pg/uri}", uri);
176
177        let response = ErrorResponse::from_error_nolog(&ConnectError {
178            uri: uri.to_string(),
179        });
180
181        assert_eq!(
182            response.message,
183            "connection to ${secret:kubernetes:pg/uri} refused"
184        );
185        assert_eq!(
186            response.details,
187            json!({"uri": "${secret:kubernetes:pg/uri}"})
188        );
189    }
190}