loveyu-kit 0.2.0

面向 Axum 项目的可组合 API 工具库
Documentation
//! 请求标识和由应用确认可信的主体提取器。

use std::{convert::Infallible, fmt, ops::Deref, sync::Arc};

use axum::{extract::FromRequestParts, http::request::Parts};

use crate::web::response::ApiError;

use super::RequestSubject;

/// 请求链路唯一标识。
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RequestId(Arc<str>);

impl RequestId {
    /// 使用应用已经生成或校验的值创建请求 ID。
    pub fn new(value: impl Into<Arc<str>>) -> Self {
        Self(value.into())
    }

    /// 返回请求 ID。
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// 获取请求 ID 字符串。
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0.to_string()
    }
}

impl AsRef<str> for RequestId {
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl From<String> for RequestId {
    fn from(value: String) -> Self {
        Self::new(value)
    }
}

impl Deref for RequestId {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl fmt::Display for RequestId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

impl<S> FromRequestParts<S> for RequestId
where
    S: Send + Sync,
{
    type Rejection = Infallible;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        Ok(parts
            .extensions
            .get::<Self>()
            .cloned()
            .unwrap_or_else(|| Self::new(uuid::Uuid::now_v7().to_string())))
    }
}

/// 已由上游网关或应用中间件确认可信的请求主体。
///
/// 只有配置了 `RequestLoggingConfig::trusted_subject_header` 且请求头合法时才会注入。
/// 业务应用必须确保外部客户端无法绕过网关伪造该请求头。
#[derive(Clone, Debug)]
pub struct TrustedSubject(Arc<RequestSubject>);

impl TrustedSubject {
    pub(crate) fn new(subject: RequestSubject) -> Self {
        Self(Arc::new(subject))
    }

    /// 返回主体唯一标识。
    #[must_use]
    pub fn id(&self) -> &str {
        &self.0.id
    }

    /// 返回完整主体信息。
    pub fn subject(&self) -> &RequestSubject {
        &self.0
    }

    /// 获取完整主体信息。
    pub fn into_subject(self) -> RequestSubject {
        Arc::unwrap_or_clone(self.0)
    }
}

impl Deref for TrustedSubject {
    type Target = RequestSubject;

    fn deref(&self) -> &Self::Target {
        self.subject()
    }
}

impl<S> FromRequestParts<S> for TrustedSubject
where
    S: Send + Sync,
{
    type Rejection = ApiError;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        parts
            .extensions
            .get::<Self>()
            .cloned()
            .ok_or_else(|| ApiError::err_unauthorized("无法确认当前请求身份,请重新登录"))
    }
}