flatbed 0.0.4

Rust HTTP framework with FlatBuffer codegen, built on Hyper
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
1180
1181
1182
1183
1184
1185
1186
1187
//! Integration tests for hyper-based flatbed server
//!
//! These tests verify:
//! - Route registration and validation
//! - JSON and FlatBuffer content negotiation
//! - HTTP methods (GET, POST, PUT, etc.)
//! - Error responses
//! - Header handling
//! - Telemetry endpoints
//! - OpenAPI endpoints
//! - Worker registration and execution

// Generated test types (plain structs as primary API)
#[path = "../src/generated/test_flatbed.rs"]
#[allow(warnings, clippy::all)]
mod generated;

mod common;

// Import plain structs
use generated::test::{TestRequest, TestResponse};

use flatbed::{
    get_routes, get_workers, route, validate_routes, FlatbedRouteError, FlatbedWorkerError,
    Request, Response, Worker,
};
use std::any::Any;
use std::sync::Arc;

/// Create a dummy context for test handler calls (no context needed)
fn dummy_ctx() -> Arc<dyn Any + Send + Sync> {
    Arc::new(())
}

// ============================================================================
// Test handlers using async pattern with Request<T> and Response<T>
// ============================================================================

#[route("/api/ping")]
async fn test_ping_handler(
    req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError> {
    let msg = req.body.message.as_deref().unwrap_or("no message");

    Ok(Response::ok(TestResponse {
        message: Some(format!("Test pong: {}", msg)),
        value: req.body.value + 100,
        success: true,
    }))
}

#[route("/api/health")]
async fn test_health_handler(
    req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError> {
    Ok(Response::ok(TestResponse {
        message: Some("Healthy".to_string()),
        value: req.body.value,
        success: true,
    }))
}

#[route("/api/error")]
async fn test_error_handler(
    _req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError> {
    Err(FlatbedRouteError::bad_request("Test error message").code("TEST_ERROR"))
}

#[route("/api/resource", method = "GET", tag = "Resources")]
async fn test_get_handler(
    req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError> {
    Ok(Response::ok(TestResponse {
        message: Some("Got resource".to_string()),
        value: req.body.value,
        success: true,
    }))
}

#[route("/api/resource", method = "PUT", tag = "Resources")]
async fn test_put_handler(
    req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError> {
    Ok(Response::ok(TestResponse {
        message: Some("Updated resource".to_string()),
        value: req.body.value,
        success: true,
    }))
}

/// Handler that returns response with custom headers
#[route("/api/with-headers")]
async fn test_response_headers_handler(
    req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError> {
    Ok(Response::ok(TestResponse {
        message: Some("Response with headers".to_string()),
        value: req.body.value,
        success: true,
    })
    .header("x-custom-header", "custom-value")
    .header("x-another-header", "another-value"))
}

/// Handler that returns error with details
#[route("/api/error-with-details")]
async fn test_error_with_details_handler(
    _req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError<TestResponse>> {
    Err(FlatbedRouteError::bad_request("Validation failed")
        .code("VALIDATION_ERROR")
        .header("x-error-source", "validation")
        .with_details(TestResponse {
            message: Some("field 'email' is invalid".to_string()),
            value: 42,
            success: false,
        }))
}

/// Handler that returns error with custom headers
#[route("/api/error-with-headers")]
async fn test_error_with_headers_handler(
    _req: Request<TestRequest>,
) -> Result<Response<TestResponse>, FlatbedRouteError> {
    Err(FlatbedRouteError::not_found("Resource not found")
        .code("NOT_FOUND")
        .header("x-error-type", "not_found")
        .header("x-retry-after", "60"))
}

// ============================================================================
// Tests
// ============================================================================

#[test]
fn test_route_validation() {
    // Validate that all routes are unique
    let result = validate_routes();
    assert!(result.is_ok(), "Route validation should pass");
}

#[test]
fn test_route_registration() {
    let routes = get_routes();

    // Check that our test routes are registered
    assert!(
        routes.contains_key(&("/api/ping".to_string(), flatbed::HttpMethod::Post)),
        "Route POST /api/ping should be registered"
    );
    assert!(
        routes.contains_key(&("/api/health".to_string(), flatbed::HttpMethod::Post)),
        "Route POST /api/health should be registered"
    );

    // Verify route info including method
    let ping_route = routes
        .get(&("/api/ping".to_string(), flatbed::HttpMethod::Post))
        .unwrap();
    assert_eq!(ping_route.path, "/api/ping");
    assert_eq!(ping_route.method, flatbed::HttpMethod::Post);
    assert_eq!(ping_route.request_type, "TestRequest");

    // Verify GET method route
    let get_route = routes
        .get(&("/api/resource".to_string(), flatbed::HttpMethod::Get))
        .unwrap();
    assert_eq!(get_route.method, flatbed::HttpMethod::Get);

    // Verify PUT method route on same path
    let put_route = routes
        .get(&("/api/resource".to_string(), flatbed::HttpMethod::Put))
        .unwrap();
    assert_eq!(put_route.method, flatbed::HttpMethod::Put);
}

#[tokio::test]
async fn test_hyper_handler_json() {
    // Test the generated hyper handler directly
    let request = TestRequest {
        message: Some("Integration test message".to_string()),
        value: 9999,
    };
    let request_bytes = flatbed::serde_json::to_vec(&request).unwrap();

    // Build request parts
    let parts = flatbed::RequestParts::new(flatbed::Method::POST, "/api/ping".to_string());

    // Call the handler
    let result =
        __hyper_handler_test_ping_handler(parts, request_bytes, "application/json", dummy_ctx())
            .await;
    assert!(result.is_ok(), "Handler should succeed");

    let response_parts = result.unwrap();
    assert_eq!(response_parts.status, flatbed::StatusCode::OK);
    assert_eq!(response_parts.content_type, "application/json");

    // Parse response
    let response: TestResponse =
        flatbed::serde_json::from_slice(&response_parts.body).expect("Should deserialize response");
    assert!(response.success);
    assert_eq!(response.value, 9999 + 100);
    assert!(response
        .message
        .as_deref()
        .unwrap()
        .contains("Integration test message"));
}

#[tokio::test]
async fn test_hyper_handler_flatbuffer() {
    // Test with FlatBuffer content type
    let request = TestRequest {
        message: Some("FlatBuffer test".to_string()),
        value: 1234,
    };
    let request_bytes = request.to_flatbuffer();

    let parts = flatbed::RequestParts::new(flatbed::Method::POST, "/api/ping".to_string());

    let result = __hyper_handler_test_ping_handler(
        parts,
        request_bytes,
        "application/x-flatbuffers",
        dummy_ctx(),
    )
    .await;
    assert!(result.is_ok());

    let response_parts = result.unwrap();
    assert_eq!(response_parts.content_type, "application/x-flatbuffers");

    // Parse response
    let response =
        TestResponse::from_flatbuffer(&response_parts.body).expect("Should deserialize response");
    assert!(response.success);
    assert_eq!(response.value, 1234 + 100);
}

#[tokio::test]
async fn test_error_response_json() {
    let request = TestRequest {
        message: Some("test".to_string()),
        value: 0,
    };
    let request_bytes = flatbed::serde_json::to_vec(&request).unwrap();
    let parts = flatbed::RequestParts::new(flatbed::Method::POST, "/api/error".to_string());

    let result =
        __hyper_handler_test_error_handler(parts, request_bytes, "application/json", dummy_ctx())
            .await;
    assert!(result.is_ok());

    let response_parts = result.unwrap();
    assert_eq!(response_parts.status, flatbed::StatusCode::BAD_REQUEST);

    // Parse error body
    let error_body: serde_json::Value =
        serde_json::from_slice(&response_parts.body).expect("Should deserialize error");
    assert_eq!(error_body["code"], "TEST_ERROR");
    assert_eq!(error_body["message"], "Test error message");
}

#[tokio::test]
async fn test_request_id_propagation() {
    let request = TestRequest {
        message: Some("test".to_string()),
        value: 0,
    };
    let request_bytes = flatbed::serde_json::to_vec(&request).unwrap();

    let mut parts = flatbed::RequestParts::new(flatbed::Method::POST, "/api/ping".to_string());
    parts.headers.insert(
        "x-request-id",
        flatbed::HeaderValue::from_static("custom-request-id-123"),
    );
    parts = parts.with_request_id_from_header();

    let result =
        __hyper_handler_test_ping_handler(parts, request_bytes, "application/json", dummy_ctx())
            .await;
    assert!(result.is_ok());

    let response_parts = result.unwrap();
    assert_eq!(
        response_parts
            .headers
            .get("x-request-id")
            .and_then(|v| v.to_str().ok()),
        Some("custom-request-id-123")
    );
}

#[tokio::test]
async fn test_response_with_custom_headers() {
    let request = TestRequest {
        message: Some("test".to_string()),
        value: 123,
    };
    let request_bytes = flatbed::serde_json::to_vec(&request).unwrap();
    let parts = flatbed::RequestParts::new(flatbed::Method::POST, "/api/with-headers".to_string());

    let result = __hyper_handler_test_response_headers_handler(
        parts,
        request_bytes,
        "application/json",
        dummy_ctx(),
    )
    .await;
    assert!(result.is_ok());

    let response_parts = result.unwrap();
    assert_eq!(
        response_parts
            .headers
            .get("x-custom-header")
            .and_then(|v| v.to_str().ok()),
        Some("custom-value")
    );
    assert_eq!(
        response_parts
            .headers
            .get("x-another-header")
            .and_then(|v| v.to_str().ok()),
        Some("another-value")
    );
}

#[tokio::test]
async fn test_error_with_details() {
    let request = TestRequest {
        message: Some("test".to_string()),
        value: 0,
    };
    let request_bytes = flatbed::serde_json::to_vec(&request).unwrap();
    let parts =
        flatbed::RequestParts::new(flatbed::Method::POST, "/api/error-with-details".to_string());

    let result = __hyper_handler_test_error_with_details_handler(
        parts,
        request_bytes,
        "application/json",
        dummy_ctx(),
    )
    .await;
    assert!(result.is_ok());

    let response_parts = result.unwrap();
    assert_eq!(response_parts.status, flatbed::StatusCode::BAD_REQUEST);

    // Verify error header
    assert_eq!(
        response_parts
            .headers
            .get("x-error-source")
            .and_then(|v| v.to_str().ok()),
        Some("validation")
    );

    // Parse error body
    let error_body: serde_json::Value =
        serde_json::from_slice(&response_parts.body).expect("Should deserialize error");
    assert_eq!(error_body["code"], "VALIDATION_ERROR");
    assert_eq!(error_body["message"], "Validation failed");
    assert!(error_body["details"].is_object());
    assert_eq!(error_body["details"]["message"], "field 'email' is invalid");
}

#[tokio::test]
async fn test_error_with_custom_headers() {
    let request = TestRequest {
        message: Some("test".to_string()),
        value: 0,
    };
    let request_bytes = flatbed::serde_json::to_vec(&request).unwrap();
    let parts =
        flatbed::RequestParts::new(flatbed::Method::POST, "/api/error-with-headers".to_string());

    let result = __hyper_handler_test_error_with_headers_handler(
        parts,
        request_bytes,
        "application/json",
        dummy_ctx(),
    )
    .await;
    assert!(result.is_ok());

    let response_parts = result.unwrap();
    assert_eq!(response_parts.status, flatbed::StatusCode::NOT_FOUND);

    assert_eq!(
        response_parts
            .headers
            .get("x-error-type")
            .and_then(|v| v.to_str().ok()),
        Some("not_found")
    );
    assert_eq!(
        response_parts
            .headers
            .get("x-retry-after")
            .and_then(|v| v.to_str().ok()),
        Some("60")
    );
}

#[tokio::test]
async fn test_flatbuffer_hyphenated_content_type() {
    // Test that hyphenated content type (application/x-flat-buffers) works
    let request = TestRequest {
        message: Some("Hyphenated content type test".to_string()),
        value: 5678,
    };
    let request_bytes = request.to_flatbuffer();
    let parts = flatbed::RequestParts::new(flatbed::Method::POST, "/api/ping".to_string());

    let result = __hyper_handler_test_ping_handler(
        parts,
        request_bytes,
        "application/x-flat-buffers",
        dummy_ctx(),
    )
    .await;
    assert!(result.is_ok());

    let response_parts = result.unwrap();
    // Response uses non-hyphenated form
    assert_eq!(response_parts.content_type, "application/x-flatbuffers");

    let response =
        TestResponse::from_flatbuffer(&response_parts.body).expect("Should deserialize response");
    assert!(response.success);
    assert_eq!(response.value, 5678 + 100);
}

// ============================================================================
// Worker tests
// ============================================================================

/// Registered workers are spawned into every server this binary starts, so
/// they take the `()` context those servers boot with and park rather than
/// returning — an exit would mark the process unhealthy and fail the probe
/// tests.
#[derive(Default)]
struct TestSimpleWorker;

impl Worker for TestSimpleWorker {
    type Context = ();
    const NAME: &'static str = "test_simple_worker";

    fn run(&self, _ctx: Arc<Self::Context>) -> flatbed::BoxFuture<Result<(), FlatbedWorkerError>> {
        Box::pin(async move {
            std::future::pending::<()>().await;
            Ok(())
        })
    }
}

flatbed::register_worker!(TestSimpleWorker, ());

/// Worker with custom name and description
#[derive(Default)]
struct TestCustomWorker;

impl Worker for TestCustomWorker {
    type Context = ();
    const NAME: &'static str = "custom-worker";
    const DESCRIPTION: Option<&'static str> = Some("A worker with custom attributes");

    fn run(&self, _ctx: Arc<Self::Context>) -> flatbed::BoxFuture<Result<(), FlatbedWorkerError>> {
        Box::pin(async move {
            std::future::pending::<()>().await;
            Ok(())
        })
    }
}

flatbed::register_worker!(TestCustomWorker, ());

#[test]
fn test_worker_registration() {
    let workers = get_workers();

    // Check that our test workers are registered
    let simple_worker = workers.iter().find(|w| w.name == "test_simple_worker");
    assert!(
        simple_worker.is_some(),
        "Simple worker should be registered"
    );
    assert!(simple_worker.unwrap().description.is_none());

    let custom_worker = workers.iter().find(|w| w.name == "custom-worker");
    assert!(
        custom_worker.is_some(),
        "Custom worker should be registered"
    );
    assert_eq!(
        custom_worker.unwrap().description,
        Some("A worker with custom attributes")
    );

    assert!(simple_worker.unwrap().restart.is_none());
    assert!(flatbed::get_worker_drains()
        .iter()
        .any(|d| d.name == "test_simple_worker"));
}

// ============================================================================
// Boot lifecycle tests
// ============================================================================

/// Stub telemetry service for integration tests
struct StubTelemetryService;

impl flatbed::TelemetryService for StubTelemetryService {
    fn new(_config: flatbed::TelemetryConfig) -> Arc<Self>
    where
        Self: Sized,
    {
        Arc::new(Self)
    }

    fn register_f64_counter(
        &self,
        _name: &str,
        _help: &str,
        _labels: Option<std::collections::HashMap<String, String>>,
    ) -> Result<Arc<dyn flatbed::telemetry::Counter<f64>>, flatbed::TelemetryError> {
        Ok(Arc::new(StubCounter))
    }

    fn register_u64_counter(
        &self,
        _name: &str,
        _help: &str,
        _labels: Option<std::collections::HashMap<String, String>>,
    ) -> Result<Arc<dyn flatbed::telemetry::Counter<u64>>, flatbed::TelemetryError> {
        Ok(Arc::new(StubCounter))
    }

    fn get_feed(&self) -> Result<String, flatbed::TelemetryError> {
        Ok(String::new())
    }

    fn service_name(&self) -> String {
        "stub".to_string()
    }

    fn ip_address(&self) -> String {
        "127.0.0.1".to_string()
    }
}

struct StubCounter;

impl flatbed::telemetry::Counter<f64> for StubCounter {
    fn inc(&self) {}
    fn inc_by(&self, _value: f64) {}
}

impl flatbed::telemetry::Counter<u64> for StubCounter {
    fn inc(&self) {}
    fn inc_by(&self, _value: u64) {}
}

/// Test that verifies the two-phase boot lifecycle:
/// - During boot: /healthz → 200, /readyz → 503, user routes → 503
/// - After boot:  /healthz → 200, /readyz → 200, user routes → 200
#[tokio::test]
async fn test_boot_lifecycle_probes() {
    use flatbed::{Flatbed, FlatbedConfig};
    use tokio::sync::oneshot;

    // Find a free port
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    drop(listener);

    let telemetry: Arc<dyn flatbed::TelemetryService> = Arc::new(StubTelemetryService);

    let config = FlatbedConfig::new("Test API")
        .host("127.0.0.1")
        .port(port)
        .with_telemetry(telemetry);

    // oneshot to control when boot completes
    let (boot_tx, boot_rx) = oneshot::channel::<()>();

    // Spawn the server
    let server_handle = tokio::spawn(async move {
        Flatbed::run(config, |_config| async move {
            // Wait until test signals us to complete boot
            let _ = boot_rx.await;
            Ok(()) // context type is ()
        })
        .await
    });

    let base = format!("http://127.0.0.1:{}", port);
    let client = reqwest::Client::new();

    // Wait for TCP port to accept connections
    for _ in 0..100 {
        if tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port))
            .await
            .is_ok()
        {
            break;
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }

    // --- Assert DURING boot ---

    // /healthz should return 200 (server is alive)
    let resp = client
        .get(format!("{}/healthz", base))
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status().as_u16(),
        200,
        "/healthz should be 200 during boot"
    );

    // /readyz should return 503 (not ready yet)
    let resp = client.get(format!("{}/readyz", base)).send().await.unwrap();
    assert_eq!(
        resp.status().as_u16(),
        503,
        "/readyz should be 503 during boot"
    );

    let resp = client
        .get(format!("{}/schema.bfbs", base))
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status().as_u16(),
        200,
        "/schema.bfbs should be 200 during boot"
    );
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/octet-stream"
    );
    let bfbs = resp.bytes().await.unwrap();
    assert!(!bfbs.is_empty(), "/schema.bfbs must return the reflection");

    // User route should return 503 (not ready yet)
    let resp = client
        .post(format!("{}/api/ping", base))
        .header("content-type", "application/json")
        .body(r#"{"message":"test","value":1}"#)
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status().as_u16(),
        503,
        "User routes should be 503 during boot"
    );

    // --- Signal boot to complete ---
    boot_tx.send(()).unwrap();

    // Wait for ready signal to propagate
    for _ in 0..100 {
        let resp = client.get(format!("{}/readyz", base)).send().await.unwrap();
        if resp.status().as_u16() == 200 {
            break;
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }

    // --- Assert AFTER boot ---

    // /healthz should still be 200
    let resp = client
        .get(format!("{}/healthz", base))
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status().as_u16(),
        200,
        "/healthz should be 200 after boot"
    );

    // /readyz should now be 200
    let resp = client.get(format!("{}/readyz", base)).send().await.unwrap();
    assert_eq!(
        resp.status().as_u16(),
        200,
        "/readyz should be 200 after boot"
    );

    // User route should now work
    let resp = client
        .post(format!("{}/api/ping", base))
        .header("content-type", "application/json")
        .body(r#"{"message":"lifecycle test","value":42}"#)
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.status().as_u16(),
        200,
        "User routes should be 200 after boot"
    );

    // Clean up: abort the server task (it would run forever otherwise)
    server_handle.abort();
}

/// A readiness gate drives the probes for the rest of the process's life,
/// after the one-shot boot latch has stopped moving:
/// - During boot: the latch is what readiness waits on, so a registered gate
///   does not rename the answer.
/// - After boot, gate closed: /readyz → 503 naming it, user routes → 503
///   `NOT_READY`.
/// - Gate open → 200; closed again → 503, without a second boot.
#[tokio::test]
async fn test_readiness_gate_probes() {
    use flatbed::{Flatbed, FlatbedConfig, Readiness};
    use tokio::sync::oneshot;

    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    drop(listener);

    let readiness = Readiness::new();
    let gate = readiness.gate("broker");

    let telemetry: Arc<dyn flatbed::TelemetryService> = Arc::new(StubTelemetryService);
    let config = FlatbedConfig::new("Test API")
        .host("127.0.0.1")
        .port(port)
        .readiness(readiness)
        .with_telemetry(telemetry);

    let (boot_tx, boot_rx) = oneshot::channel::<()>();
    let server_handle = tokio::spawn(async move {
        Flatbed::run(config, |_config| async move {
            let _ = boot_rx.await;
            Ok(())
        })
        .await
    });

    let base = format!("http://127.0.0.1:{}", port);
    let client = reqwest::Client::new();

    for _ in 0..100 {
        if tokio::net::TcpStream::connect(format!("127.0.0.1:{}", port))
            .await
            .is_ok()
        {
            break;
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }

    let readyz = |client: reqwest::Client, base: String| async move {
        let resp = client.get(format!("{}/readyz", base)).send().await.unwrap();
        (resp.status().as_u16(), resp.text().await.unwrap())
    };
    let ping = |client: reqwest::Client, base: String| async move {
        let resp = client
            .post(format!("{}/api/ping", base))
            .header("content-type", "application/json")
            .body(r#"{"message":"gate","value":1}"#)
            .send()
            .await
            .unwrap();
        (resp.status().as_u16(), resp.text().await.unwrap())
    };

    // A gate registered before boot must not make an unfinished boot look
    // like a lost dependency.
    let (status, body) = readyz(client.clone(), base.clone()).await;
    assert_eq!(status, 503, "/readyz is 503 during boot");
    assert_eq!(
        body, "Not Ready",
        "the boot latch, not a gate, holds it down"
    );

    let (status, body) = ping(client.clone(), base.clone()).await;
    assert_eq!(status, 503, "user routes are 503 during boot");
    assert!(
        body.contains("BOOTING"),
        "an unfinished boot reports BOOTING, got {body}"
    );

    boot_tx.send(()).unwrap();

    // Booted with the gate still closed: the gate is now the whole answer.
    let mut named = false;
    for _ in 0..100 {
        if readyz(client.clone(), base.clone()).await.1 == "Not Ready: broker" {
            named = true;
            break;
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }
    assert!(named, "/readyz should name the gate holding it down");

    let (status, body) = ping(client.clone(), base.clone()).await;
    assert_eq!(status, 503, "user routes are 503 behind a closed gate");
    assert!(
        body.contains("NOT_READY") && body.contains("broker"),
        "a closed gate reports NOT_READY and names itself, got {body}"
    );

    gate.set_ready(true);
    assert_eq!(
        readyz(client.clone(), base.clone()).await,
        (200, "Ready".to_string()),
        "an open gate on a booted server is ready"
    );
    assert_eq!(
        ping(client.clone(), base.clone()).await.0,
        200,
        "user routes serve once the gate opens"
    );

    // The gate is not one-shot: it closes again without a second boot.
    gate.set_ready(false);
    assert_eq!(
        readyz(client.clone(), base.clone()).await,
        (503, "Not Ready: broker".to_string()),
        "a gate that closes again takes readiness with it"
    );

    server_handle.abort();
}

/// HEAD requests to built-in endpoints (splash, healthz/readyz, openapi.json,
/// schema.bfbs) put the same `Content-Length` header on the wire as GET but
/// no body bytes, over both HTTP/1.1 and HTTP/2.
#[tokio::test]
async fn test_head_request_builtins_strip_body_keep_length() {
    use flatbed::{Flatbed, FlatbedConfig};

    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    drop(listener);

    let telemetry: Arc<dyn flatbed::TelemetryService> = Arc::new(StubTelemetryService);
    let config = FlatbedConfig::new("Test API")
        .host("127.0.0.1")
        .port(port)
        .splash("Test API Server")
        .with_telemetry(telemetry);

    let server = tokio::spawn(async move { Flatbed::run(config, |_| async { Ok(()) }).await });

    let base = format!("http://127.0.0.1:{}", port);
    let client = reqwest::Client::new();

    // Wait for the server to become ready.
    let mut ready = false;
    for _ in 0..100 {
        if let Ok(r) = client.get(format!("{}/readyz", base)).send().await {
            if r.status().as_u16() == 200 {
                ready = true;
                break;
            }
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }
    assert!(ready, "server did not become ready");

    for path in ["/", "/healthz", "/readyz", "/schema.bfbs", "/openapi.json"] {
        let url = format!("{}{}", base, path);

        // HTTP/1.1, via reqwest: same status and content-length as GET, no
        // client-visible body.
        let get = client.get(&url).send().await.unwrap();
        assert_eq!(get.status().as_u16(), 200, "GET {path} should be 200");
        let get_content_length = get
            .headers()
            .get("content-length")
            .expect("GET content-length present")
            .to_str()
            .unwrap()
            .to_string();

        let head = client.head(&url).send().await.unwrap();
        assert_eq!(head.status().as_u16(), 200, "HEAD {path} should be 200");
        assert_eq!(
            head.headers()
                .get("content-length")
                .expect("HEAD content-length present")
                .to_str()
                .unwrap(),
            get_content_length,
            "HEAD {path} content-length must equal GET's over HTTP/1.1"
        );

        // HTTP/2 cleartext: no protocol error, same content-length, zero
        // actual body bytes received.
        let (status, content_length, received) = common::h2c_head_request(port, path).await;
        assert_eq!(
            status,
            http::StatusCode::OK,
            "HEAD {path} should be 200 over h2c"
        );
        assert_eq!(
            content_length.as_deref(),
            Some(get_content_length.as_str()),
            "HEAD {path} content-length must equal GET's over h2c"
        );
        assert_eq!(
            received, 0,
            "HEAD {path} must not put a body on the wire over h2c"
        );
    }

    server.abort();
}

/// A `before_request` guard rejects a request with its own status/code
/// before the matched route handler runs, and lets a request through once it
/// satisfies the guard.
#[tokio::test]
#[allow(clippy::result_large_err)]
async fn test_before_request_guard_rejects_before_handler_runs() {
    use flatbed::{Flatbed, FlatbedConfig};

    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    drop(listener);

    let telemetry: Arc<dyn flatbed::TelemetryService> = Arc::new(StubTelemetryService);
    let config = FlatbedConfig::new("Test API")
        .host("127.0.0.1")
        .port(port)
        .with_telemetry(telemetry)
        .before_request(|req| match req.header("authorization") {
            Some("Bearer secret") => Ok(()),
            _ => Err(
                FlatbedRouteError::unauthorized("missing or invalid bearer token")
                    .code("UNAUTHORIZED"),
            ),
        });

    let server = tokio::spawn(async move { Flatbed::run(config, |_| async { Ok(()) }).await });

    let base = format!("http://127.0.0.1:{}", port);
    let client = reqwest::Client::new();

    let mut ready = false;
    for _ in 0..100 {
        if let Ok(r) = client.get(format!("{}/readyz", base)).send().await {
            if r.status().as_u16() == 200 {
                ready = true;
                break;
            }
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }
    assert!(ready, "server did not become ready");

    // No Authorization header: the guard rejects before the handler runs.
    let resp = client
        .post(format!("{}/api/ping", base))
        .header("content-type", "application/json")
        .body(r#"{"message":"hi","value":1}"#)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 401);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert_eq!(body["code"], "UNAUTHORIZED");
    assert_eq!(body["message"], "missing or invalid bearer token");
    assert!(body.get("value").is_none());

    // Same rejection over FlatBuffers: code/message travel in headers with an
    // empty body, matching the `#[route]` macro's own error-response shape.
    let resp = client
        .post(format!("{}/api/ping", base))
        .header("content-type", "application/x-flatbuffers")
        .body(Vec::<u8>::new())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 401);
    assert_eq!(resp.headers().get("x-error-code").unwrap(), "UNAUTHORIZED");
    assert_eq!(
        resp.headers().get("x-error-message").unwrap(),
        "missing or invalid bearer token"
    );
    assert!(resp.bytes().await.unwrap().is_empty());

    // Correct bearer token: the guard passes and the handler runs normally.
    let resp = client
        .post(format!("{}/api/ping", base))
        .header("content-type", "application/json")
        .header("authorization", "Bearer secret")
        .body(r#"{"message":"hi","value":1}"#)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 200);
    let body: TestResponse = resp.json().await.unwrap();
    assert_eq!(body.value, 1 + 100);

    server.abort();
}

#[test]
fn test_router_path_matching() {
    use flatbed::hyper::Router;

    let router = Router::new();

    // This test verifies the router can match paths correctly
    // Note: We don't have actual handlers registered for this test
    let methods = router.get_allowed_methods("/api/users");
    assert!(methods.is_empty()); // No routes added

    // Path matching with no routes returns None
    assert!(router.match_route("/api/ping", "GET").is_none());
}

/// `accept` picks the response codec when it names one; the body is still
/// decoded by `content-type`, and a request that names neither is answered
/// the way it always was.
#[tokio::test]
async fn accept_header_selects_the_response_codec() {
    use flatbed::{Flatbed, FlatbedConfig};

    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    drop(listener);

    let telemetry: Arc<dyn flatbed::TelemetryService> = Arc::new(StubTelemetryService);
    let config = FlatbedConfig::new("Test API")
        .host("127.0.0.1")
        .port(port)
        .with_telemetry(telemetry);
    let server = tokio::spawn(async move { Flatbed::run(config, |_| async { Ok(()) }).await });

    let base = format!("http://127.0.0.1:{port}");
    let client = reqwest::Client::new();
    for _ in 0..100 {
        if let Ok(resp) = client.get(format!("{base}/readyz")).send().await {
            if resp.status().as_u16() == 200 {
                break;
            }
        }
        tokio::time::sleep(tokio::time::Duration::from_millis(20)).await;
    }

    // A bodiless GET with `accept: application/json` is answered in JSON.
    // `TestRequest.value` has no default, so the empty body is a 400 here
    // whatever the codec; what `accept` decides is the shape of the answer.
    let resp = client
        .get(format!("{base}/api/resource"))
        .header("accept", "application/json")
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 400);
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/json"
    );
    let json: flatbed::serde_json::Value = resp.json().await.unwrap();
    assert_eq!(json["code"], "BAD_REQUEST");

    // The same GET with no headers is answered as before: no `accept` and no
    // `content-type` means the JSON error body.
    let resp = client
        .get(format!("{base}/api/resource"))
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 400);
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/json"
    );

    // A handler's own error under `accept: application/x-flatbuffers` takes
    // the FlatBuffer shape: code and message in headers, no JSON body. (A body
    // that fails to decode is the service's answer, JSON whatever the codec.)
    let resp = client
        .post(format!("{base}/api/error"))
        .header("content-type", "application/json")
        .header("accept", "application/x-flatbuffers")
        .body(r#"{"message":"e","value":1}"#)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 400);
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/x-flatbuffers"
    );
    assert_eq!(resp.headers().get("x-error-code").unwrap(), "TEST_ERROR");
    assert!(resp.bytes().await.unwrap().is_empty());

    // A FlatBuffer body in, `accept: application/json` out: decoded by
    // content-type, encoded by accept.
    let request = TestRequest {
        message: Some("fb".to_string()),
        value: 1,
    };
    let resp = client
        .post(format!("{base}/api/ping"))
        .header("content-type", "application/x-flatbuffers")
        .header("accept", "application/json")
        .body(request.to_flatbuffer())
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 200);
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/json"
    );
    let json: flatbed::serde_json::Value = resp.json().await.unwrap();
    assert_eq!(json["value"], 101);
    assert_eq!(json["message"], "Test pong: fb");

    // JSON in with `accept: application/x-flatbuffers` answers FlatBuffers.
    let resp = client
        .post(format!("{base}/api/ping"))
        .header("content-type", "application/json")
        .header("accept", "application/x-flatbuffers")
        .body(r#"{"message":"j","value":2}"#)
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 200);
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/x-flatbuffers"
    );
    let decoded = TestResponse::from_flatbuffer(&resp.bytes().await.unwrap()).unwrap();
    assert_eq!(decoded.value, 102);

    // An `accept` naming neither falls through to the content-type rule.
    let resp = client
        .post(format!("{base}/api/ping"))
        .header("content-type", "application/json")
        .header("accept", "text/html")
        .body(r#"{"message":"h","value":3}"#)
        .send()
        .await
        .unwrap();
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/json"
    );

    // A handler error under `accept: application/json` is a JSON error body.
    let resp = client
        .post(format!("{base}/api/error"))
        .header("content-type", "application/x-flatbuffers")
        .header("accept", "application/json")
        .body(
            TestRequest {
                message: Some("e".to_string()),
                value: 1,
            }
            .to_flatbuffer(),
        )
        .send()
        .await
        .unwrap();
    assert_eq!(resp.status().as_u16(), 400);
    assert_eq!(
        resp.headers().get("content-type").unwrap(),
        "application/json"
    );
    let json: flatbed::serde_json::Value = resp.json().await.unwrap();
    assert_eq!(json["code"], "TEST_ERROR");

    server.abort();
}