Skip to main content

baijimu_cmodel_http/
lib.rs

1mod public_boundary;
2mod service_identity;
3pub use public_boundary::{PublicErrorDefinition, PublicErrorPolicy};
4pub use service_identity::{
5    ServiceIdentityLayer, current_service_identity, scope_service_identity,
6};
7
8use std::{
9    future::Future,
10    pin::Pin,
11    task::{Context, Poll},
12};
13
14use baijimu_cmodel_core::{CModelFailureData, CModelResponse, ContractViolation};
15use bytes::Bytes;
16use http::{
17    HeaderMap, HeaderValue, Request, Response,
18    header::{CONTENT_TYPE, HeaderName},
19};
20use serde::de::DeserializeOwned;
21use thiserror::Error;
22use tower::{Layer, Service};
23use uuid::Uuid;
24
25pub use http::StatusCode;
26
27pub const CMODEL_CONTENT_TYPE: &str = "application/json; charset=utf-8";
28pub const REQUEST_ID_HEADER: HeaderName = HeaderName::from_static("x-request-id");
29pub const TRACE_ID_HEADER: HeaderName = HeaderName::from_static("x-trace-id");
30
31#[derive(Clone, Debug, PartialEq, Eq)]
32pub struct RequestContext {
33    request_id: String,
34    trace_id: Option<String>,
35}
36
37impl RequestContext {
38    pub fn new(request_id: impl Into<String>, trace_id: Option<impl Into<String>>) -> Self {
39        Self {
40            request_id: request_id.into(),
41            trace_id: trace_id.map(Into::into),
42        }
43    }
44
45    pub fn request_id(&self) -> &str {
46        &self.request_id
47    }
48
49    pub fn trace_id(&self) -> Option<&str> {
50        self.trace_id.as_deref()
51    }
52}
53
54tokio::task_local! {
55    static REQUEST_CONTEXT: RequestContext;
56}
57
58pub fn current_request_context() -> RequestContext {
59    REQUEST_CONTEXT
60        .try_with(Clone::clone)
61        .unwrap_or_else(|_| RequestContext::new(Uuid::new_v4().to_string(), None::<String>))
62}
63
64/// Run a framework adapter's request future with the shared CModel context.
65/// Context is scoped to this future and cannot leak between concurrent requests.
66pub async fn scope_request_context<F: Future>(context: RequestContext, future: F) -> F::Output {
67    REQUEST_CONTEXT.scope(context, future).await
68}
69
70#[derive(Clone, Copy, Debug, Default)]
71pub struct RequestContextLayer;
72
73impl RequestContextLayer {
74    pub const fn new() -> Self {
75        Self
76    }
77}
78
79impl<S> Layer<S> for RequestContextLayer {
80    type Service = RequestContextService<S>;
81
82    fn layer(&self, inner: S) -> Self::Service {
83        RequestContextService { inner }
84    }
85}
86
87#[derive(Clone, Debug)]
88pub struct RequestContextService<S> {
89    inner: S,
90}
91
92impl<S, RequestBody, ResponseBody> Service<Request<RequestBody>> for RequestContextService<S>
93where
94    S: Service<Request<RequestBody>, Response = Response<ResponseBody>>,
95    S::Future: Send + 'static,
96    S::Error: 'static,
97    ResponseBody: 'static,
98{
99    type Response = Response<ResponseBody>;
100    type Error = S::Error;
101    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
102
103    fn poll_ready(&mut self, context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
104        self.inner.poll_ready(context)
105    }
106
107    fn call(&mut self, request: Request<RequestBody>) -> Self::Future {
108        let request_id = header_text(request.headers(), &REQUEST_ID_HEADER)
109            .unwrap_or_else(|| Uuid::new_v4().to_string());
110        let context = RequestContext::new(
111            request_id.clone(),
112            header_text(request.headers(), &TRACE_ID_HEADER),
113        );
114        let future = self.inner.call(request);
115
116        Box::pin(REQUEST_CONTEXT.scope(context, async move {
117            let mut response = future.await?;
118            response.headers_mut().insert(
119                REQUEST_ID_HEADER,
120                HeaderValue::from_str(&request_id)
121                    .expect("validated request ID must be a valid HTTP header value"),
122            );
123            Ok(response)
124        }))
125    }
126}
127
128fn header_text(headers: &HeaderMap, name: &HeaderName) -> Option<String> {
129    headers
130        .get(name)
131        .and_then(|value| value.to_str().ok())
132        .map(str::trim)
133        .filter(|value| !value.is_empty() && value.chars().count() <= 256)
134        .map(str::to_owned)
135}
136
137#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct PreservedErrorResponse {
139    status: StatusCode,
140    body: Bytes,
141    error_code: String,
142    message: Option<String>,
143    retryable: Option<bool>,
144    failure_data: Option<Box<CModelFailureData>>,
145}
146
147impl PreservedErrorResponse {
148    pub fn new(status: StatusCode, body: impl Into<Bytes>, error_code: impl Into<String>) -> Self {
149        Self {
150            status,
151            body: body.into(),
152            error_code: error_code.into(),
153            message: None,
154            retryable: None,
155            failure_data: None,
156        }
157    }
158
159    pub fn with_message(mut self, message: impl Into<String>) -> Self {
160        let message = message.into();
161        self.message = (!message.trim().is_empty()).then_some(message);
162        self
163    }
164
165    pub fn with_failure_data(mut self, data: &CModelFailureData) -> Self {
166        self.message = Some(data.message().to_owned());
167        self.retryable = Some(data.retryable());
168        self.failure_data = Some(Box::new(data.clone()));
169        self
170    }
171
172    pub fn status(&self) -> StatusCode {
173        self.status
174    }
175
176    pub fn body(&self) -> &Bytes {
177        &self.body
178    }
179
180    pub fn error_code(&self) -> &str {
181        &self.error_code
182    }
183
184    pub fn message(&self) -> Option<&str> {
185        self.message.as_deref()
186    }
187
188    pub fn retryable(&self) -> Option<bool> {
189        self.retryable
190    }
191
192    pub fn error_path(&self) -> Option<&baijimu_cmodel_core::ErrorPath> {
193        self.failure_data
194            .as_deref()
195            .and_then(CModelFailureData::error_path)
196    }
197
198    /// Client-side extraction preserves bytes and never appends a service hop.
199    pub fn into_parts(self) -> (StatusCode, Bytes) {
200        (StatusCode::OK, self.body)
201    }
202
203    /// Called only by the unified server response adapter, once per returned failure.
204    pub fn into_service_response_parts(mut self) -> (StatusCode, Bytes) {
205        if let (Some(identity), Some(data)) = (current_service_identity(), &mut self.failure_data) {
206            data.prepend_error_path(identity);
207            self.body = serialize_failure(&self.error_code, data);
208        }
209        (StatusCode::OK, self.body)
210    }
211
212    pub fn content_type_header() -> (&'static HeaderName, HeaderValue) {
213        (&CONTENT_TYPE, HeaderValue::from_static(CMODEL_CONTENT_TYPE))
214    }
215}
216
217fn serialize_failure(error_code: &str, data: &CModelFailureData) -> Bytes {
218    #[derive(serde::Serialize)]
219    #[serde(rename_all = "camelCase")]
220    struct FailureEnvelope<'a> {
221        contract_version: baijimu_cmodel_core::ContractVersion,
222        error_code: &'a str,
223        data: &'a CModelFailureData,
224    }
225    serde_json::to_vec(&FailureEnvelope {
226        contract_version: baijimu_cmodel_core::ContractVersion::current(),
227        error_code,
228        data,
229    })
230    .expect("validated CModel failure details must serialize")
231    .into()
232}
233
234impl std::fmt::Display for PreservedErrorResponse {
235    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
236        if let Some(message) = &self.message {
237            write!(
238                formatter,
239                "{message} (downstream HTTP {}, error code {})",
240                self.status, self.error_code
241            )
242        } else {
243            write!(
244                formatter,
245                "downstream returned HTTP {} with error code {}",
246                self.status, self.error_code
247            )
248        }
249    }
250}
251
252#[derive(Debug, Error)]
253pub enum CModelHttpError {
254    #[error("{operation} response violates the CModel HTTP contract: HTTP {status}, {detail}")]
255    InvalidResponse {
256        operation: String,
257        status: StatusCode,
258        detail: String,
259    },
260    #[error("{operation} successful response is missing data")]
261    MissingData { operation: String },
262    #[error("{0}")]
263    Downstream(PreservedErrorResponse),
264}
265
266impl CModelHttpError {
267    pub fn downstream(
268        status: StatusCode,
269        body: impl Into<Bytes>,
270        error_code: impl Into<String>,
271        message: impl Into<String>,
272    ) -> Self {
273        Self::Downstream(
274            PreservedErrorResponse::new(status, body, error_code).with_message(message),
275        )
276    }
277
278    pub fn is_invalid_response(&self) -> bool {
279        matches!(self, Self::InvalidResponse { .. })
280    }
281}
282
283pub fn validate_http_status<T>(
284    status: StatusCode,
285    _body: &CModelResponse<T>,
286) -> Result<(), ContractViolation> {
287    if status != StatusCode::OK {
288        return Err(ContractViolation::new(
289            "httpStatus",
290            "CModel responses must use HTTP 200; errorCode expresses the business outcome",
291        ));
292    }
293    Ok(())
294}
295
296pub fn decode_required_data<T>(
297    status: StatusCode,
298    body: &[u8],
299    operation: &str,
300) -> Result<T, CModelHttpError>
301where
302    T: DeserializeOwned,
303{
304    decode_optional_data(status, body, operation)?.ok_or_else(|| CModelHttpError::MissingData {
305        operation: operation.to_owned(),
306    })
307}
308
309/// Decode and validate a complete CModel response without interpreting a
310/// business failure as transport failure.
311///
312/// Use this at boundaries that intentionally preserve the downstream CModel
313/// envelope, such as a generic Runtime service invocation. Callers that need
314/// successful data should use [`decode_required_data`] or
315/// [`decode_optional_data`] instead.
316pub fn decode_response<T>(
317    status: StatusCode,
318    body: &[u8],
319    operation: &str,
320) -> Result<CModelResponse<T>, CModelHttpError>
321where
322    T: DeserializeOwned,
323{
324    let response = deserialize_response(status, body, operation)?;
325
326    if status != StatusCode::OK && !status.is_client_error() && !status.is_server_error() {
327        return Err(CModelHttpError::InvalidResponse {
328            operation: operation.to_owned(),
329            status,
330            detail: "CModel responses must use HTTP 200; only legacy 4xx/5xx failures are accepted during migration".to_owned(),
331        });
332    }
333
334    if response.is_success() {
335        validate_http_status(status, &response).map_err(|error| {
336            CModelHttpError::InvalidResponse {
337                operation: operation.to_owned(),
338                status,
339                detail: error.to_string(),
340            }
341        })?;
342    }
343
344    Ok(response)
345}
346
347pub fn decode_optional_data<T>(
348    status: StatusCode,
349    body: &[u8],
350    operation: &str,
351) -> Result<Option<T>, CModelHttpError>
352where
353    T: DeserializeOwned,
354{
355    let response = decode_response(status, body, operation)?;
356
357    if !response.is_success() {
358        let mut error = PreservedErrorResponse::new(
359            status,
360            Bytes::copy_from_slice(body),
361            response.error_code().as_str(),
362        );
363        if let Some(data) = response.failure_data() {
364            error = error.with_failure_data(data);
365        }
366        return Err(CModelHttpError::Downstream(error));
367    }
368
369    Ok(response.into_data())
370}
371
372fn deserialize_response<T>(
373    status: StatusCode,
374    body: &[u8],
375    operation: &str,
376) -> Result<CModelResponse<T>, CModelHttpError>
377where
378    T: DeserializeOwned,
379{
380    let mut deserializer = serde_json::Deserializer::from_slice(body);
381    let response = serde_path_to_error::deserialize(&mut deserializer).map_err(|error| {
382        CModelHttpError::InvalidResponse {
383            operation: operation.to_owned(),
384            status,
385            detail: error.to_string(),
386        }
387    })?;
388    deserializer
389        .end()
390        .map_err(|error| CModelHttpError::InvalidResponse {
391            operation: operation.to_owned(),
392            status,
393            detail: error.to_string(),
394        })?;
395    Ok(response)
396}
397
398#[cfg(test)]
399mod tests;