sdforge 0.3.0

Multi-protocol SDK framework with unified macro configuration
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
//! HTTP response building utilities
//!
//! This module contains HTTP-specific response handling for Axum.
//! These functions are kept separate from core to avoid HTTP dependencies
//! for non-HTTP protocol implementations.

use axum::body::Body;
use axum::http;
use axum::response::IntoResponse;
use serde::Serialize;

use crate::core::{ApiError, ServiceResponse};

/// Build a JSON response with proper error handling and fallbacks
#[inline]
pub fn build_json_response<T: Serialize>(
    status: u16,
    body: &T,
    fallback_message: &str,
) -> axum::response::Response {
    match serde_json::to_vec(body) {
        Ok(body_bytes) => axum::response::Response::builder()
            .status(status)
            .header(http::header::CONTENT_TYPE, "application/json")
            .body(Body::from(body_bytes))
            .unwrap_or_else(|_| build_fallback_response(status, fallback_message)),
        Err(_e) => build_fallback_response(status, fallback_message),
    }
}

/// Build a fallback response when JSON serialization fails
#[inline]
pub fn build_fallback_response(status: u16, message: &str) -> axum::response::Response {
    let escaped_message = message.replace('"', "\\\"");
    let fallback = format!(
        r#"{{"success":false,"error":{{"code":"SERIALIZATION_ERROR","message":"{}"}}}}"#,
        escaped_message
    );
    axum::response::Response::builder()
        .status(status)
        .header(http::header::CONTENT_TYPE, "application/json")
        .body(Body::from(fallback))
        .unwrap_or_else(|_| axum::response::Response::new(Body::empty()))
}

impl IntoResponse for ApiError {
    fn into_response(self) -> axum::response::Response {
        let status = match self {
            ApiError::NotFound { .. } => 404,
            ApiError::InvalidInput { .. } => 400,
            ApiError::AuthenticationFailed { .. } => 401,
            ApiError::AccessDenied { .. } => 403,
            ApiError::RateLimitExceeded { .. } => 429,
            ApiError::Internal { .. } => 500,
            ApiError::ServiceUnavailable { .. } => 503,
            ApiError::ValidationError { .. } => 422,
        };

        build_json_response(status, &self, "Internal server error")
    }
}

impl<T> IntoResponse for ServiceResponse<T>
where
    T: Serialize,
{
    fn into_response(self) -> axum::response::Response {
        let status = self.error.as_ref().map(|e| e.http_status).unwrap_or(200);

        if let Some(ref error) = self.error {
            let error_response = ServiceResponse::<serde_json::Value>::error(error.clone());
            build_json_response(status, &error_response, "Service error")
        } else {
            build_json_response(status, &self, "Response error")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::header;

    #[test]
    fn test_build_json_response_success() {
        #[derive(serde::Serialize)]
        struct Payload {
            value: i32,
        }

        let resp = build_json_response(200, &Payload { value: 42 }, "fallback");
        assert_eq!(resp.status(), 200);
        let content_type = resp.headers().get(header::CONTENT_TYPE).unwrap();
        assert_eq!(content_type, "application/json");
    }

    #[test]
    fn test_build_fallback_response_status_and_header() {
        let resp = build_fallback_response(500, "error");
        assert_eq!(resp.status(), 500);
        let content_type = resp.headers().get(header::CONTENT_TYPE).unwrap();
        assert_eq!(content_type, "application/json");
    }

    #[test]
    fn test_api_error_into_response_status_mapping() {
        let resp = ApiError::NotFound {
            resource: "User".to_string(),
            resource_id: Some("1".to_string()),
        }
        .into_response();
        assert_eq!(resp.status(), 404);
        let resp = ApiError::InvalidInput {
            message: "reason".to_string(),
            field: Some("field".to_string()),
            value: None,
        }
        .into_response();
        assert_eq!(resp.status(), 400);
    }

    #[test]
    fn test_service_response_into_response_success() {
        let resp = ServiceResponse::success("ok").into_response();
        assert_eq!(resp.status(), 200);
    }

    #[test]
    fn test_service_response_into_response_error_status() {
        let err = crate::core::ServiceError::with_details(
            "CODE",
            "message",
            serde_json::json!({"k":"v"}),
            418,
        );
        let resp = ServiceResponse::<String>::error(err).into_response();
        assert_eq!(resp.status(), 418);
    }

    /// Test: all ApiError variants map to the correct HTTP status code.
    /// Covers the previously-uncovered match arms (AuthenticationFailed,
    /// AccessDenied, RateLimitExceeded, Internal, ServiceUnavailable,
    /// ValidationError).
    #[test]
    fn test_api_error_all_variants_status_mapping() {
        let cases: Vec<(u16, ApiError)> = vec![
            (
                401,
                ApiError::AuthenticationFailed {
                    reason: "bad token".to_string(),
                },
            ),
            (
                403,
                ApiError::AccessDenied {
                    permission: "read".to_string(),
                    user_id: None,
                },
            ),
            (
                429,
                ApiError::RateLimitExceeded {
                    limit: 100,
                    window_seconds: 60,
                },
            ),
            (
                500,
                ApiError::Internal {
                    message: "boom".to_string(),
                    error_id: "err-1".to_string(),
                    source: None,
                    context: None,
                },
            ),
            (
                503,
                ApiError::ServiceUnavailable {
                    service: "downstream".to_string(),
                    retry_after: Some(10),
                    source: None,
                },
            ),
            (
                422,
                ApiError::ValidationError {
                    field: "email".to_string(),
                    constraint: "invalid format".to_string(),
                },
            ),
        ];
        for (expected_status, err) in cases {
            let resp = err.into_response();
            assert_eq!(
                resp.status(),
                axum::http::StatusCode::from_u16(expected_status).unwrap(),
                "ApiError variant should map to HTTP {}",
                expected_status
            );
        }
    }

    /// Test: build_json_response falls back when serialization fails.
    /// Covers the `Err(_e)` branch by passing a value whose `Serialize`
    /// implementation returns an error.
    #[test]
    fn test_build_json_response_serialization_failure_fallback() {
        use serde::ser::{self, Serialize, Serializer};

        /// A type that always fails to serialize.
        struct Unserializable;
        impl Serialize for Unserializable {
            fn serialize<S: Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
                Err(ser::Error::custom("intentional serialization failure"))
            }
        }

        let resp = build_json_response(200, &Unserializable, "fallback message");
        // Should fall back to a 200 response with the fallback body.
        assert_eq!(resp.status(), 200);
        let content_type = resp.headers().get(header::CONTENT_TYPE).unwrap();
        assert_eq!(content_type, "application/json");
    }

    /// Test: build_fallback_response escapes embedded double quotes in the
    /// message to keep the emitted JSON valid.
    #[test]
    fn test_build_fallback_response_escapes_quotes() {
        let resp = build_fallback_response(400, r#"bad "value" here"#);
        assert_eq!(resp.status(), 400);
        assert_eq!(
            resp.headers().get(header::CONTENT_TYPE).unwrap(),
            "application/json"
        );
    }

    // ============================================================================
    // Body content verification tests
    //
    // These tests verify the actual JSON body content of responses, not just
    // status codes and headers.
    // ============================================================================

    #[tokio::test]
    async fn test_build_json_response_body_content() {
        #[derive(serde::Serialize)]
        struct Payload {
            name: String,
            count: i32,
        }

        let resp = build_json_response(
            201,
            &Payload {
                name: "test".to_string(),
                count: 5,
            },
            "fallback",
        );
        assert_eq!(resp.status(), 201);

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["name"], "test");
        assert_eq!(parsed["count"], 5);
    }

    #[tokio::test]
    async fn test_build_fallback_response_body_content() {
        let resp = build_fallback_response(500, "something went wrong");
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["success"], false);
        assert_eq!(parsed["error"]["code"], "SERIALIZATION_ERROR");
        assert_eq!(parsed["error"]["message"], "something went wrong");
    }

    #[tokio::test]
    async fn test_build_fallback_response_empty_message() {
        let resp = build_fallback_response(400, "");
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["error"]["message"], "");
    }

    #[tokio::test]
    async fn test_build_fallback_response_escaped_body_valid_json() {
        // Verify that escaped quotes produce valid JSON
        let resp = build_fallback_response(400, r#"bad "value" here"#);
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        // Should parse without error
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["error"]["message"], r#"bad "value" here"#);
    }

    #[tokio::test]
    async fn test_api_error_response_body_contains_error_info() {
        let resp = ApiError::NotFound {
            resource: "User".to_string(),
            resource_id: Some("42".to_string()),
        }
        .into_response();

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        // The response should contain error information
        assert!(parsed.is_object());
    }

    #[tokio::test]
    async fn test_service_response_success_body_content() {
        let resp = ServiceResponse::success("hello").into_response();
        assert_eq!(resp.status(), 200);

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["data"], "hello");
        assert!(parsed.get("error").is_none() || parsed["error"].is_null());
    }

    #[tokio::test]
    async fn test_service_response_error_body_content() {
        let err = crate::core::ServiceError::with_details(
            "CUSTOM_CODE",
            "custom error message",
            serde_json::json!({"detail": "info"}),
            451,
        );
        let resp = ServiceResponse::<String>::error(err).into_response();
        assert_eq!(resp.status(), 451);

        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["error"]["code"], "CUSTOM_CODE");
    }

    #[test]
    fn test_build_json_response_with_various_status_codes() {
        #[derive(serde::Serialize)]
        struct Empty;
        for status in [
            200u16, 201, 204, 301, 400, 401, 403, 404, 422, 429, 500, 503,
        ] {
            let resp = build_json_response(status, &Empty, "fallback");
            assert_eq!(
                resp.status(),
                axum::http::StatusCode::from_u16(status).unwrap(),
                "Status code {} should be preserved",
                status
            );
        }
    }

    #[tokio::test]
    async fn test_build_json_response_serialization_failure_uses_fallback_message() {
        use serde::ser::{self, Serialize, Serializer};

        struct Unserializable;
        impl Serialize for Unserializable {
            fn serialize<S: Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
                Err(ser::Error::custom("intentional failure"))
            }
        }

        let resp = build_json_response(422, &Unserializable, "custom fallback message");
        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let parsed: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(parsed["error"]["message"], "custom fallback message");
        assert_eq!(parsed["error"]["code"], "SERIALIZATION_ERROR");
    }

    // ============================================================================
    // unwrap_or_else fallback branch coverage
    //
    // The `unwrap_or_else` closures in build_json_response (line 27) and
    // build_fallback_response (line 44) are defensive fallbacks triggered when
    // `Response::builder().body()` returns Err. This happens when the status
    // code is invalid (outside the 100..=999 range accepted by
    // `StatusCode::TryFrom<u16>`). Passing a status < 100 (e.g., 99) causes
    // the builder to store an error internally, making `.body()` return Err.
    // ============================================================================

    /// Test build_json_response falls back when given an invalid status code
    /// (< 100). Covers the `unwrap_or_else(|_| build_fallback_response(...))`
    /// branch in build_json_response.
    #[test]
    fn test_build_json_response_invalid_status_triggers_fallback() {
        #[derive(serde::Serialize)]
        struct Payload {
            value: i32,
        }

        // Status 99 is invalid (< 100), causing Response::builder().body() to
        // return Err, which triggers the unwrap_or_else fallback.
        let resp = build_json_response(99, &Payload { value: 42 }, "fallback for invalid status");
        // The response should still be created via the fallback path.
        // The fallback itself also receives the invalid status, so it too
        // falls back to Response::new(Body::empty()).
        // Just verify we get a Response without panic.
        let _ = resp.status();
    }

    /// Test build_fallback_response falls back to an empty body when given an
    /// invalid status code (< 100). Covers the
    /// `unwrap_or_else(|_| axum::response::Response::new(Body::empty()))`
    /// branch in build_fallback_response.
    #[test]
    fn test_build_fallback_response_invalid_status_triggers_empty_body() {
        // Status 99 is invalid, causing both build_json_response and
        // build_fallback_response to hit their unwrap_or_else fallbacks.
        let resp = build_fallback_response(99, "invalid status test");
        // The final fallback is Response::new(Body::empty()), which defaults
        // to status 200. Verify no panic occurs.
        let _ = resp.status();
    }

    /// Test build_json_response with a very large invalid status code (> 999)
    /// also triggers the fallback path.
    #[test]
    fn test_build_json_response_status_above_999_triggers_fallback() {
        #[derive(serde::Serialize)]
        struct Payload {
            value: i32,
        }

        // Status 1000 is invalid (> 999), triggering the fallback.
        let resp = build_json_response(1000, &Payload { value: 42 }, "overflow status");
        let _ = resp.status();
    }
}