caelix-actix 0.0.25

Actix Web runtime adapter for Caelix.
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
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
use std::{
    collections::BTreeMap,
    ffi::{OsStr, OsString},
    sync::Arc,
    time::Instant,
};

use actix_web::{
    App, HttpRequest, HttpResponse, HttpServer,
    body::{BodySize, MessageBody},
    dev::{Service, ServiceResponse},
    error::{JsonPayloadError, PathError, QueryPayloadError},
    http::header,
    web,
};
#[cfg(feature = "uploads")]
use caelix_core::UploadConfig;
#[cfg(feature = "openapi")]
use caelix_core::openapi::{OpenApiConfig, build_openapi};
use caelix_core::{
    BadRequestException, BoxFuture, Container, HttpException, HttpResponse as CaelixHttpResponse,
    IntoCaelixResponse, Module, NotFoundException, PayloadTooLargeException, ResponseBody, Result,
    build_container, http_request_logging_enabled, log_application_started, log_http_request,
    log_http_request_info, log_listening, log_module_routes, register_module_controllers,
    shutdown_module,
};
use futures_util::StreamExt;

/// Public Caelix constant `DEFAULT_BODY_LIMIT_BYTES`.
pub const DEFAULT_BODY_LIMIT_BYTES: usize = 1024 * 1024;

/// Application-scoped multipart storage and limit configuration.
#[derive(Clone)]
pub(crate) struct UploadRuntimeConfig {
    #[cfg(feature = "uploads")]
    pub(crate) config: UploadConfig,
    pub(crate) body_limit: usize,
}

#[cfg(feature = "openapi")]
#[derive(Clone)]
pub(crate) struct OpenApiServices {
    /// The `config` value.
    pub config: OpenApiConfig,
    /// The `document` value.
    pub document: String,
}

#[cfg(not(feature = "openapi"))]
#[derive(Clone)]
pub(crate) struct OpenApiServices;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum AccessLogFormat {
    Compact,
    Info,
}

/// Configures Actix runtime logging for an [`Application`].
///
/// `Logging::default()` enables Caelix's asynchronous HTTP access log.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
/// Public Caelix type `Logging`.
pub struct Logging {
    access_log: bool,
    access_log_format: AccessLogFormat,
}

impl Default for Logging {
    fn default() -> Self {
        Self {
            access_log: true,
            access_log_format: AccessLogFormat::Compact,
        }
    }
}

impl Logging {
    /// Enables Actix-compatible detailed HTTP access logs.
    ///
    /// The output includes client address, request line and protocol, status,
    /// response size, referrer, user agent, and duration.
    pub fn info() -> Self {
        Self {
            access_log: true,
            access_log_format: AccessLogFormat::Info,
        }
    }

    /// Enables or disables HTTP access logging.
    pub fn access_log(mut self, enabled: bool) -> Self {
        self.access_log = enabled;
        self
    }

    /// Runs the `access_log_enabled` public API operation.
    pub fn access_log_enabled(&self) -> bool {
        self.access_log
    }

    fn access_log_format(&self) -> AccessLogFormat {
        self.access_log_format
    }
}

/// Runs the `to_actix_response` public API operation.
pub fn to_actix_response(response: CaelixHttpResponse) -> HttpResponse {
    // Caelix core uses http 1.x while Actix 4 still builds responses with http 0.2.
    let status = actix_web::http::StatusCode::from_u16(response.status.as_u16())
        .unwrap_or(actix_web::http::StatusCode::INTERNAL_SERVER_ERROR);

    let mut builder = HttpResponse::build(status);
    builder.content_type(response.content_type);
    for (name, value) in response.headers {
        builder.insert_header((name, value));
    }
    for cookie in response.cookies {
        let mut runtime_cookie =
            actix_web::cookie::Cookie::new(cookie.name().to_string(), cookie.value().to_string());
        runtime_cookie.set_http_only(cookie.is_http_only());
        runtime_cookie.set_secure(cookie.is_secure());
        runtime_cookie.set_same_site(match cookie.same_site_value() {
            caelix_core::SameSite::Strict => actix_web::cookie::SameSite::Strict,
            caelix_core::SameSite::Lax => actix_web::cookie::SameSite::Lax,
            caelix_core::SameSite::None => actix_web::cookie::SameSite::None,
        });
        if let Some(path) = cookie.path_value() {
            runtime_cookie.set_path(path.to_string());
        }
        if let Some(domain) = cookie.domain_value() {
            runtime_cookie.set_domain(domain.to_string());
        }
        if let Some(max_age) = cookie.max_age_value() {
            runtime_cookie.set_max_age(
                actix_web::cookie::time::Duration::try_from(max_age)
                    .unwrap_or(actix_web::cookie::time::Duration::MAX),
            );
        }
        if let Some(expires) = cookie.expires_value() {
            runtime_cookie.set_expires(actix_web::cookie::time::OffsetDateTime::from(expires));
        }
        builder.append_header((
            actix_web::http::header::SET_COOKIE,
            runtime_cookie.encoded().to_string(),
        ));
    }

    match response.body {
        ResponseBody::Buffered(bytes) => builder.body(bytes),
        ResponseBody::Streaming(stream) => {
            // Mid-stream errors cannot rewrite an already-sent status line.
            let stream = stream.map(|chunk| {
                chunk.map_err(|err| {
                    caelix_core::log_http_exception(&err);
                    actix_web::error::ErrorInternalServerError("Internal Server Error")
                })
            });
            builder.streaming(stream)
        }
    }
}

/// Public Caelix type `Application`.
pub struct Application {
    container: Arc<Container>,
    configure_fn: fn(&mut web::ServiceConfig),
    gateway_configure_fn: fn(&mut web::ServiceConfig, Arc<Container>, usize),
    shutdown_fn: for<'a> fn(&'a Container) -> BoxFuture<'a, caelix_core::Result<()>>,
    body_limit: usize,
    #[cfg(feature = "uploads")]
    upload_config: UploadConfig,
    websocket_max_message_size: usize,
    workers: usize,
    logging: Option<Logging>,
    openapi: Option<OpenApiServices>,
    #[cfg(feature = "openapi")]
    openapi_build_fn:
        fn(&OpenApiConfig) -> caelix_core::Result<caelix_core::openapi::utoipa::openapi::OpenApi>,
}

fn json_config(body_limit: usize) -> web::JsonConfig {
    web::JsonConfig::default()
        .limit(body_limit)
        .content_type_required(false)
        .error_handler(move |err, _req| {
            let exception = json_exception(&err, body_limit);
            let response = to_actix_response(exception.into_response());

            actix_web::error::InternalError::from_response(err, response).into()
        })
}

fn json_exception(err: &JsonPayloadError, body_limit: usize) -> HttpException {
    if matches!(
        err,
        JsonPayloadError::Overflow { .. } | JsonPayloadError::OverflowKnownLength { .. }
    ) {
        return PayloadTooLargeException::new(format!(
            "request body exceeds the configured limit of {body_limit} bytes"
        ));
    }

    if let JsonPayloadError::Deserialize(source) = err {
        if let Some(exception) = missing_field_exception(&source.to_string()) {
            return exception;
        }
    }

    BadRequestException::new("invalid JSON request body")
}

fn path_config() -> web::PathConfig {
    web::PathConfig::default().error_handler(|err: PathError, _req| {
        let exception = missing_field_exception(&err.to_string())
            .unwrap_or_else(|| BadRequestException::new(err.to_string()));
        let response = to_actix_response(exception.into_response());

        actix_web::error::InternalError::from_response(err, response).into()
    })
}

fn query_config() -> web::QueryConfig {
    web::QueryConfig::default().error_handler(|err: QueryPayloadError, _req| {
        let exception = missing_field_exception(&err.to_string())
            .unwrap_or_else(|| BadRequestException::new(err.to_string()));
        let response = to_actix_response(exception.into_response());

        actix_web::error::InternalError::from_response(err, response).into()
    })
}

fn missing_field_exception(message: &str) -> Option<HttpException> {
    let field = missing_field_name(message)?;
    let mut errors = BTreeMap::new();
    errors.insert(field, vec!["is required".to_string()]);

    Some(BadRequestException::new("Validation failed").with_errors(errors))
}

fn missing_field_name(message: &str) -> Option<String> {
    let start = message.find("missing field `")? + "missing field `".len();
    let rest = &message[start..];
    let end = rest.find('`')?;
    let field = &rest[..end];

    if field.is_empty() {
        None
    } else {
        Some(field.to_string())
    }
}

async fn not_found(req: HttpRequest) -> HttpResponse {
    to_actix_response(
        NotFoundException::new(format!("Cannot {} {}", req.method(), req.path())).into_response(),
    )
}

fn log_access_request<B: MessageBody>(
    format: AccessLogFormat,
    response: &ServiceResponse<B>,
    elapsed: std::time::Duration,
) {
    let request = response.request();

    match format {
        AccessLogFormat::Compact => log_http_request(
            request.method().as_str(),
            request.path(),
            response.status().as_u16(),
            elapsed,
        ),
        AccessLogFormat::Info => {
            let path_and_query = if request.query_string().is_empty() {
                request.path().to_string()
            } else {
                format!("{}?{}", request.path(), request.query_string())
            };
            let response_size = match response.response().body().size() {
                BodySize::None => Some(0),
                BodySize::Sized(size) => Some(size),
                BodySize::Stream => None,
            };

            log_http_request_info(
                request.connection_info().peer_addr().unwrap_or("-"),
                request.method().as_str(),
                &path_and_query,
                &format!("{:?}", request.version()),
                response.status().as_u16(),
                response_size,
                request_header(request, &header::REFERER).as_str(),
                request_header(request, &header::USER_AGENT).as_str(),
                elapsed,
            );
        }
    }
}

fn request_header(request: &HttpRequest, name: &header::HeaderName) -> String {
    request
        .headers()
        .get(name)
        .map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned())
        .unwrap_or_else(|| "-".to_string())
}

pub(crate) fn configure_caelix_services(
    cfg: &mut web::ServiceConfig,
    body_limit: usize,
    #[cfg(feature = "uploads")] upload_config: UploadConfig,
    configure_fn: fn(&mut web::ServiceConfig),
    openapi: Option<&OpenApiServices>,
) {
    cfg.app_data(json_config(body_limit));
    cfg.app_data(web::Data::new(UploadRuntimeConfig {
        #[cfg(feature = "uploads")]
        config: upload_config,
        body_limit,
    }));
    cfg.app_data(path_config());
    cfg.app_data(query_config());
    configure_fn(cfg);
    #[cfg(feature = "openapi")]
    if let Some(openapi) = openapi {
        let ui_base = openapi.config.ui_path.trim_end_matches('/');
        let ui_redirect = format!("{ui_base}/");
        let document = openapi.document.clone();
        cfg.route(
            &openapi.config.json_path,
            web::get().to(move || {
                let document = document.clone();
                async move {
                    HttpResponse::Ok()
                        .content_type("application/json")
                        .body(document)
                }
            }),
        );
        let html = swagger_ui_html(&openapi.config.json_path);
        cfg.route(
            &format!("{ui_base}/"),
            web::get().to(move || {
                let html = html.clone();
                async move {
                    HttpResponse::Ok()
                        .content_type("text/html; charset=utf-8")
                        .body(html)
                }
            }),
        );
        cfg.route(
            ui_base,
            web::get().to(move || {
                let ui_redirect = ui_redirect.clone();
                async move {
                    HttpResponse::TemporaryRedirect()
                        .insert_header((header::LOCATION, ui_redirect))
                        .finish()
                }
            }),
        );
    }
    #[cfg(not(feature = "openapi"))]
    let _ = openapi;
    cfg.default_service(web::route().to(not_found));
}

#[cfg(feature = "openapi")]
fn swagger_ui_html(json_path: &str) -> String {
    let json_path = serde_json::to_string(json_path).expect("OpenAPI path must serialize");
    format!(
        r#"<!doctype html><html><head><meta charset="utf-8"><title>Swagger UI</title><link rel="stylesheet" href="https://unpkg.com/swagger-ui-dist@5/swagger-ui.css"></head><body><div id="swagger-ui"></div><script src="https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js"></script><script>SwaggerUIBundle({{url:{json_path},dom_id:'#swagger-ui'}});</script></body></html>"#
    )
}

impl Application {
    /// Runs the `new` public API operation.
    pub async fn new<M: Module + 'static>() -> Result<Self> {
        let start = Instant::now();
        let container = build_container::<M>().await?;
        log_module_routes::<M>();
        log_application_started(start.elapsed());

        Ok(Self {
            container: Arc::new(container),
            configure_fn: |cfg| register_module_controllers::<M>(cfg),
            gateway_configure_fn: |cfg, container, max| {
                crate::websocket::configure_gateway_routes::<M>(cfg, container, max)
            },
            shutdown_fn: |container| Box::pin(async move { shutdown_module::<M>(container).await }),
            body_limit: DEFAULT_BODY_LIMIT_BYTES,
            #[cfg(feature = "uploads")]
            upload_config: UploadConfig::default(),
            websocket_max_message_size: crate::websocket::DEFAULT_WEBSOCKET_MAX_MESSAGE_SIZE,
            workers: num_cpus::get(),
            logging: None,
            openapi: None,
            #[cfg(feature = "openapi")]
            openapi_build_fn: |config| build_openapi::<M>(config),
        })
    }

    /// Runs the `body_limit` public API operation.
    pub fn body_limit(mut self, bytes: usize) -> Self {
        self.body_limit = bytes;
        self
    }

    #[cfg(feature = "uploads")]
    /// Changes the directory used to stage multipart uploads before they are persisted.
    pub fn upload_temp_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
        self.upload_config = self.upload_config.upload_temp_dir(path);
        self
    }

    /// Runs the `websocket_max_message_size` public API operation.
    pub fn websocket_max_message_size(mut self, bytes: usize) -> Self {
        self.websocket_max_message_size = bytes.max(1);
        self
    }

    /// Runs the `workers` public API operation.
    pub fn workers(mut self, workers: usize) -> Self {
        self.workers = workers.max(1);
        self
    }

    /// Configures runtime logging for this application.
    ///
    /// An explicit configuration takes precedence over `CAELIX_HTTP_LOG` and
    /// `CAELIX_ACCESS_LOG`. When omitted, those environment variables remain
    /// supported for backwards compatibility.
    pub fn logging(mut self, logging: Logging) -> Self {
        self.logging = Some(logging);
        self
    }

    /// Generates and serves OpenAPI JSON plus Swagger UI for this application.
    #[cfg(feature = "openapi")]
    /// Runs the `with_openapi` public API operation.
    pub fn with_openapi(mut self, config: OpenApiConfig) -> Result<Self> {
        let document = (self.openapi_build_fn)(&config)?;
        self.openapi = Some(OpenApiServices {
            config,
            document: document.to_json().expect("OpenAPI document must serialize"),
        });
        Ok(self)
    }

    #[cfg(test)]
    fn configure_services(&self, cfg: &mut web::ServiceConfig) {
        configure_caelix_services(
            cfg,
            self.body_limit,
            #[cfg(feature = "uploads")]
            self.upload_config.clone(),
            self.configure_fn,
            self.openapi.as_ref(),
        );
    }

    async fn shutdown(&self) -> caelix_core::Result<()> {
        (self.shutdown_fn)(&self.container).await
    }

    fn prepare_doctor_runtime(&self) {
        let container = self.container.clone();
        let configure_fn = self.configure_fn;
        let body_limit = self.body_limit;
        #[cfg(feature = "uploads")]
        let upload_config = self.upload_config.clone();
        let websocket_max_message_size = self.websocket_max_message_size;
        let gateway_configure_fn = self.gateway_configure_fn;
        let openapi = self.openapi.clone();

        let _app = App::new()
            .app_data(web::Data::from(container.clone()))
            .configure({
                move |cfg| {
                    configure_caelix_services(
                        cfg,
                        body_limit,
                        #[cfg(feature = "uploads")]
                        upload_config.clone(),
                        configure_fn,
                        openapi.as_ref(),
                    )
                }
            })
            .configure(move |cfg| {
                gateway_configure_fn(cfg, container.clone(), websocket_max_message_size)
            });
    }

    /// Runs the `listen` public API operation.
    pub async fn listen(self, addr: &str) -> std::io::Result<()> {
        self.listen_with_doctor_mode(addr, has_doctor_argument(std::env::args_os()))
            .await
    }

    async fn listen_with_doctor_mode(self, addr: &str, doctor_mode: bool) -> std::io::Result<()> {
        if doctor_mode {
            self.prepare_doctor_runtime();
            return self.shutdown().await.map_err(to_io_error);
        }

        let container = self.container.clone();
        let configure_fn = self.configure_fn;
        let body_limit = self.body_limit;
        #[cfg(feature = "uploads")]
        let upload_config = self.upload_config.clone();
        let websocket_max_message_size = self.websocket_max_message_size;
        let gateway_configure_fn = self.gateway_configure_fn;
        let workers = self.workers;
        let addr = addr.to_string();
        let logging = self.logging.unwrap_or(Logging {
            access_log: http_request_logging_enabled(),
            access_log_format: AccessLogFormat::Compact,
        });
        let openapi = self.openapi.clone();

        log_listening(&addr);

        let result = if logging.access_log_enabled() {
            let logging_container = container.clone();
            let openapi_with_logging = openapi.clone();
            let access_log_format = logging.access_log_format();
            let server = match HttpServer::new(move || {
                App::new()
                    .app_data(web::Data::from(logging_container.clone()))
                    .wrap_fn(move |req, service| {
                        let request_log_start = Instant::now();
                        let future = service.call(req);

                        async move {
                            let response = future.await?;
                            log_access_request(
                                access_log_format,
                                &response,
                                request_log_start.elapsed(),
                            );
                            Ok(response)
                        }
                    })
                    .configure({
                        let openapi = openapi_with_logging.clone();
                        #[cfg(feature = "uploads")]
                        let upload_config = upload_config.clone();
                        move |cfg| {
                            configure_caelix_services(
                                cfg,
                                body_limit,
                                #[cfg(feature = "uploads")]
                                upload_config.clone(),
                                configure_fn,
                                openapi.as_ref(),
                            )
                        }
                    })
                    .configure({
                        let container = logging_container.clone();
                        move |cfg| {
                            gateway_configure_fn(cfg, container.clone(), websocket_max_message_size)
                        }
                    })
            })
            .workers(workers)
            .bind(addr.as_str())
            {
                Ok(server) => server.run(),
                Err(err) => {
                    let _ = self.shutdown().await;
                    return Err(err);
                }
            };

            server.await
        } else {
            let server = match HttpServer::new(move || {
                App::new()
                    .app_data(web::Data::from(container.clone()))
                    .configure({
                        let openapi = openapi.clone();
                        #[cfg(feature = "uploads")]
                        let upload_config = upload_config.clone();
                        move |cfg| {
                            configure_caelix_services(
                                cfg,
                                body_limit,
                                #[cfg(feature = "uploads")]
                                upload_config.clone(),
                                configure_fn,
                                openapi.as_ref(),
                            )
                        }
                    })
                    .configure({
                        let container = container.clone();
                        move |cfg| {
                            gateway_configure_fn(cfg, container.clone(), websocket_max_message_size)
                        }
                    })
            })
            .workers(workers)
            .bind(addr.as_str())
            {
                Ok(server) => server.run(),
                Err(err) => {
                    let _ = self.shutdown().await;
                    return Err(err);
                }
            };

            server.await
        };

        self.shutdown().await.map_err(to_io_error)?;
        result
    }
}

fn has_doctor_argument<I>(args: I) -> bool
where
    I: IntoIterator<Item = OsString>,
{
    args.into_iter().any(|arg| arg == OsStr::new("--doctor"))
}

fn to_io_error(err: caelix_core::HttpException) -> std::io::Error {
    std::io::Error::other(err.message)
}

#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{http::StatusCode, test as actix_test};
    use caelix_core::{Controller, Injectable, ModuleMetadata};
    use serde::Deserialize;
    use serde_json::{Value, json};
    use std::{
        any::Any,
        sync::atomic::{AtomicUsize, Ordering},
    };

    #[test]
    fn response_adapter_appends_every_cookie_header() {
        let response = to_actix_response(
            CaelixHttpResponse::text(caelix_core::StatusCode::OK, "ok")
                .with_cookie(caelix_core::Cookie::new("session", "a b"))
                .with_cookie(
                    caelix_core::Cookie::removal("preference")
                        .path("/settings")
                        .domain("example.com"),
                ),
        );
        let values = response
            .headers()
            .get_all(actix_web::http::header::SET_COOKIE)
            .into_iter()
            .map(|value| value.to_str().unwrap().to_string())
            .collect::<Vec<_>>();
        assert_eq!(values.len(), 2);
        assert!(values[0].contains("session=a%20b"));
        assert!(values[0].contains("HttpOnly"));
        assert!(values[0].contains("Secure"));
        assert!(values[0].contains("SameSite=Lax"));
        assert!(values[1].contains("Max-Age=0"));
        assert!(values[1].contains("Domain=example.com"));
        assert!(values[1].contains("Path=/settings"));
    }
    use uuid::Uuid;

    static SHUTDOWN_COUNT: AtomicUsize = AtomicUsize::new(0);
    static DOCTOR_CONSTRUCTION_COUNT: AtomicUsize = AtomicUsize::new(0);
    static DOCTOR_INIT_COUNT: AtomicUsize = AtomicUsize::new(0);
    static DOCTOR_STARTUP_COUNT: AtomicUsize = AtomicUsize::new(0);
    static DOCTOR_SHUTDOWN_COUNT: AtomicUsize = AtomicUsize::new(0);
    static DOCTOR_ROUTE_CONFIG_COUNT: AtomicUsize = AtomicUsize::new(0);

    struct HealthService {
        status: &'static str,
    }

    impl Injectable for HealthService {
        fn dependencies() -> Vec<caelix_core::ProviderDependency> {
            caelix_core::provider_dependencies![]
        }

        fn create(_container: &Container) -> caelix_core::BoxFuture<'_, caelix_core::Result<Self>> {
            Box::pin(async move { Ok(Self { status: "ok" }) })
        }
    }

    struct TestModule;

    impl Module for TestModule {
        fn register() -> ModuleMetadata {
            ModuleMetadata::new().provider::<HealthService>()
        }
    }

    struct JsonController;

    impl Injectable for JsonController {
        fn dependencies() -> Vec<caelix_core::ProviderDependency> {
            caelix_core::provider_dependencies![]
        }

        fn create(_container: &Container) -> caelix_core::BoxFuture<'_, caelix_core::Result<Self>> {
            Box::pin(async move {
                DOCTOR_CONSTRUCTION_COUNT.fetch_add(1, Ordering::SeqCst);
                Ok(Self)
            })
        }

        fn on_module_init(&self) -> caelix_core::BoxFuture<'_, caelix_core::Result<()>> {
            Box::pin(async move {
                DOCTOR_INIT_COUNT.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        }
    }

    impl JsonController {
        async fn accept_json(_payload: web::Json<Value>) -> HttpResponse {
            HttpResponse::Ok().finish()
        }
    }

    impl Controller for JsonController {
        fn base_path() -> &'static str {
            "/json"
        }

        fn register_routes(cfg_any: &mut dyn Any) {
            let cfg = cfg_any
                .downcast_mut::<web::ServiceConfig>()
                .expect("expected actix ServiceConfig");

            cfg.route("/json", web::post().to(Self::accept_json));
        }
    }

    struct JsonModule;

    impl Module for JsonModule {
        fn register() -> ModuleMetadata {
            ModuleMetadata::new().controller::<JsonController>()
        }
    }

    #[derive(Deserialize)]
    struct SearchQuery {
        limit: usize,
    }

    #[derive(Deserialize)]
    struct RequiredBody {
        name: String,
    }

    #[derive(Deserialize)]
    struct RequiredQuery {
        q: String,
    }

    #[derive(Deserialize)]
    struct RequiredPath {
        org_id: Uuid,
        user_id: Uuid,
    }

    async fn accept_uuid(_id: web::Path<Uuid>) -> HttpResponse {
        HttpResponse::Ok().finish()
    }

    async fn accept_required_body(body: web::Json<RequiredBody>) -> HttpResponse {
        let body = body.into_inner();
        let _ = body.name;

        HttpResponse::Ok().finish()
    }

    async fn accept_query(query: web::Query<SearchQuery>) -> HttpResponse {
        let query = query.into_inner();
        let _ = query.limit;

        HttpResponse::Ok().finish()
    }

    async fn accept_required_query(query: web::Query<RequiredQuery>) -> HttpResponse {
        let query = query.into_inner();
        let _ = query.q;

        HttpResponse::Ok().finish()
    }

    async fn accept_required_path(path: web::Path<RequiredPath>) -> HttpResponse {
        let path = path.into_inner();
        let _ = (path.org_id, path.user_id);

        HttpResponse::Ok().finish()
    }

    struct ShutdownService;

    impl Injectable for ShutdownService {
        fn dependencies() -> Vec<caelix_core::ProviderDependency> {
            caelix_core::provider_dependencies![]
        }

        fn create(_container: &Container) -> caelix_core::BoxFuture<'_, caelix_core::Result<Self>> {
            Box::pin(async move { Ok(Self) })
        }

        fn on_shutdown(&self) -> caelix_core::BoxFuture<'_, caelix_core::Result<()>> {
            Box::pin(async move {
                SHUTDOWN_COUNT.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        }
    }

    struct ShutdownModule;

    impl Module for ShutdownModule {
        fn register() -> ModuleMetadata {
            ModuleMetadata::new().provider::<ShutdownService>()
        }
    }

    struct DoctorService;

    impl Injectable for DoctorService {
        fn dependencies() -> Vec<caelix_core::ProviderDependency> {
            caelix_core::provider_dependencies![]
        }

        fn create(_container: &Container) -> caelix_core::BoxFuture<'_, caelix_core::Result<Self>> {
            Box::pin(async move { Ok(Self) })
        }

        fn on_bootstrap(&self) -> caelix_core::BoxFuture<'_, caelix_core::Result<()>> {
            Box::pin(async move {
                DOCTOR_STARTUP_COUNT.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        }

        fn on_shutdown(&self) -> caelix_core::BoxFuture<'_, caelix_core::Result<()>> {
            Box::pin(async move {
                DOCTOR_SHUTDOWN_COUNT.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
        }
    }

    struct DoctorController;

    impl Injectable for DoctorController {
        fn dependencies() -> Vec<caelix_core::ProviderDependency> {
            caelix_core::provider_dependencies![]
        }

        fn create(_container: &Container) -> caelix_core::BoxFuture<'_, caelix_core::Result<Self>> {
            Box::pin(async move { Ok(Self) })
        }
    }

    impl Controller for DoctorController {
        fn base_path() -> &'static str {
            "/doctor"
        }

        fn register_routes(cfg_any: &mut dyn Any) {
            DOCTOR_ROUTE_CONFIG_COUNT.fetch_add(1, Ordering::SeqCst);
            let cfg = cfg_any
                .downcast_mut::<web::ServiceConfig>()
                .expect("expected actix ServiceConfig");
            cfg.route(
                "/doctor",
                web::get().to(|| async { HttpResponse::Ok().finish() }),
            );
        }
    }

    struct DoctorModule;

    impl Module for DoctorModule {
        fn register() -> ModuleMetadata {
            ModuleMetadata::new()
                .provider::<DoctorService>()
                .controller::<DoctorController>()
        }
    }

    struct FailingShutdownService;

    impl Injectable for FailingShutdownService {
        fn dependencies() -> Vec<caelix_core::ProviderDependency> {
            caelix_core::provider_dependencies![]
        }

        fn create(_container: &Container) -> caelix_core::BoxFuture<'_, caelix_core::Result<Self>> {
            Box::pin(async move { Ok(Self) })
        }

        fn on_shutdown(&self) -> caelix_core::BoxFuture<'_, caelix_core::Result<()>> {
            Box::pin(async move {
                Err(caelix_core::HttpException::new(
                    caelix_core::StatusCode::INTERNAL_SERVER_ERROR,
                    "Internal Server Error",
                    "shutdown failed",
                ))
            })
        }
    }

    struct FailingShutdownModule;

    impl Module for FailingShutdownModule {
        fn register() -> ModuleMetadata {
            ModuleMetadata::new().provider::<FailingShutdownService>()
        }
    }

    #[actix_web::test]
    async fn new_builds_container_from_module_metadata() {
        let app = Application::new::<TestModule>().await.unwrap();

        let service = app.container.resolve::<HealthService>().unwrap();

        assert_eq!(service.status, "ok");
    }

    #[actix_web::test]
    async fn application_accepts_explicit_logging_configuration() {
        let app = Application::new::<TestModule>()
            .await
            .unwrap()
            .logging(Logging::default().access_log(false));

        assert_eq!(app.logging, Some(Logging::default().access_log(false)));
        assert!(!Logging::default().access_log(false).access_log_enabled());
        assert!(Logging::default().access_log_enabled());
        assert_eq!(Logging::info().access_log_format(), AccessLogFormat::Info);
    }

    #[actix_web::test]
    async fn json_body_limit_rejects_large_payloads_with_json_error() {
        async fn accept_json(_payload: web::Json<Value>) -> HttpResponse {
            HttpResponse::Ok().finish()
        }

        let app = actix_test::init_service(
            App::new()
                .app_data(json_config(8))
                .route("/json", web::post().to(accept_json)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::post()
                .uri("/json")
                .insert_header(("content-type", "application/json"))
                .set_payload(r#"{"too":"large"}"#)
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(
            body,
            json!({
                "status": 413,
                "error": "Payload Too Large",
                "message": "request body exceeds the configured limit of 8 bytes"
            })
        );
    }

    #[actix_web::test]
    async fn json_config_accepts_json_without_content_type_header() {
        async fn accept_json(_payload: web::Json<Value>) -> HttpResponse {
            HttpResponse::Ok().finish()
        }

        let app = actix_test::init_service(
            App::new()
                .app_data(json_config(DEFAULT_BODY_LIMIT_BYTES))
                .route("/json", web::post().to(accept_json)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::post()
                .uri("/json")
                .set_payload("{}")
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::OK);
    }

    #[actix_web::test]
    async fn json_missing_field_errors_are_validation_shaped() {
        let app = actix_test::init_service(
            App::new()
                .app_data(json_config(DEFAULT_BODY_LIMIT_BYTES))
                .route("/json", web::patch().to(accept_required_body)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::patch()
                .uri("/json")
                .insert_header(("content-type", "application/json"))
                .set_payload("{}")
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(
            body,
            json!({
                "status": 400,
                "error": "Bad Request",
                "message": "Validation failed",
                "errors": {
                    "name": ["is required"]
                }
            })
        );
    }

    #[actix_web::test]
    async fn application_enforces_configured_body_limit() {
        let application = Application::new::<JsonModule>()
            .await
            .unwrap()
            .body_limit(8);
        let app = actix_test::init_service(
            App::new()
                .app_data(web::Data::from(application.container.clone()))
                .configure(|cfg| application.configure_services(cfg)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::post()
                .uri("/json")
                .insert_header(("content-type", "application/json"))
                .set_payload(r#"{"too":"large"}"#)
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::PAYLOAD_TOO_LARGE);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(
            body,
            json!({
                "status": 413,
                "error": "Payload Too Large",
                "message": "request body exceeds the configured limit of 8 bytes"
            })
        );
    }

    #[actix_web::test]
    async fn path_extractor_errors_are_caelix_json_errors() {
        let app = actix_test::init_service(
            App::new()
                .app_data(path_config())
                .route("/users/{id}", web::get().to(accept_uuid)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get().uri("/users/1").to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(body["status"], 400);
        assert_eq!(body["error"], "Bad Request");
        assert!(
            body["message"]
                .as_str()
                .is_some_and(|message| message.contains("UUID parsing failed"))
        );
    }

    #[actix_web::test]
    async fn path_missing_field_errors_are_validation_shaped() {
        let app = actix_test::init_service(App::new().app_data(path_config()).route(
            "/orgs/{org_id}/users/{user}",
            web::get().to(accept_required_path),
        ))
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/orgs/550e8400-e29b-41d4-a716-446655440000/users/550e8400-e29b-41d4-a716-446655440000")
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(
            body,
            json!({
                "status": 400,
                "error": "Bad Request",
                "message": "Validation failed",
                "errors": {
                    "user_id": ["is required"]
                }
            })
        );
    }

    #[actix_web::test]
    async fn query_extractor_errors_are_caelix_json_errors() {
        let app = actix_test::init_service(
            App::new()
                .app_data(query_config())
                .route("/users", web::get().to(accept_query)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get()
                .uri("/users?limit=abc")
                .to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(body["status"], 400);
        assert_eq!(body["error"], "Bad Request");
        assert!(
            body["message"]
                .as_str()
                .is_some_and(|message| message.contains("invalid digit"))
        );
    }

    #[actix_web::test]
    async fn query_missing_field_errors_are_validation_shaped() {
        let app = actix_test::init_service(
            App::new()
                .app_data(query_config())
                .route("/users", web::get().to(accept_required_query)),
        )
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get().uri("/users").to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(
            body,
            json!({
                "status": 400,
                "error": "Bad Request",
                "message": "Validation failed",
                "errors": {
                    "q": ["is required"]
                }
            })
        );
    }

    #[actix_web::test]
    async fn unmatched_routes_are_caelix_json_errors() {
        let app = actix_test::init_service(App::new().configure(|cfg| {
            configure_caelix_services(
                cfg,
                DEFAULT_BODY_LIMIT_BYTES,
                #[cfg(feature = "uploads")]
                UploadConfig::default(),
                |_| {},
                None,
            )
        }))
        .await;

        let response = actix_test::call_service(
            &app,
            actix_test::TestRequest::get().uri("/missing").to_request(),
        )
        .await;

        assert_eq!(response.status(), StatusCode::NOT_FOUND);
        let body: Value = actix_test::read_body_json(response).await;
        assert_eq!(
            body,
            json!({
                "status": 404,
                "error": "Not Found",
                "message": "Cannot GET /missing"
            })
        );
    }

    #[actix_web::test]
    async fn application_runs_module_shutdown_hook() {
        SHUTDOWN_COUNT.store(0, Ordering::SeqCst);

        let application = Application::new::<ShutdownModule>().await.unwrap();
        application.shutdown().await.unwrap();

        assert_eq!(SHUTDOWN_COUNT.load(Ordering::SeqCst), 1);
    }

    #[actix_web::test]
    async fn doctor_mode_runs_startup_runtime_setup_and_shutdown_without_binding() {
        DOCTOR_CONSTRUCTION_COUNT.store(0, Ordering::SeqCst);
        DOCTOR_INIT_COUNT.store(0, Ordering::SeqCst);
        DOCTOR_STARTUP_COUNT.store(0, Ordering::SeqCst);
        DOCTOR_SHUTDOWN_COUNT.store(0, Ordering::SeqCst);
        DOCTOR_ROUTE_CONFIG_COUNT.store(0, Ordering::SeqCst);

        let application = Application::new::<DoctorModule>().await.unwrap();
        assert_eq!(DOCTOR_CONSTRUCTION_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(DOCTOR_INIT_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(DOCTOR_STARTUP_COUNT.load(Ordering::SeqCst), 1);

        application
            .listen_with_doctor_mode("not a socket address", true)
            .await
            .unwrap();

        assert_eq!(DOCTOR_ROUTE_CONFIG_COUNT.load(Ordering::SeqCst), 1);
        assert_eq!(DOCTOR_SHUTDOWN_COUNT.load(Ordering::SeqCst), 1);
    }

    #[actix_web::test]
    async fn doctor_mode_propagates_shutdown_failures() {
        let error = Application::new::<FailingShutdownModule>()
            .await
            .unwrap()
            .listen_with_doctor_mode("not a socket address", true)
            .await
            .unwrap_err();

        assert!(error.to_string().contains("shutdown failed"));
    }

    #[actix_web::test]
    async fn normal_listen_still_attempts_to_bind_the_configured_address() {
        let error = Application::new::<TestModule>()
            .await
            .unwrap()
            .listen_with_doctor_mode("127.0.0.1:not-a-port", false)
            .await
            .unwrap_err();

        assert!(error.to_string().contains("invalid port value"));
    }

    #[test]
    fn doctor_mode_requires_the_exact_process_argument() {
        assert!(has_doctor_argument([OsString::from("--doctor")]));
        assert!(!has_doctor_argument([OsString::from("--doctor=true")]));
        assert!(!has_doctor_argument([OsString::from("doctor")]));
    }

    #[actix_web::test]
    async fn to_actix_response_streams_chunked_body() {
        use actix_web::body::to_bytes;
        use caelix_core::{Bytes, Response};

        let stream = futures_util::stream::iter(vec![
            Ok::<_, caelix_core::HttpException>(Bytes::from_static(b"chunk-a-")),
            Ok(Bytes::from_static(b"chunk-b")),
        ]);
        let caelix = Response::stream("text/plain", stream);
        let actix_response = to_actix_response(caelix);

        assert_eq!(actix_response.status(), StatusCode::OK);
        assert_eq!(
            actix_response
                .headers()
                .get(actix_web::http::header::CONTENT_TYPE)
                .unwrap(),
            "text/plain"
        );

        let body = to_bytes(actix_response.into_body()).await.unwrap();
        assert_eq!(&body[..], b"chunk-a-chunk-b");
    }

    #[actix_web::test]
    async fn to_actix_response_applies_sse_headers() {
        use caelix_core::Response;

        let stream = futures_util::stream::iter(Vec::<
            std::result::Result<serde_json::Value, caelix_core::HttpException>,
        >::new());
        let actix_response = to_actix_response(Response::sse(stream));

        assert_eq!(
            actix_response
                .headers()
                .get(actix_web::http::header::CONTENT_TYPE)
                .unwrap(),
            "text/event-stream"
        );
        assert_eq!(
            actix_response.headers().get("cache-control").unwrap(),
            "no-cache"
        );
        assert_eq!(
            actix_response.headers().get("x-accel-buffering").unwrap(),
            "no"
        );
    }
}