crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Unified response builders for presentation layer
//!
//! Provides standardized response formatting to eliminate code duplication
//! across handlers and ensure consistent API responses.

use axum::{
    http::StatusCode,
    response::{IntoResponse, Response},
    Json,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use crate::i18n::{I18nBundle, Locale};

/// Unified API response wrapper
///
/// # Type Parameters
///
/// * `T` - The type of data being returned
#[derive(Debug, Serialize, Deserialize)]
pub struct ApiResponse<T> {
    /// Whether the request was successful
    pub success: bool,
    /// Response data
    pub data: Option<T>,
    /// Error details (only present when success is false)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<ApiError>,
    /// Pagination metadata (only present for list responses)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meta: Option<PaginationMeta>,
    /// Response timestamp in RFC3339 format
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
}

impl<T> ApiResponse<T> {
    /// Create a success response with data
    pub fn success(data: T) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            meta: None,
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        }
    }

    /// Create a success response with data and pagination
    pub fn success_with_meta(data: T, meta: PaginationMeta) -> Self {
        Self {
            success: true,
            data: Some(data),
            error: None,
            meta: Some(meta),
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        }
    }

    /// Create an error response
    pub fn error(code: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            success: false,
            data: None,
            error: Some(ApiError {
                code: code.into(),
                message: message.into(),
            }),
            meta: None,
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        }
    }
}

/// Pagination metadata for list responses
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginationMeta {
    /// Current page number (1-indexed)
    pub page: u32,
    /// Number of items per page
    pub per_page: u32,
    /// Total number of items
    pub total_items: u64,
    /// Total number of pages
    pub total_pages: u32,
    /// Has next page
    pub has_next: bool,
    /// Has previous page
    pub has_previous: bool,
}

impl PaginationMeta {
    /// Create pagination metadata from parameters
    pub fn new(page: u32, per_page: u32, total_items: u64) -> Self {
        let total_pages = if total_items == 0 {
            0
        } else {
            total_items.div_ceil(per_page as u64) as u32
        };

        Self {
            page,
            per_page,
            total_items,
            total_pages,
            has_next: page < total_pages,
            has_previous: page > 1,
        }
    }

    /// Calculate offset for database queries
    pub fn offset(&self) -> u64 {
        ((self.page - 1) * self.per_page) as u64
    }

    /// Calculate limit for database queries
    pub fn limit(&self) -> u32 {
        self.per_page
    }
}

/// Standard API error details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ApiError {
    /// Error code for programmatic handling
    pub code: String,
    /// Human-readable error message
    pub message: String,
}

/// Rate limit error response with retry information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RateLimitErrorResponse {
    /// Whether the request was successful
    pub success: bool,
    /// Error details
    pub error: ApiError,
    /// Seconds to wait before retrying
    pub retry_after_seconds: u64,
    /// Response timestamp in RFC3339 format
    #[serde(skip_serializing_if = "Option::is_none")]
    pub timestamp: Option<String>,
}

impl RateLimitErrorResponse {
    /// Create a new rate limit error response
    pub fn new(message: impl Into<String>, retry_after_seconds: u64) -> Self {
        Self {
            success: false,
            error: ApiError {
                code: error_codes::RATE_LIMITED.to_string(),
                message: message.into(),
            },
            retry_after_seconds,
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        }
    }
}

impl<T: Serialize> IntoResponse for ApiResponse<T> {
    fn into_response(self) -> Response {
        let status = if self.success {
            StatusCode::OK
        } else {
            // Determine status code from error code
            match self.error.as_ref().map(|e| e.code.as_str()) {
                Some("VALIDATION_ERROR") => StatusCode::BAD_REQUEST,
                Some("NOT_FOUND") => StatusCode::NOT_FOUND,
                Some("UNAUTHORIZED") => StatusCode::UNAUTHORIZED,
                Some("FORBIDDEN") => StatusCode::FORBIDDEN,
                Some("RATE_LIMITED") => StatusCode::TOO_MANY_REQUESTS,
                Some("CONFLICT") => StatusCode::CONFLICT,
                Some("PRECONDITION_FAILED") => StatusCode::PRECONDITION_FAILED,
                Some("UNPROCESSABLE_ENTITY") => StatusCode::UNPROCESSABLE_ENTITY,
                _ => StatusCode::INTERNAL_SERVER_ERROR,
            }
        };
        (status, Json(self)).into_response()
    }
}

/// Standard API error response using ApiResponse
#[inline]
pub fn error_response(status: StatusCode, message: impl Into<String>) -> Response {
    // Infer error code from status code
    let code = match status {
        StatusCode::BAD_REQUEST => error_codes::VALIDATION_ERROR,
        StatusCode::NOT_FOUND => error_codes::NOT_FOUND,
        StatusCode::UNAUTHORIZED => error_codes::UNAUTHORIZED,
        StatusCode::FORBIDDEN => error_codes::FORBIDDEN,
        StatusCode::TOO_MANY_REQUESTS => error_codes::RATE_LIMITED,
        StatusCode::CONFLICT => error_codes::CONFLICT,
        StatusCode::PRECONDITION_FAILED => error_codes::PRECONDITION_FAILED,
        StatusCode::UNPROCESSABLE_ENTITY => error_codes::UNPROCESSABLE_ENTITY,
        StatusCode::SERVICE_UNAVAILABLE => error_codes::SERVICE_UNAVAILABLE,
        StatusCode::PAYMENT_REQUIRED => error_codes::QUOTA_EXCEEDED,
        _ => error_codes::INTERNAL_ERROR,
    };
    let response: ApiResponse<()> = ApiResponse::error(code, message);
    (status, Json(response)).into_response()
}

/// API error response with error code using ApiResponse
#[inline]
pub fn error_response_with_code(
    status: StatusCode,
    code: impl Into<String>,
    message: impl Into<String>,
) -> Response {
    let response: ApiResponse<()> = ApiResponse::error(code, message);
    (status, Json(response)).into_response()
}

/// Standard success response with data using ApiResponse
#[inline]
pub fn success_response<T: serde::Serialize>(status: StatusCode, data: T) -> Response {
    (status, Json(ApiResponse::success(data))).into_response()
}

/// Success response with metadata using ApiResponse
#[inline]
pub fn success_response_with_meta<T: serde::Serialize>(
    status: StatusCode,
    data: T,
    meta: PaginationMeta,
) -> Response {
    (status, Json(ApiResponse::success_with_meta(data, meta))).into_response()
}

/// Common error responses for quick access
pub mod errors {
    use super::*;

    /// Internal server error response
    #[inline]
    pub fn internal_server_error(message: impl Into<String>) -> Response {
        error_response(StatusCode::INTERNAL_SERVER_ERROR, message)
    }

    /// Bad request error response
    #[inline]
    pub fn bad_request(message: impl Into<String>) -> Response {
        error_response(StatusCode::BAD_REQUEST, message)
    }

    /// Not found error response
    #[inline]
    pub fn not_found(message: impl Into<String>) -> Response {
        error_response(StatusCode::NOT_FOUND, message)
    }

    /// Forbidden error response
    #[inline]
    pub fn forbidden(message: impl Into<String>) -> Response {
        error_response(StatusCode::FORBIDDEN, message)
    }

    /// Unauthorized error response
    #[inline]
    pub fn unauthorized(message: impl Into<String>) -> Response {
        error_response(StatusCode::UNAUTHORIZED, message)
    }

    /// Too many requests error response
    #[inline]
    pub fn too_many_requests(message: impl Into<String>) -> Response {
        error_response(StatusCode::TOO_MANY_REQUESTS, message)
    }

    /// Too many requests error response with retry_after using RateLimitErrorResponse
    #[inline]
    pub fn too_many_requests_with_retry(
        message: impl Into<String>,
        retry_after_seconds: u64,
    ) -> Response {
        (
            StatusCode::TOO_MANY_REQUESTS,
            Json(RateLimitErrorResponse::new(message, retry_after_seconds)),
        )
            .into_response()
    }

    /// Unprocessable entity error response
    #[inline]
    pub fn unprocessable_entity(message: impl Into<String>) -> Response {
        error_response(StatusCode::UNPROCESSABLE_ENTITY, message)
    }

    /// Service unavailable error response (fail-closed rate-limit backend errors)
    #[inline]
    pub fn service_unavailable(message: impl Into<String>) -> Response {
        error_response(StatusCode::SERVICE_UNAVAILABLE, message)
    }

    /// Payment required error response
    #[inline]
    pub fn payment_required(message: impl Into<String>) -> Response {
        error_response(StatusCode::PAYMENT_REQUIRED, message)
    }
}

/// Validation error response
#[inline]
pub fn validation_error(message: impl Into<String>) -> Response {
    error_response(
        StatusCode::BAD_REQUEST,
        format!("Validation error: {}", message.into()),
    )
}

/// axum `Json` 提取失败的统一包封映射。
///
/// 提取器级别的拒绝(body 非法 JSON / 字段缺失 / Content-Type 不符)默认
/// 返回 axum 纯文本响应,绕过 `ApiResponse` 包封——客户端若按包封契约解析
/// 会静默失败。此助手把各类拒绝映射为与 handler 侧校验一致的包封响应,
/// 状态码语义与 axum 默认对齐(语法错 400、数据错 422、类型不符 415)。
pub fn json_rejection_response(rejection: &axum::extract::rejection::JsonRejection) -> Response {
    use axum::extract::rejection::JsonRejection;

    match rejection {
        JsonRejection::JsonDataError(err) => error_response_with_code(
            StatusCode::UNPROCESSABLE_ENTITY,
            error_codes::UNPROCESSABLE_ENTITY,
            err.body_text(),
        ),
        JsonRejection::JsonSyntaxError(err) => error_response_with_code(
            StatusCode::BAD_REQUEST,
            error_codes::VALIDATION_ERROR,
            err.body_text(),
        ),
        JsonRejection::MissingJsonContentType(err) => (
            StatusCode::UNSUPPORTED_MEDIA_TYPE,
            Json(ApiResponse::<()>::error(
                error_codes::VALIDATION_ERROR,
                err.body_text(),
            )),
        )
            .into_response(),
        _ => error_response_with_code(
            StatusCode::BAD_REQUEST,
            error_codes::VALIDATION_ERROR,
            rejection.body_text(),
        ),
    }
}

/// `Json` 提取失败 → `CrawlRsError`(供返回 `Result<Json<_>, CrawlRsError>`
/// 形态的 handler 使用),状态语义与 [`json_rejection_response`] 对齐:
/// 结构错误(字段缺失/类型不符)422,语法错误 400。
pub fn json_rejection_error(
    rejection: axum::extract::rejection::JsonRejection,
) -> crate::common::error::CrawlRsError {
    use axum::extract::rejection::JsonRejection;

    match rejection {
        JsonRejection::JsonDataError(err) => {
            crate::common::error::CrawlRsError::Unprocessable(err.body_text())
        }
        _ => crate::common::error::CrawlRsError::Validation(rejection.body_text()),
    }
}

/// Not found response for resources
#[inline]
pub fn resource_not_found(resource: impl Into<String>) -> Response {
    errors::not_found(format!("{} not found", resource.into()))
}

/// Access denied response
#[inline]
pub fn access_denied() -> Response {
    errors::forbidden("Access denied")
}

// Locale-aware error helpers

/// Locale-aware error response
///
/// Uses the i18n bundle to translate the FTL `key` into the request's locale.
#[inline]
pub fn error_response_locale(
    status: StatusCode,
    locale: &Locale,
    bundle: &Arc<I18nBundle>,
    key: &str,
) -> Response {
    let message = crate::i18n::t(locale, bundle, key);
    error_response(status, message)
}

/// Locale-aware error response with arguments
#[inline]
pub fn error_response_locale_with_args(
    status: StatusCode,
    locale: &Locale,
    bundle: &Arc<I18nBundle>,
    key: &str,
    args: &[(&str, String)],
) -> Response {
    let message = crate::i18n::t_with_args(locale, bundle, key, args);
    error_response(status, message)
}

/// Locale-aware error helpers module
pub mod errors_locale {
    use super::*;

    /// Forbidden response with locale
    #[inline]
    pub fn forbidden(locale: &Locale, bundle: &Arc<I18nBundle>, key: &str) -> Response {
        let message = crate::i18n::t(locale, bundle, key);
        errors::forbidden(message)
    }

    /// Not found response with locale
    #[inline]
    pub fn not_found(locale: &Locale, bundle: &Arc<I18nBundle>, key: &str) -> Response {
        let message = crate::i18n::t(locale, bundle, key);
        errors::not_found(message)
    }

    /// Internal server error response with locale
    #[inline]
    pub fn internal_server_error(locale: &Locale, bundle: &Arc<I18nBundle>, key: &str) -> Response {
        let message = crate::i18n::t(locale, bundle, key);
        errors::internal_server_error(message)
    }

    /// Too many requests response with locale
    #[inline]
    pub fn too_many_requests(locale: &Locale, bundle: &Arc<I18nBundle>, key: &str) -> Response {
        let message = crate::i18n::t(locale, bundle, key);
        errors::too_many_requests(message)
    }

    /// Bad request response with locale
    #[inline]
    pub fn bad_request(locale: &Locale, bundle: &Arc<I18nBundle>, key: &str) -> Response {
        let message = crate::i18n::t(locale, bundle, key);
        errors::bad_request(message)
    }
}

/// Standard error codes for API responses
pub mod error_codes {
    /// Validation failed
    pub const VALIDATION_ERROR: &str = "VALIDATION_ERROR";
    /// Resource not found
    pub const NOT_FOUND: &str = "NOT_FOUND";
    /// Unauthorized access
    pub const UNAUTHORIZED: &str = "UNAUTHORIZED";
    /// Forbidden access
    pub const FORBIDDEN: &str = "FORBIDDEN";
    /// Rate limit exceeded
    pub const RATE_LIMITED: &str = "RATE_LIMITED";
    /// Resource conflict
    pub const CONFLICT: &str = "CONFLICT";
    /// Precondition failed
    pub const PRECONDITION_FAILED: &str = "PRECONDITION_FAILED";
    /// Unprocessable entity
    pub const UNPROCESSABLE_ENTITY: &str = "UNPROCESSABLE_ENTITY";
    /// Internal server error
    pub const INTERNAL_ERROR: &str = "INTERNAL_ERROR";
    /// Service unavailable
    pub const SERVICE_UNAVAILABLE: &str = "SERVICE_UNAVAILABLE";
    /// Database error
    pub const DATABASE_ERROR: &str = "DATABASE_ERROR";
    /// Cache error
    pub const CACHE_ERROR: &str = "CACHE_ERROR";
    /// External service error
    pub const EXTERNAL_SERVICE_ERROR: &str = "EXTERNAL_SERVICE_ERROR";
    /// Timeout error
    pub const TIMEOUT: &str = "TIMEOUT";
    /// Quota exceeded
    pub const QUOTA_EXCEEDED: &str = "QUOTA_EXCEEDED";
    /// Feature not enabled
    pub const FEATURE_DISABLED: &str = "FEATURE_DISABLED";
}

/// 校验失败响应文案:只输出字段名与约束码,不输出 Debug 参数值
/// (审查 L3:`ValidationErrors` 的 Debug 会带出内部字段路径与约束参数)。
pub fn validation_error_message(errors: &sdforge::validator::ValidationErrors) -> String {
    let mut parts: Vec<String> = Vec::new();
    for (field, errs) in errors.field_errors() {
        let codes: Vec<String> = errs.iter().map(|e| e.code.to_string()).collect();
        if codes.is_empty() {
            parts.push(field.to_string());
        } else {
            parts.push(format!("{} ({})", field, codes.join(",")));
        }
    }
    parts.sort();
    if parts.is_empty() {
        "Validation failed".to_string()
    } else {
        format!("Validation failed - {}", parts.join("; "))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use chrono::DateTime as ChronoDateTime;

    #[test]
    fn test_api_response_success_has_timestamp() {
        let response = ApiResponse::success("test data");
        assert!(response.success);
        assert_eq!(response.data, Some("test data"));
        assert!(response.timestamp.is_some());
        // Verify timestamp is RFC3339 format
        let ts = response.timestamp.unwrap();
        assert!(ts.contains('-'));
        assert!(ts.contains(':'));
    }

    #[test]
    fn test_api_response_error_has_timestamp() {
        let response: ApiResponse<()> = ApiResponse::error("TEST_ERROR", "Test error message");
        assert!(!response.success);
        assert!(response.error.is_some());
        assert_eq!(response.error.as_ref().unwrap().code, "TEST_ERROR");
        assert!(response.timestamp.is_some());
    }

    #[test]
    fn test_api_response_success_with_meta_has_timestamp() {
        let meta = PaginationMeta::new(1, 10, 100);
        let response = ApiResponse::success_with_meta("data", meta);
        assert!(response.success);
        assert!(response.meta.is_some());
        assert!(response.timestamp.is_some());
    }

    #[test]
    fn test_timestamp_is_recent() {
        use chrono::Utc;

        let response = ApiResponse::success("test");
        let ts_str = response.timestamp.unwrap();
        let parsed = ChronoDateTime::parse_from_rfc3339(&ts_str).unwrap();
        let now = Utc::now();

        // Timestamp should be within 1 second of now
        let diff = (now.timestamp() - parsed.timestamp()).abs();
        assert!(diff < 2);
    }

    // PaginationMeta tests

    #[test]
    fn test_pagination_meta_new_with_zero_items() {
        let meta = PaginationMeta::new(1, 10, 0);
        assert_eq!(meta.page, 1);
        assert_eq!(meta.per_page, 10);
        assert_eq!(meta.total_items, 0);
        assert_eq!(meta.total_pages, 0);
        assert!(!meta.has_next);
        assert!(!meta.has_previous);
    }

    #[test]
    fn test_pagination_meta_new_exact_pages() {
        // 100 items, 10 per page -> 10 pages
        let meta = PaginationMeta::new(1, 10, 100);
        assert_eq!(meta.total_pages, 10);
        assert!(meta.has_next);
        assert!(!meta.has_previous);
    }

    #[test]
    fn test_pagination_meta_new_partial_last_page() {
        // 95 items, 10 per page -> 10 pages (95/10 = 9.5, ceil = 10)
        let meta = PaginationMeta::new(1, 10, 95);
        assert_eq!(meta.total_pages, 10);
    }

    #[test]
    fn test_pagination_meta_has_next_false_on_last_page() {
        let meta = PaginationMeta::new(10, 10, 100);
        assert_eq!(meta.total_pages, 10);
        assert!(!meta.has_next);
        assert!(meta.has_previous);
    }

    #[test]
    fn test_pagination_meta_has_previous_false_on_first_page() {
        let meta = PaginationMeta::new(1, 10, 100);
        assert!(!meta.has_previous);
    }

    #[test]
    fn test_pagination_meta_has_previous_true_on_page_two() {
        let meta = PaginationMeta::new(2, 10, 100);
        assert!(meta.has_previous);
    }

    #[test]
    fn test_pagination_meta_offset_first_page() {
        let meta = PaginationMeta::new(1, 10, 100);
        assert_eq!(meta.offset(), 0);
    }

    #[test]
    fn test_pagination_meta_offset_second_page() {
        let meta = PaginationMeta::new(2, 10, 100);
        assert_eq!(meta.offset(), 10);
    }

    #[test]
    fn test_pagination_meta_offset_third_page() {
        let meta = PaginationMeta::new(3, 20, 100);
        assert_eq!(meta.offset(), 40);
    }

    #[test]
    fn test_pagination_meta_limit_equals_per_page() {
        let meta = PaginationMeta::new(1, 25, 100);
        assert_eq!(meta.limit(), 25);
    }

    #[test]
    fn test_pagination_meta_div_ceil_one_item_one_per_page() {
        let meta = PaginationMeta::new(1, 1, 1);
        assert_eq!(meta.total_pages, 1);
        assert!(!meta.has_next);
    }

    // IntoResponse status code mapping

    #[tokio::test]
    async fn test_into_response_success_returns_200() {
        let response = ApiResponse::success("data");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_into_response_validation_error_returns_400() {
        let response: ApiResponse<()> = ApiResponse::error("VALIDATION_ERROR", "bad input");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_into_response_not_found_returns_404() {
        let response: ApiResponse<()> = ApiResponse::error("NOT_FOUND", "missing");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_into_response_unauthorized_returns_401() {
        let response: ApiResponse<()> = ApiResponse::error("UNAUTHORIZED", "no auth");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn test_into_response_forbidden_returns_403() {
        let response: ApiResponse<()> = ApiResponse::error("FORBIDDEN", "denied");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::FORBIDDEN);
    }

    #[tokio::test]
    async fn test_into_response_rate_limited_returns_429() {
        let response: ApiResponse<()> = ApiResponse::error("RATE_LIMITED", "slow down");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::TOO_MANY_REQUESTS);
    }

    #[tokio::test]
    async fn test_into_response_conflict_returns_409() {
        let response: ApiResponse<()> = ApiResponse::error("CONFLICT", "dup");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::CONFLICT);
    }

    #[tokio::test]
    async fn test_into_response_precondition_failed_returns_412() {
        let response: ApiResponse<()> = ApiResponse::error("PRECONDITION_FAILED", "precond");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::PRECONDITION_FAILED);
    }

    #[tokio::test]
    async fn test_into_response_unprocessable_entity_returns_422() {
        let response: ApiResponse<()> = ApiResponse::error("UNPROCESSABLE_ENTITY", "unprocessable");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::UNPROCESSABLE_ENTITY);
    }

    #[tokio::test]
    async fn test_into_response_unknown_code_returns_500() {
        let response: ApiResponse<()> = ApiResponse::error("UNKNOWN_CODE", "oops");
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    #[tokio::test]
    async fn test_into_response_error_no_error_field_returns_500() {
        // Manually construct a response with success=false but no error
        let response: ApiResponse<()> = ApiResponse {
            success: false,
            data: None,
            error: None,
            meta: None,
            timestamp: Some(chrono::Utc::now().to_rfc3339()),
        };
        let http_response = response.into_response();
        assert_eq!(http_response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    }

    // JSON serialization structure

    #[tokio::test]
    async fn test_success_response_json_structure() {
        let response = ApiResponse::success("hello");
        let http_response = response.into_response();
        let bytes = axum::body::to_bytes(http_response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["success"], serde_json::Value::Bool(true));
        assert_eq!(json["data"], serde_json::Value::String("hello".to_string()));
        assert!(json.get("error").is_none() || json["error"].is_null());
        assert!(json.get("meta").is_none() || json["meta"].is_null());
        assert!(json["timestamp"].is_string());
    }

    #[tokio::test]
    async fn test_error_response_json_structure() {
        let response: ApiResponse<()> = ApiResponse::error("NOT_FOUND", "not here");
        let http_response = response.into_response();
        let bytes = axum::body::to_bytes(http_response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["success"], serde_json::Value::Bool(false));
        assert!(json.get("data").is_none() || json["data"].is_null());
        assert_eq!(json["error"]["code"], "NOT_FOUND");
        assert_eq!(json["error"]["message"], "not here");
    }

    #[tokio::test]
    async fn test_success_with_meta_json_includes_meta() {
        let meta = PaginationMeta::new(2, 10, 55);
        let response = ApiResponse::success_with_meta(vec!["a", "b"], meta);
        let http_response = response.into_response();
        let bytes = axum::body::to_bytes(http_response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["meta"]["page"], 2);
        assert_eq!(json["meta"]["per_page"], 10);
        assert_eq!(json["meta"]["total_items"], 55);
        assert_eq!(json["meta"]["total_pages"], 6);
        assert_eq!(json["meta"]["has_next"], true);
        assert_eq!(json["meta"]["has_previous"], true);
    }

    // error_response function

    #[tokio::test]
    async fn test_error_response_bad_request() {
        let response = error_response(StatusCode::BAD_REQUEST, "bad data");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["success"], false);
        assert_eq!(json["error"]["code"], "VALIDATION_ERROR");
        assert_eq!(json["error"]["message"], "bad data");
    }

    #[tokio::test]
    async fn test_error_response_not_found() {
        let response = error_response(StatusCode::NOT_FOUND, "missing");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "NOT_FOUND");
    }

    #[tokio::test]
    async fn test_error_response_unauthorized() {
        let response = error_response(StatusCode::UNAUTHORIZED, "no token");
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "UNAUTHORIZED");
    }

    #[tokio::test]
    async fn test_error_response_forbidden() {
        let response = error_response(StatusCode::FORBIDDEN, "denied");
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "FORBIDDEN");
    }

    #[tokio::test]
    async fn test_error_response_too_many_requests() {
        let response = error_response(StatusCode::TOO_MANY_REQUESTS, "slow");
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "RATE_LIMITED");
    }

    #[tokio::test]
    async fn test_error_response_conflict() {
        let response = error_response(StatusCode::CONFLICT, "dup");
        assert_eq!(response.status(), StatusCode::CONFLICT);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "CONFLICT");
    }

    #[tokio::test]
    async fn test_error_response_precondition_failed() {
        let response = error_response(StatusCode::PRECONDITION_FAILED, "precond");
        assert_eq!(response.status(), StatusCode::PRECONDITION_FAILED);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "PRECONDITION_FAILED");
    }

    #[tokio::test]
    async fn test_error_response_unprocessable_entity() {
        let response = error_response(StatusCode::UNPROCESSABLE_ENTITY, "unprocessable");
        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "UNPROCESSABLE_ENTITY");
    }

    #[tokio::test]
    async fn test_error_response_service_unavailable() {
        let response = error_response(StatusCode::SERVICE_UNAVAILABLE, "down");
        assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "SERVICE_UNAVAILABLE");
    }

    #[tokio::test]
    async fn test_error_response_payment_required() {
        let response = error_response(StatusCode::PAYMENT_REQUIRED, "pay up");
        assert_eq!(response.status(), StatusCode::PAYMENT_REQUIRED);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "QUOTA_EXCEEDED");
    }

    #[tokio::test]
    async fn test_error_response_internal_error_default() {
        let response = error_response(StatusCode::INTERNAL_SERVER_ERROR, "boom");
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "INTERNAL_ERROR");
    }

    // error_response_with_code function

    #[tokio::test]
    async fn test_error_response_with_code_custom() {
        let response =
            error_response_with_code(StatusCode::BAD_REQUEST, "CUSTOM_CODE", "custom msg");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "CUSTOM_CODE");
        assert_eq!(json["error"]["message"], "custom msg");
    }

    #[tokio::test]
    async fn test_error_response_with_code_preserves_status() {
        let response =
            error_response_with_code(StatusCode::NOT_FOUND, "CUSTOM_404", "not found custom");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    // success_response function

    #[tokio::test]
    async fn test_success_response_with_data() {
        let response = success_response(StatusCode::OK, vec!["a", "b"]);
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["success"], true);
        assert_eq!(json["data"], serde_json::json!(["a", "b"]));
    }

    #[tokio::test]
    async fn test_success_response_with_created_status() {
        let response = success_response(StatusCode::CREATED, "created");
        assert_eq!(response.status(), StatusCode::CREATED);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["data"], "created");
    }

    // success_response_with_meta function

    #[tokio::test]
    async fn test_success_response_with_meta_includes_pagination() {
        let meta = PaginationMeta::new(1, 5, 12);
        let response = success_response_with_meta(StatusCode::OK, vec![1, 2, 3, 4, 5], meta);
        assert_eq!(response.status(), StatusCode::OK);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["meta"]["total_pages"], 3);
        assert_eq!(json["meta"]["has_next"], true);
        assert_eq!(json["data"], serde_json::json!([1, 2, 3, 4, 5]));
    }

    // errors module

    #[tokio::test]
    async fn test_errors_internal_server_error() {
        let response = errors::internal_server_error("internal");
        assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "INTERNAL_ERROR");
        assert_eq!(json["error"]["message"], "internal");
    }

    #[tokio::test]
    async fn test_errors_bad_request() {
        let response = errors::bad_request("bad");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "VALIDATION_ERROR");
    }

    #[tokio::test]
    async fn test_errors_not_found() {
        let response = errors::not_found("absent");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "NOT_FOUND");
        assert_eq!(json["error"]["message"], "absent");
    }

    #[tokio::test]
    async fn test_errors_forbidden() {
        let response = errors::forbidden("no access");
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "FORBIDDEN");
    }

    #[tokio::test]
    async fn test_errors_unauthorized() {
        let response = errors::unauthorized("no auth");
        assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "UNAUTHORIZED");
    }

    #[tokio::test]
    async fn test_errors_too_many_requests() {
        let response = errors::too_many_requests("slow down");
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "RATE_LIMITED");
    }

    #[tokio::test]
    async fn test_errors_too_many_requests_with_retry() {
        let response = errors::too_many_requests_with_retry("rate limited", 60);
        assert_eq!(response.status(), StatusCode::TOO_MANY_REQUESTS);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["success"], false);
        assert_eq!(json["error"]["code"], "RATE_LIMITED");
        assert_eq!(json["error"]["message"], "rate limited");
        assert_eq!(json["retry_after_seconds"], 60);
        assert!(json["timestamp"].is_string());
    }

    #[tokio::test]
    async fn test_errors_unprocessable_entity() {
        let response = errors::unprocessable_entity("cannot process");
        assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "UNPROCESSABLE_ENTITY");
    }

    #[tokio::test]
    async fn test_errors_payment_required() {
        let response = errors::payment_required("pay up");
        assert_eq!(response.status(), StatusCode::PAYMENT_REQUIRED);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "QUOTA_EXCEEDED");
    }

    // validation_error & resource_not_found & access_denied

    #[tokio::test]
    async fn test_validation_error_prepends_prefix() {
        let response = validation_error("field required");
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "VALIDATION_ERROR");
        assert_eq!(json["error"]["message"], "Validation error: field required");
    }

    #[tokio::test]
    async fn test_resource_not_found_appends_suffix() {
        let response = resource_not_found("Task");
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "NOT_FOUND");
        assert_eq!(json["error"]["message"], "Task not found");
    }

    #[tokio::test]
    async fn test_access_denied_returns_forbidden() {
        let response = access_denied();
        assert_eq!(response.status(), StatusCode::FORBIDDEN);
        let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();
        assert_eq!(json["error"]["code"], "FORBIDDEN");
        assert_eq!(json["error"]["message"], "Access denied");
    }

    // RateLimitErrorResponse

    #[test]
    fn test_rate_limit_error_response_fields() {
        let resp = RateLimitErrorResponse::new("too many", 30);
        assert!(!resp.success);
        assert_eq!(resp.error.code, "RATE_LIMITED");
        assert_eq!(resp.error.message, "too many");
        assert_eq!(resp.retry_after_seconds, 30);
        assert!(resp.timestamp.is_some());
    }

    #[tokio::test]
    async fn test_rate_limit_error_response_serialization() {
        let resp = RateLimitErrorResponse::new("limited", 120);
        let json_str = serde_json::to_string(&resp).unwrap();
        let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();
        assert_eq!(json["success"], false);
        assert_eq!(json["error"]["code"], "RATE_LIMITED");
        assert_eq!(json["retry_after_seconds"], 120);
    }

    // ApiError struct

    #[test]
    fn test_api_error_serialization() {
        let err = ApiError {
            code: "TEST_CODE".to_string(),
            message: "test message".to_string(),
        };
        let json = serde_json::to_string(&err).unwrap();
        assert!(json.contains("TEST_CODE"));
        assert!(json.contains("test message"));
    }

    #[test]
    fn test_api_error_deserialization() {
        let json = r#"{"code":"ERR","message":"msg"}"#;
        let err: ApiError = serde_json::from_str(json).unwrap();
        assert_eq!(err.code, "ERR");
        assert_eq!(err.message, "msg");
    }

    // ApiResponse round-trip deserialization

    #[test]
    fn test_api_response_round_trip_success() {
        let original = ApiResponse::success(vec![1, 2, 3]);
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: ApiResponse<Vec<i32>> = serde_json::from_str(&json).unwrap();
        assert!(deserialized.success);
        assert_eq!(deserialized.data, Some(vec![1, 2, 3]));
    }

    #[test]
    fn test_pagination_meta_round_trip() {
        let original = PaginationMeta::new(3, 15, 42);
        let json = serde_json::to_string(&original).unwrap();
        let deserialized: PaginationMeta = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.page, original.page);
        assert_eq!(deserialized.per_page, original.per_page);
        assert_eq!(deserialized.total_items, original.total_items);
        assert_eq!(deserialized.total_pages, original.total_pages);
        assert_eq!(deserialized.has_next, original.has_next);
        assert_eq!(deserialized.has_previous, original.has_previous);
    }

    // RateLimitErrorResponse 反序列化

    #[test]
    fn test_rate_limit_error_response_deserialization() {
        let json = r#"{"success":false,"error":{"code":"RATE_LIMITED","message":"slow down"},"retry_after_seconds":45,"timestamp":"2025-01-01T00:00:00Z"}"#;
        let resp: RateLimitErrorResponse = serde_json::from_str(json).unwrap();
        assert!(!resp.success);
        assert_eq!(resp.error.code, "RATE_LIMITED");
        assert_eq!(resp.error.message, "slow down");
        assert_eq!(resp.retry_after_seconds, 45);
        assert!(resp.timestamp.is_some());
    }
}