Skip to main content

anycms_core/frameworks/
actix.rs

1#[cfg(feature = "actix")]
2use crate::result::{ApiResult, ErrorCode};
3#[cfg(feature = "actix")]
4use actix_web::Error;
5#[cfg(feature = "actix")]
6use actix_web::HttpMessage;
7#[cfg(feature = "actix")]
8use actix_web::dev::{Service, ServiceRequest, ServiceResponse, Transform, forward_ready};
9#[cfg(feature = "actix")]
10use actix_web::{HttpResponse, Responder};
11#[cfg(feature = "actix")]
12use futures_util::future::LocalBoxFuture;
13#[cfg(feature = "actix")]
14use serde::Serialize;
15#[cfg(feature = "actix")]
16use std::rc::Rc;
17
18#[cfg(feature = "actix")]
19fn error_code_to_status(code: ErrorCode) -> actix_web::http::StatusCode {
20    match code {
21        ErrorCode::Success => actix_web::http::StatusCode::OK,
22        ErrorCode::BadRequest => actix_web::http::StatusCode::BAD_REQUEST,
23        ErrorCode::Unauthorized => actix_web::http::StatusCode::UNAUTHORIZED,
24        ErrorCode::Forbidden => actix_web::http::StatusCode::FORBIDDEN,
25        ErrorCode::NotFound => actix_web::http::StatusCode::NOT_FOUND,
26        ErrorCode::MethodNotAllowed => actix_web::http::StatusCode::METHOD_NOT_ALLOWED,
27        ErrorCode::Conflict => actix_web::http::StatusCode::CONFLICT,
28        ErrorCode::PayloadTooLarge => actix_web::http::StatusCode::PAYLOAD_TOO_LARGE,
29        ErrorCode::ValidationError => actix_web::http::StatusCode::UNPROCESSABLE_ENTITY,
30        ErrorCode::TooManyRequests => actix_web::http::StatusCode::TOO_MANY_REQUESTS,
31        ErrorCode::InternalError => actix_web::http::StatusCode::INTERNAL_SERVER_ERROR,
32        ErrorCode::ServiceUnavailable => actix_web::http::StatusCode::SERVICE_UNAVAILABLE,
33    }
34}
35
36// ============================================================
37// Request Extension: trace_id carrier
38// ============================================================
39
40/// Internal extension that carries the trace ID through the request lifecycle.
41///
42/// Set by [`ApiResultLayer`] middleware and read by the `Responder` implementation
43/// to auto-inject `trace_id` into `ApiResult` responses.
44#[cfg(feature = "actix")]
45#[derive(Clone)]
46pub struct ApiTraceId(pub String);
47
48// ============================================================
49// Middleware Configuration
50// ============================================================
51
52/// Configuration for the [`ApiResultLayer`] middleware.
53#[cfg(feature = "actix")]
54#[derive(Clone)]
55pub struct ApiResultMiddlewareConfig {
56    /// Header names to check for an existing trace ID (checked in order).
57    ///
58    /// Default: `["X-Request-ID", "X-Trace-ID"]`
59    pub trace_id_headers: Vec<String>,
60
61    /// Whether to auto-inject the current Unix-millisecond timestamp.
62    ///
63    /// Default: `false`
64    pub inject_timestamp: bool,
65}
66
67#[cfg(feature = "actix")]
68impl Default for ApiResultMiddlewareConfig {
69    fn default() -> Self {
70        Self {
71            trace_id_headers: vec!["X-Request-ID".to_string(), "X-Trace-ID".to_string()],
72            inject_timestamp: false,
73        }
74    }
75}
76
77// ============================================================
78// Middleware Layer (Transform factory)
79// ============================================================
80
81/// Actix-web middleware layer that auto-injects `trace_id` (and optionally `timestamp`)
82/// into `ApiResult` responses.
83///
84/// # How it works
85///
86/// 1. Extracts a trace ID from request headers (or generates a UUID v4)
87/// 2. Stores it in request extensions as [`ApiTraceId`]
88/// 3. The `Responder` impl for `ApiResult<T>` reads the extension and injects it
89///
90/// This approach is **zero-overhead**: no body re-serialization needed.
91///
92/// # Usage
93///
94/// ```ignore
95/// use actix_web::App;
96/// use anycms_core::actix::ApiResultLayer;
97///
98/// App::new()
99///     .wrap(ApiResultLayer::default())
100///     .route("/users", web::get().to(list_users))
101/// ```
102#[cfg(feature = "actix")]
103pub struct ApiResultLayer {
104    config: ApiResultMiddlewareConfig,
105}
106
107#[cfg(feature = "actix")]
108impl ApiResultLayer {
109    /// Create a new layer with the given configuration.
110    pub fn new(config: ApiResultMiddlewareConfig) -> Self {
111        Self { config }
112    }
113}
114
115#[cfg(feature = "actix")]
116impl Default for ApiResultLayer {
117    fn default() -> Self {
118        Self::new(ApiResultMiddlewareConfig::default())
119    }
120}
121
122#[cfg(feature = "actix")]
123impl<S, B> Transform<S, ServiceRequest> for ApiResultLayer
124where
125    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
126    S::Future: 'static,
127    B: 'static,
128{
129    type Response = ServiceResponse<B>;
130    type Error = Error;
131    type InitError = ();
132    type Transform = ApiResultMiddleware<S>;
133    type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
134
135    fn new_transform(&self, service: S) -> Self::Future {
136        std::future::ready(Ok(ApiResultMiddleware {
137            service: Rc::new(service),
138            config: self.config.clone(),
139        }))
140    }
141}
142
143// ============================================================
144// Middleware Service
145// ============================================================
146
147/// The actual middleware service that processes each request.
148#[cfg(feature = "actix")]
149pub struct ApiResultMiddleware<S> {
150    service: Rc<S>,
151    config: ApiResultMiddlewareConfig,
152}
153
154#[cfg(feature = "actix")]
155impl<S, B> Service<ServiceRequest> for ApiResultMiddleware<S>
156where
157    S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
158    S::Future: 'static,
159    B: 'static,
160{
161    type Response = ServiceResponse<B>;
162    type Error = Error;
163    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
164
165    forward_ready!(service);
166
167    fn call(&self, req: ServiceRequest) -> Self::Future {
168        let service = Rc::clone(&self.service);
169
170        // Extract trace_id from headers or generate a new one
171        let trace_id = self
172            .config
173            .trace_id_headers
174            .iter()
175            .find_map(|h| {
176                req.headers()
177                    .get(h.as_str())
178                    .and_then(|v| v.to_str().ok())
179                    .map(|s| s.to_string())
180            })
181            .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
182
183        // Store in request extensions for the Responder to pick up
184        req.extensions_mut().insert(ApiTraceId(trace_id));
185
186        Box::pin(async move {
187            let res = service.call(req).await?;
188            Ok(res)
189        })
190    }
191}
192
193// ============================================================
194// Responder implementation (enhanced with auto trace_id injection)
195// ============================================================
196
197/// Actix-web framework integration for ApiResult.
198///
199/// When [`ApiResultLayer`] middleware is active, the `trace_id` is automatically
200/// injected from request extensions into the response.
201#[cfg(feature = "actix")]
202impl<T: Serialize> Responder for ApiResult<T> {
203    type Body = actix_web::body::BoxBody;
204
205    fn respond_to(self, req: &actix_web::HttpRequest) -> actix_web::HttpResponse<Self::Body> {
206        let mut result = self;
207
208        // Auto-inject trace_id from middleware if not already set
209        if result.trace_id.is_none()
210            && let Some(tid) = req.extensions().get::<ApiTraceId>()
211        {
212            result = result.with_trace_id(&tid.0);
213        }
214
215        let status = result
216            .code
217            .and_then(ErrorCode::from_i32)
218            .map(error_code_to_status)
219            .unwrap_or_else(|| {
220                if result.success {
221                    actix_web::http::StatusCode::OK
222                } else {
223                    actix_web::http::StatusCode::INTERNAL_SERVER_ERROR
224                }
225            });
226
227        HttpResponse::build(status).json(result)
228    }
229}