hyperlane-plugin-problem-details 23.3.0

An RFC 9457 Problem Details (application/problem+json) error normalizer and builder plugin for the Hyperlane framework with zero-overhead 2xx/3xx fast path and automatic 4xx/5xx error structuring.
Documentation
use super::*;

/// Construction, fluent builders, and response application for [`ProblemDetails`].
impl ProblemDetails {
    /// Creates a new [`ProblemDetails`] with `status` and its standard HTTP title.
    ///
    /// # Arguments
    ///
    /// - `HttpStatus` - HTTP error status.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed Problem Details object.
    pub fn from_status(status: HttpStatus) -> Self {
        let code: usize = status.code();
        Self {
            problem_type: ABOUT_BLANK_TYPE.to_owned(),
            title: default_title_for_status(code).to_owned(),
            status: code,
            detail: None,
            instance: None,
            extensions: BTreeMap::new(),
        }
    }

    /// Creates a new [`ProblemDetails`] with explicit numeric status code and `title`.
    ///
    /// # Arguments
    ///
    /// - `usize` - HTTP status code.
    /// - `T` - Human-readable title.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed Problem Details object.
    pub fn new<T>(status: usize, title: T) -> Self
    where
        T: Into<String>,
    {
        Self {
            problem_type: ABOUT_BLANK_TYPE.to_owned(),
            title: title.into(),
            status,
            detail: None,
            instance: None,
            extensions: BTreeMap::new(),
        }
    }

    /// Sets the RFC 9457 `type` URI reference.
    ///
    /// # Arguments
    ///
    /// - `S` - Problem type URI.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated Problem Details.
    pub fn with_type<S>(mut self, problem_type: S) -> Self
    where
        S: Into<String>,
    {
        self.set_problem_type(problem_type.into());
        self
    }

    /// Sets the `detail` explanation string.
    ///
    /// # Arguments
    ///
    /// - `S` - Detailed explanation for this error occurrence.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated Problem Details.
    pub fn with_detail<S>(mut self, detail: S) -> Self
    where
        S: Into<String>,
    {
        self.set_detail(Some(detail.into()));
        self
    }

    /// Sets the `instance` URI reference.
    ///
    /// # Arguments
    ///
    /// - `S` - Instance URI (typically the request path or trace URI).
    ///
    /// # Returns
    ///
    /// - `Self` - Updated Problem Details.
    pub fn with_instance<S>(mut self, instance: S) -> Self
    where
        S: Into<String>,
    {
        self.set_instance(Some(instance.into()));
        self
    }

    /// Attaches a custom top-level JSON extension member.
    ///
    /// # Arguments
    ///
    /// - `K` - Extension key name.
    /// - `Value` - JSON extension value.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated Problem Details.
    pub fn with_extension<K>(mut self, key: K, value: Value) -> Self
    where
        K: Into<String>,
    {
        let _: Option<Value> = self.get_mut_extensions().insert(key.into(), value);
        self
    }

    /// Serializes this [`ProblemDetails`] into UTF-8 JSON bytes.
    ///
    /// # Returns
    ///
    /// - `Vec<u8>` - JSON bytes.
    pub fn to_json_bytes(&self) -> Vec<u8> {
        to_vec(self).unwrap_or_default()
    }

    /// Writes this [`ProblemDetails`] directly into a Hyperlane [`Response`].
    ///
    /// # Arguments
    ///
    /// - `&mut Response` - Target HTTP response.
    pub fn write_to_response(&self, response: &mut Response) {
        response
            .set_status_code(self.get_status())
            .set_header(CONTENT_TYPE, PROBLEM_JSON_MEDIA_TYPE)
            .set_body(self.to_json_bytes());
    }

    /// Writes this [`ProblemDetails`] into `ctx.get_mut_response()`, automatically filling `instance` from request path if unset.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Active Hyperlane context.
    pub fn apply(&self, ctx: &mut Context) {
        let mut owned: Self = self.clone();
        if owned.try_get_instance().is_none() {
            owned.set_instance(Some(ctx.get_request().get_path().to_owned()));
        }
        owned.write_to_response(ctx.get_mut_response());
    }
}

/// Default construction for [`ProblemDetailsConfig`].
impl Default for ProblemDetailsConfig {
    /// Builds a default config enabling auto-normalization, request `instance`, and `5xx` detail masking.
    ///
    /// # Returns
    ///
    /// - `Self` - Default configuration.
    fn default() -> Self {
        Self {
            auto_normalize: true,
            include_instance: true,
            type_base_uri: None,
            mask_server_error_details: true,
        }
    }
}

/// Fluent builders for [`ProblemDetailsConfig`].
impl ProblemDetailsConfig {
    /// Sets a base URI used to construct `<base>/<status>` problem type URIs.
    ///
    /// # Arguments
    ///
    /// - `S` - Base URI prefix.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_type_base_uri<S>(mut self, base_uri: S) -> Self
    where
        S: Into<String>,
    {
        self.set_type_base_uri(Some(base_uri.into()));
        self
    }

    /// Configures whether raw `5xx` plain-text bodies are hidden during auto-normalization.
    ///
    /// # Arguments
    ///
    /// - `bool` - `true` to mask `5xx` details.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated configuration.
    pub fn with_mask_server_error_details(mut self, mask: bool) -> Self {
        self.set_mask_server_error_details(mask);
        self
    }
}

/// Normalization engine for [`ProblemDetailsPlugin`].
impl ProblemDetailsPlugin {
    /// Compiles a standalone [`ProblemDetailsPlugin`] from `config`.
    ///
    /// # Arguments
    ///
    /// - `ProblemDetailsConfig` - Problem Details configuration.
    ///
    /// # Returns
    ///
    /// - `Self` - Compiled plugin.
    pub fn new(config: ProblemDetailsConfig) -> Self {
        let type_base_clean: Option<String> = config
            .try_get_type_base_uri()
            .as_ref()
            .map(|u: &String| u.trim().trim_end_matches('/').to_owned())
            .filter(|u: &String| !u.is_empty());
        Self {
            config,
            type_base_clean,
        }
    }

    /// Initializes the global [`ProblemDetailsPlugin`] singleton once.
    ///
    /// # Arguments
    ///
    /// - `ProblemDetailsConfig` - Configuration.
    ///
    /// # Returns
    ///
    /// - `&'static Self` - Reference to the global plugin.
    pub fn init(config: ProblemDetailsConfig) -> &'static Self {
        PROBLEM_DETAILS_PLUGIN.get_or_init(|| Self::new(config))
    }

    /// Returns the initialized global [`ProblemDetailsPlugin`], if configured.
    ///
    /// # Returns
    ///
    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
    #[inline(always)]
    pub fn get() -> Option<&'static Self> {
        PROBLEM_DETAILS_PLUGIN.get()
    }

    /// Normalizes a `4xx`/`5xx` response in `ctx` into `application/problem+json` if eligible.
    ///
    /// # Arguments
    ///
    /// - `&mut Context` - Active request/response context.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` if the response was converted to RFC 9457 JSON.
    #[inline]
    pub fn normalize_context(&self, ctx: &mut Context) -> bool {
        let Self {
            config,
            type_base_clean,
            ..
        } = self;
        if !config.get_auto_normalize() {
            return false;
        }
        let status: usize = ctx.get_response().get_status_code();
        if status < 400 {
            return false;
        }
        let existing_ct: Option<&str> = ctx
            .get_response()
            .get_headers()
            .get(CONTENT_TYPE)
            .and_then(|vals: &VecDeque<String>| vals.back().map(String::as_str));
        if let Some(ct) = existing_ct {
            let trimmed: &str = ct.trim();
            if trimmed.len() >= PROBLEM_JSON_PREFIX.len()
                && trimmed.as_bytes()[..PROBLEM_JSON_PREFIX.len()]
                    .eq_ignore_ascii_case(PROBLEM_JSON_PREFIX.as_bytes())
            {
                return false;
            }
            let is_plain: bool = trimmed.len() >= TEXT_PLAIN_PREFIX.len()
                && trimmed.as_bytes()[..TEXT_PLAIN_PREFIX.len()]
                    .eq_ignore_ascii_case(TEXT_PLAIN_PREFIX.as_bytes());
            if !is_plain && !ctx.get_response().get_body().is_empty() {
                return false;
            }
        }
        let problem_type: String = match type_base_clean {
            Some(base) => format!("{base}/{status}"),
            None => ABOUT_BLANK_TYPE.to_owned(),
        };
        let detail: Option<String> = if status >= 500 && config.get_mask_server_error_details() {
            None
        } else {
            let body: &[u8] = ctx.get_response().get_body();
            if body.is_empty() {
                None
            } else {
                from_utf8(body)
                    .ok()
                    .map(|s: &str| s.trim().to_owned())
                    .filter(|s: &String| !s.is_empty())
            }
        };
        let instance: Option<String> = if config.get_include_instance() {
            Some(ctx.get_request().get_path().to_owned())
        } else {
            None
        };
        let problem: ProblemDetails = ProblemDetails {
            problem_type,
            title: default_title_for_status(status).to_owned(),
            status,
            detail,
            instance,
            extensions: BTreeMap::new(),
        };
        problem.write_to_response(ctx.get_mut_response());
        true
    }
}

/// Implements [`ServerHook`] for [`ProblemDetailsHook`].
impl ServerHook for ProblemDetailsHook {
    /// Constructs a per-response [`ProblemDetailsHook`].
    ///
    /// # Arguments
    ///
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Self` - Hook instance.
    #[inline(always)]
    async fn new(_: &mut Stream, _: &mut Context) -> Self {
        Self
    }

    /// Converts bare `4xx`/`5xx` error responses into structured RFC 9457 `application/problem+json`.
    ///
    /// # Arguments
    ///
    /// - `Self` - Hook instance.
    /// - `&mut Stream` - Connection stream.
    /// - `&mut Context` - Request context.
    ///
    /// # Returns
    ///
    /// - `Status` - Always `Status::Continue`.
    #[inline(always)]
    async fn handle(self, _: &mut Stream, ctx: &mut Context) -> Status {
        let Some(plugin) = ProblemDetailsPlugin::get() else {
            return Status::Continue;
        };
        let _: bool = plugin.normalize_context(ctx);
        Status::Continue
    }
}