zino-http 0.15.1

HTTP requests and responses for zino.
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
//! Constructing responses and rejections.
//!
//! # Examples
//!
//! ```rust
//! use zino_core::{application::ApplicationCode, error::Error, SharedString};
//! use zino_http::response::{Response, StatusCode};
//!
//! #[derive(Debug, Clone, Copy, Default, PartialEq)]
//! #[repr(i32)]
//! pub enum AppCode {
//!     #[default]
//!     Success = 20000,
//!     InvalidInput = 40001,
//!     InternalError = 50000,
//! }
//!
//! impl ApplicationCode for AppCode {
//!     #[inline]
//!     fn code(&self) -> i32 {
//!         *self as i32
//!     }
//!
//!     #[inline]
//!     fn message(&self) -> SharedString {
//!         match self {
//!             AppCode::Success => "success".into(),
//!             AppCode::InvalidInput => "invalid input".into(),
//!             AppCode::InternalError => "internal error".into(),
//!         }
//!     }
//! }
//!
//! async fn send_success_response() -> Result<Response<StatusCode>, Error> {
//!     let mut res = Response::default();
//!     res.set_app_code(&AppCode::Success);
//!     Ok(res)
//! }
//! ```

use crate::{
    helper,
    request::RequestContext,
    timing::{ServerTiming, TimingMetric},
};
use bytes::Bytes;
use etag::EntityTag;
use http::{HeaderMap, HeaderName};
use serde::Serialize;
use std::{
    marker::PhantomData,
    mem,
    time::{Duration, Instant},
};
use zino_core::{
    JsonValue, SharedString, Uuid, application::ApplicationCode, error::Error,
    extension::JsonValueExt, trace::TraceContext, validation::Validation,
};
use zino_storage::NamedFile;

#[cfg(feature = "inertia")]
use crate::inertia::InertiaPage;

#[cfg(feature = "cookie")]
use cookie::{Cookie, SameSite};

mod rejection;
mod response_code;
mod webhook;

pub use rejection::{ExtractRejection, Rejection};
pub use response_code::ResponseCode;
pub use webhook::WebHook;

/// An HTTP status code for http v0.2.
#[cfg(feature = "http02")]
pub type StatusCode = http02::StatusCode;

/// An HTTP status code.
#[cfg(not(feature = "http02"))]
pub type StatusCode = http::StatusCode;

/// A function pointer of transforming the response data.
pub type DataTransformer = fn(data: &JsonValue) -> Result<Bytes, Error>;

/// An HTTP response.
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct Response<S: ResponseCode> {
    /// A URI reference that identifies the problem type.
    #[serde(rename = "type")]
    #[serde(skip_serializing_if = "Option::is_none")]
    type_uri: Option<SharedString>,
    /// A short, human-readable summary of the problem type.
    #[serde(skip_serializing_if = "Option::is_none")]
    title: Option<SharedString>,
    /// Status code.
    #[serde(rename = "status")]
    status_code: u16,
    /// Application code.
    #[serde(rename = "code")]
    #[serde(skip_serializing_if = "Option::is_none")]
    app_code: Option<i32>,
    /// A human-readable explanation specific to this occurrence of the problem.
    #[serde(skip_serializing_if = "Option::is_none")]
    detail: Option<SharedString>,
    /// A URI reference that identifies the specific occurrence of the problem.
    #[serde(skip_serializing_if = "Option::is_none")]
    instance: Option<SharedString>,
    /// Indicates the response is successful or not.
    success: bool,
    /// A context-specific descriptive message for successful response.
    #[serde(skip_serializing_if = "Option::is_none")]
    message: Option<SharedString>,
    /// Start time.
    #[serde(skip)]
    start_time: Instant,
    /// Request ID.
    #[serde(skip_serializing_if = "Uuid::is_nil")]
    request_id: Uuid,
    /// JSON data.
    #[serde(rename = "data")]
    #[serde(skip_serializing_if = "JsonValue::is_null")]
    json_data: JsonValue,
    /// Bytes data.
    #[serde(skip)]
    bytes_data: Bytes,
    /// Transformer of the response data.
    #[serde(skip)]
    data_transformer: Option<DataTransformer>,
    /// Content type.
    #[serde(skip)]
    content_type: Option<SharedString>,
    /// Trace context.
    #[serde(skip)]
    trace_context: Option<TraceContext>,
    /// Server timing.
    #[serde(skip)]
    server_timing: ServerTiming,
    /// Custom headers.
    #[serde(skip)]
    headers: HeaderMap<String>,
    /// Phantom type of response code.
    #[serde(skip)]
    phantom: PhantomData<S>,
}

impl<S: ResponseCode> Response<S> {
    /// Creates a new instance.
    pub fn new(code: S) -> Self {
        let success = code.is_success();
        let message = code.message();
        let mut res = Self {
            type_uri: code.type_uri(),
            title: code.title(),
            status_code: code.status_code(),
            app_code: None,
            detail: None,
            instance: None,
            success,
            message: None,
            start_time: Instant::now(),
            request_id: Uuid::nil(),
            json_data: JsonValue::Null,
            bytes_data: Bytes::new(),
            data_transformer: None,
            content_type: None,
            trace_context: None,
            server_timing: ServerTiming::new(),
            headers: HeaderMap::default(),
            phantom: PhantomData,
        };
        if success {
            res.message = message;
        } else {
            res.detail = message;
        }
        res
    }

    /// Creates a new instance with the request context.
    pub fn with_context<Ctx: RequestContext>(code: S, ctx: &Ctx) -> Self {
        let success = code.is_success();
        let message = code.message();
        let mut res = Self {
            type_uri: code.type_uri(),
            title: code.title(),
            status_code: code.status_code(),
            app_code: None,
            detail: None,
            instance: (!success).then(|| ctx.instance().into()),
            success,
            message: None,
            start_time: ctx.start_time(),
            request_id: ctx.request_id(),
            json_data: JsonValue::Null,
            bytes_data: Bytes::new(),
            data_transformer: None,
            content_type: None,
            trace_context: None,
            server_timing: ServerTiming::new(),
            headers: HeaderMap::default(),
            phantom: PhantomData,
        };
        if success {
            res.message = message;
        } else {
            res.detail = message;
        }
        res.trace_context = Some(ctx.new_trace_context());
        res
    }

    /// Provides the request context for the response.
    pub fn context<Ctx: RequestContext>(mut self, ctx: &Ctx) -> Self {
        self.instance = (!self.is_success()).then(|| ctx.instance().into());
        self.start_time = ctx.start_time();
        self.request_id = ctx.request_id();
        self.trace_context = Some(ctx.new_trace_context());
        self
    }

    /// Renders a template with the data and sets it as the reponse.
    #[cfg(feature = "view")]
    pub fn render<T: Serialize>(mut self, template_name: &str, data: T) -> Self {
        let result = serde_json::to_value(data)
            .map_err(|err| err.into())
            .and_then(|value| {
                if let JsonValue::Object(map) = value {
                    crate::view::render(template_name, map)
                } else {
                    Err(zino_core::warn!("invalid template data"))
                }
            });
        match result {
            Ok(content) => {
                self.json_data = content.into();
                self.bytes_data = Bytes::new();
                self.content_type = Some("text/html; charset=utf-8".into());
            }
            Err(err) => {
                let code = S::INTERNAL_SERVER_ERROR;
                self.type_uri = code.type_uri();
                self.title = code.title();
                self.status_code = code.status_code();
                self.success = false;
                self.detail = Some(err.to_string().into());
                self.json_data = JsonValue::Null;
                self.bytes_data = Bytes::new();
            }
        }
        self
    }

    /// Sets the response code.
    pub fn set_code(&mut self, code: S) {
        let success = code.is_success();
        let message = code.message();
        self.type_uri = code.type_uri();
        self.title = code.title();
        self.status_code = code.status_code();
        self.success = success;
        if success {
            self.detail = None;
            self.message = message;
        } else {
            self.detail = message;
            self.message = None;
        }
    }

    /// Sets the status code.
    #[inline]
    pub fn set_status_code(&mut self, status_code: impl Into<u16>) {
        self.status_code = status_code.into();
    }

    /// Sets the application code.
    #[inline]
    pub fn set_app_code<C: ApplicationCode>(&mut self, app_code: &C) {
        self.app_code = Some(app_code.code());
        self.message = Some(app_code.message());
    }

    /// Sets a URI reference that identifies the specific occurrence of the problem.
    #[inline]
    pub fn set_instance(&mut self, instance: impl Into<SharedString>) {
        self.instance = Some(instance.into());
    }

    /// Sets the message. If the response is not successful,
    /// it should be a human-readable explanation specific to this occurrence of the problem.
    pub fn set_message(&mut self, message: impl Into<SharedString>) {
        fn inner<S: ResponseCode>(res: &mut Response<S>, message: SharedString) {
            if res.is_success() {
                res.detail = None;
                res.message = Some(message);
            } else {
                res.detail = Some(message);
                res.message = None;
            }
        }
        inner::<S>(self, message.into())
    }

    /// Sets the error message.
    pub fn set_error_message(&mut self, error: impl Into<Error>) {
        fn inner<S: ResponseCode>(res: &mut Response<S>, error: Error) {
            let message = error.to_string().into();
            if res.is_success() {
                res.detail = None;
                res.message = Some(message);
            } else {
                res.detail = Some(message);
                res.message = None;
            }
        }
        inner::<S>(self, error.into())
    }

    /// Sets the response data.
    #[inline]
    pub fn set_data<T: Serialize>(&mut self, data: &T) {
        match serde_json::to_value(data) {
            Ok(value) => {
                self.json_data = value;
                self.bytes_data = Bytes::new();
            }
            Err(err) => self.set_error_message(err),
        }
    }

    /// Sets the JSON data.
    #[inline]
    pub fn set_json_data(&mut self, data: impl Into<JsonValue>) {
        self.json_data = data.into();
        self.bytes_data = Bytes::new();
    }

    /// Sets the bytes data.
    #[inline]
    pub fn set_bytes_data(&mut self, data: impl Into<Bytes>) {
        self.json_data = JsonValue::Null;
        self.bytes_data = data.into();
    }

    /// Sets the response data for the validation.
    #[inline]
    pub fn set_validation_data(&mut self, validation: Validation) {
        self.json_data = validation.into_map().into();
        self.bytes_data = Bytes::new();
    }

    /// Sets a transformer for the response data.
    #[inline]
    pub fn set_data_transformer(&mut self, transformer: DataTransformer) {
        self.data_transformer = Some(transformer);
    }

    /// Sets the content type.
    ///
    /// # Note
    ///
    /// Currently, we have built-in support for the following values:
    ///
    /// - `application/json`
    /// - `application/jsonlines`
    /// - `application/octet-stream`
    /// - `application/problem+json`
    /// - `application/x-www-form-urlencoded`
    /// - `text/csv`
    /// - `text/html`
    /// - `text/plain`
    #[inline]
    pub fn set_content_type(&mut self, content_type: impl Into<SharedString>) {
        self.content_type = Some(content_type.into());
    }

    /// Sets the form data as the response body.
    #[inline]
    pub fn set_form_response(&mut self, data: impl Into<JsonValue>) {
        fn inner<S: ResponseCode>(res: &mut Response<S>, data: JsonValue) {
            res.set_json_data(data);
            res.set_content_type("application/x-www-form-urlencoded");
            res.set_data_transformer(|data| {
                let mut bytes = Vec::new();
                serde_qs::to_writer(&data, &mut bytes)?;
                Ok(bytes.into())
            });
        }
        inner::<S>(self, data.into())
    }

    /// Sets the JSON data as the response body.
    #[inline]
    pub fn set_json_response(&mut self, data: impl Into<JsonValue>) {
        fn inner<S: ResponseCode>(res: &mut Response<S>, data: JsonValue) {
            res.set_json_data(data);
            res.set_data_transformer(|data| Ok(serde_json::to_vec(&data)?.into()));
        }
        inner::<S>(self, data.into())
    }

    /// Sets the JSON Lines data as the response body.
    #[inline]
    pub fn set_jsonlines_response(&mut self, data: impl Into<JsonValue>) {
        fn inner<S: ResponseCode>(res: &mut Response<S>, data: JsonValue) {
            res.set_json_data(data);
            res.set_content_type("application/jsonlines; charset=utf-8");
            res.set_data_transformer(|data| Ok(data.to_jsonlines(Vec::new())?.into()));
        }
        inner::<S>(self, data.into())
    }

    /// Sets the CSV data as the response body.
    #[inline]
    pub fn set_csv_response(&mut self, data: impl Into<JsonValue>) {
        fn inner<S: ResponseCode>(res: &mut Response<S>, data: JsonValue) {
            res.set_json_data(data);
            res.set_content_type("text/csv; charset=utf-8");
            res.set_data_transformer(|data| Ok(data.to_csv(Vec::new())?.into()));
        }
        inner::<S>(self, data.into())
    }

    /// Sets the plain text as the response body.
    #[inline]
    pub fn set_text_response(&mut self, data: impl Into<String>) {
        self.set_json_data(data.into());
        self.set_content_type("text/plain; charset=utf-8");
    }

    /// Sets the bytes data as the response body.
    #[inline]
    pub fn set_bytes_response(&mut self, data: impl Into<Bytes>) {
        self.set_bytes_data(data);
        self.set_content_type("application/octet-stream");
    }

    /// Sets the request ID.
    #[inline]
    pub(crate) fn set_request_id(&mut self, request_id: Uuid) {
        self.request_id = request_id;
    }

    /// Sets the trace context from headers.
    #[inline]
    pub(crate) fn set_trace_context(&mut self, trace_context: Option<TraceContext>) {
        self.trace_context = trace_context;
    }

    /// Sets the start time.
    #[inline]
    pub(crate) fn set_start_time(&mut self, start_time: Instant) {
        self.start_time = start_time;
    }

    /// Sends a cookie to the user agent.
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn set_cookie(&mut self, cookie: &Cookie<'_>) {
        self.insert_header("set-cookie", cookie.to_string());
    }

    /// Clears a cookie for the given name.
    #[cfg(feature = "cookie")]
    #[inline]
    pub fn clear_cookie(&mut self, name: impl Into<SharedString>) {
        let cookie = Cookie::build((name, ""))
            .path("/")
            .http_only(true)
            .secure(true)
            .same_site(SameSite::Lax)
            .removal()
            .build();
        self.insert_header("set-cookie", cookie.to_string());
    }

    /// Records a server timing metric entry.
    pub fn record_server_timing(
        &mut self,
        name: impl Into<SharedString>,
        description: impl Into<Option<SharedString>>,
        duration: impl Into<Option<Duration>>,
    ) {
        fn inner<S: ResponseCode>(
            res: &mut Response<S>,
            name: SharedString,
            description: Option<SharedString>,
            duration: Option<Duration>,
        ) {
            let metric = TimingMetric::new(name, description, duration);
            res.server_timing.push(metric);
        }
        inner::<S>(self, name.into(), description.into(), duration.into())
    }

    /// Inserts a custom header.
    #[inline]
    pub fn insert_header(&mut self, name: &'static str, value: impl ToString) {
        self.headers
            .insert(HeaderName::from_static(name), value.to_string());
    }

    /// Gets a custome header with the given name.
    #[inline]
    pub fn get_header(&self, name: &str) -> Option<&str> {
        self.headers
            .iter()
            .find_map(|(key, value)| (key == name).then_some(value.as_str()))
    }

    /// Returns the status code as `u16`.
    #[inline]
    pub fn status_code(&self) -> u16 {
        self.status_code
    }

    /// Returns the optional application code.
    #[inline]
    pub fn app_code(&self) -> Option<i32> {
        self.app_code
    }

    /// Returns `true` if the response is successful or `false` otherwise.
    #[inline]
    pub fn is_success(&self) -> bool {
        self.success
    }

    /// Returns `true` if the response has a request context.
    #[inline]
    pub fn has_context(&self) -> bool {
        self.trace_context.is_some() && !self.request_id.is_nil()
    }

    /// Returns the message.
    #[inline]
    pub fn message(&self) -> Option<&str> {
        self.detail
            .as_ref()
            .or(self.message.as_ref())
            .map(|s| s.as_ref())
    }

    /// Returns the request ID.
    #[inline]
    pub fn request_id(&self) -> Uuid {
        self.request_id
    }

    /// Returns the trace ID.
    #[inline]
    pub fn trace_id(&self) -> Uuid {
        if let Some(ref trace_context) = self.trace_context {
            Uuid::from_u128(trace_context.trace_id())
        } else {
            Uuid::nil()
        }
    }

    /// Returns the content type.
    #[inline]
    pub fn content_type(&self) -> &str {
        self.content_type.as_deref().unwrap_or_else(|| {
            if !self.bytes_data.is_empty() {
                "application/octet-stream"
            } else if self.is_success() {
                "application/json; charset=utf-8"
            } else {
                "application/problem+json; charset=utf-8"
            }
        })
    }

    /// Returns a reference to the custom headers.
    #[inline]
    pub fn headers(&self) -> &HeaderMap<String> {
        &self.headers
    }

    /// Returns a mutable reference to the custom headers.
    #[inline]
    pub fn headers_mut(&mut self) -> &mut HeaderMap<String> {
        &mut self.headers
    }

    /// Returns the trace context in the form `(traceparent, tracestate)`.
    pub fn trace_context(&self) -> (String, String) {
        if let Some(ref trace_context) = self.trace_context {
            (trace_context.traceparent(), trace_context.tracestate())
        } else {
            let mut trace_context = TraceContext::new();
            trace_context.record_trace_state();
            (trace_context.traceparent(), trace_context.tracestate())
        }
    }

    /// Returns the server timing.
    #[inline]
    pub fn server_timing(&self) -> String {
        self.server_timing.to_string()
    }

    /// Reads the response into a byte buffer.
    pub fn read_bytes(&mut self) -> Result<Bytes, Error> {
        let has_bytes_data = !self.bytes_data.is_empty();
        let has_json_data = !self.json_data.is_null();
        let bytes_opt = if has_bytes_data {
            Some(mem::take(&mut self.bytes_data))
        } else if has_json_data {
            if let Some(transformer) = self.data_transformer.as_ref() {
                Some(transformer(&self.json_data)?)
            } else {
                None
            }
        } else {
            None
        };
        if let Some(bytes) = bytes_opt {
            let etag = EntityTag::from_data(&bytes);
            self.insert_header("x-etag", etag);
            return Ok(bytes);
        }

        let content_type = self.content_type();
        let (bytes, etag_opt) = if crate::helper::check_json_content_type(content_type) {
            let (capacity, etag_opt) = if has_json_data {
                let data = serde_json::to_vec(&self.json_data)?;
                let etag = EntityTag::from_data(&data);
                (data.len() + 128, Some(etag))
            } else {
                (128, None)
            };
            let mut bytes = Vec::with_capacity(capacity);
            serde_json::to_writer(&mut bytes, &self)?;
            (bytes, etag_opt)
        } else if has_json_data {
            let bytes = if content_type.starts_with("text/csv") {
                self.json_data.to_csv(Vec::new())?
            } else if content_type.starts_with("application/jsonlines") {
                self.json_data.to_jsonlines(Vec::new())?
            } else {
                let text = if let JsonValue::String(s) = &mut self.json_data {
                    mem::take(s)
                } else {
                    self.json_data.to_string()
                };
                text.into_bytes()
            };
            (bytes, None)
        } else {
            (Vec::new(), None)
        };
        let etag = etag_opt.unwrap_or_else(|| EntityTag::from_data(&bytes));
        self.insert_header("x-etag", etag);
        Ok(bytes.into())
    }

    /// Gets the response time.
    ///
    /// # Note
    ///
    /// It should only be called when the response will finish.
    pub fn response_time(&self) -> Duration {
        let start_time = self.start_time;
        #[cfg(feature = "metrics")]
        {
            let labels = [("status_code", self.status_code().to_string())];
            metrics::gauge!("zino_http_requests_in_flight").decrement(1.0);
            metrics::counter!("zino_http_responses_total", &labels).increment(1);
            metrics::histogram!("zino_http_requests_duration_seconds", &labels,)
                .record(start_time.elapsed().as_secs_f64());
        }
        start_time.elapsed()
    }

    /// Sends a file to the client.
    pub fn send_file(&mut self, file: NamedFile) {
        let mut displayed_inline = false;
        if let Some(content_type) = file.content_type() {
            displayed_inline = helper::displayed_inline(content_type);
            self.set_content_type(content_type.to_string());
        }
        if !displayed_inline && let Some(file_name) = file.file_name() {
            self.insert_header(
                "content-disposition",
                format!(r#"attachment; filename="{file_name}""#),
            );
        }
        self.insert_header("etag", file.etag());
        self.set_bytes_data(Bytes::from(file));
    }

    /// Sends an Inertia page to the client.
    #[cfg(feature = "inertia")]
    pub fn send_inertia_page(&mut self, mut page: InertiaPage) {
        if page.version().is_empty() {
            page.set_version(zino_core::datetime::DateTime::current_timestamp().to_string());
        }
        self.insert_header("vary", "x-inertia");
        self.insert_header("x-inertia", true);
        if let Some(url) = page.redirect_url() {
            self.insert_header("x-inertia-location", url);
        } else {
            self.set_json_response(page.into_json_response());
        }
    }

    /// Emits the response for the request.
    pub fn emit<Ctx: RequestContext>(mut self, ctx: &Ctx) -> Self {
        if ctx
            .get_header("prefer")
            .is_some_and(|s| s.split(';').any(|p| p.trim() == "return=data-only"))
        {
            self.set_data_transformer(|data| Ok(serde_json::to_vec(&data)?.into()));
        }
        #[cfg(feature = "inertia")]
        if self.get_header("x-inertia").is_none()
            && ctx.get_header("x-inertia-partial-component").is_some()
        {
            match InertiaPage::partial_reload(ctx) {
                Ok(mut page) => {
                    if let JsonValue::Object(data) = &mut self.json_data {
                        page.append_props(data);
                    }
                    self.send_inertia_page(page);
                }
                Err(err) => self.set_error_message(err),
            }
        }
        self
    }

    /// Consumes `self` and returns the custom headers.
    pub fn finalize(mut self) -> HeaderMap<String> {
        let request_id = self.request_id();
        if !request_id.is_nil() {
            self.insert_header("x-request-id", request_id.to_string());
        }

        let (traceparent, tracestate) = self.trace_context();
        self.insert_header("traceparent", traceparent);
        self.insert_header("tracestate", tracestate);

        let duration = self.response_time();
        self.record_server_timing("total", None, Some(duration));
        self.insert_header("server-timing", self.server_timing());
        self.headers
    }
}

impl Response<StatusCode> {
    /// Constructs a new response with status `200 OK`.
    #[inline]
    pub fn ok() -> Self {
        Response::new(StatusCode::OK)
    }

    /// Constructs a new response with status `201 Created`.
    #[inline]
    pub fn created() -> Self {
        Response::new(StatusCode::CREATED)
    }

    /// Constructs a new response with status `303 See Other`.
    #[inline]
    pub fn redirect(uri: &str) -> Self {
        let mut res = Response::new(StatusCode::SEE_OTHER);
        res.insert_header("location", uri);
        res
    }

    /// Constructs a new response with status `307 Temporary Redirect`.
    #[inline]
    pub fn temporary_redirect(uri: &str) -> Self {
        let mut res = Response::new(StatusCode::TEMPORARY_REDIRECT);
        res.insert_header("location", uri);
        res
    }

    /// Constructs a new response with status `308 Permanent Redirect`.
    #[inline]
    pub fn permanent_redirect(uri: &str) -> Self {
        let mut res = Response::new(StatusCode::PERMANENT_REDIRECT);
        res.insert_header("location", uri);
        res
    }

    /// Constructs a new response with status `400 Bad Request`.
    #[inline]
    pub fn bad_request() -> Self {
        Response::new(StatusCode::BAD_REQUEST)
    }

    /// Constructs a new response with status `401 Unauthorized`.
    #[inline]
    pub fn unauthorized() -> Self {
        Response::new(StatusCode::UNAUTHORIZED)
    }

    /// Constructs a new response with status `403 Forbidden`.
    #[inline]
    pub fn forbidden() -> Self {
        Response::new(StatusCode::FORBIDDEN)
    }

    /// Constructs a new response with status `404 Not Found`.
    #[inline]
    pub fn not_found() -> Self {
        Response::new(StatusCode::NOT_FOUND)
    }

    /// Constructs a new response with status `405 Method Not Allowed`.
    #[inline]
    pub fn method_not_allowed() -> Self {
        Response::new(StatusCode::METHOD_NOT_ALLOWED)
    }

    /// Constructs a new response with status `409 Conflict`.
    #[inline]
    pub fn conflict() -> Self {
        Response::new(StatusCode::CONFLICT)
    }

    /// Constructs a new response with status `500 Internal Server Error`.
    #[inline]
    pub fn internal_server_error() -> Self {
        Response::new(StatusCode::INTERNAL_SERVER_ERROR)
    }

    /// Constructs a new response with status `503 Service Unavailable`.
    #[inline]
    pub fn service_unavailable() -> Self {
        Response::new(StatusCode::SERVICE_UNAVAILABLE)
    }
}

impl<S: ResponseCode> Default for Response<S> {
    #[inline]
    fn default() -> Self {
        Self::new(S::OK)
    }
}

impl<S: ResponseCode> From<Validation> for Response<S> {
    fn from(validation: Validation) -> Self {
        if validation.is_success() {
            Self::new(S::OK)
        } else {
            let mut res = Self::new(S::BAD_REQUEST);
            res.set_validation_data(validation);
            res
        }
    }
}