a3s-boot 0.1.3

Adapter-first modular Rust web framework for A3S inspired by Nest.js
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
use super::cookie::CookieOptions;
use super::header::{
    get_header, is_json_media_type, matches_media_type, normalize_header_name, normalize_headers,
    parse_content_length, strict_content_length_values, validate_header_name,
    validate_header_value,
};
use super::streamable_file::{StreamableFile, StreamableFileBody, StreamableFileStream};
use crate::{BootError, Result, SseEvent, SseStream};
use futures_core::Stream;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::collections::BTreeMap;
use std::fmt;
use std::sync::{Arc, Mutex};

/// Framework-neutral HTTP response returned by Boot route handlers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BootResponse {
    pub status: u16,
    pub headers: BTreeMap<String, String>,
    pub appended_headers: Vec<(String, String)>,
    pub body: Vec<u8>,
    stream: Option<SharedResponseStream>,
}

#[derive(Clone)]
struct SharedResponseStream {
    kind: ResponseStreamKind,
    inner: Arc<Mutex<Option<ResponseStream>>>,
}

impl SharedResponseStream {
    fn new(stream: ResponseStream) -> Self {
        let kind = stream.kind();
        Self {
            kind,
            inner: Arc::new(Mutex::new(Some(stream))),
        }
    }

    fn kind(&self) -> ResponseStreamKind {
        self.kind
    }

    fn take(&self) -> Option<SseStream> {
        let mut guard = self.inner.lock().ok()?;
        match guard.take()? {
            ResponseStream::Sse(stream) => Some(stream),
            ResponseStream::Body(stream) => {
                *guard = Some(ResponseStream::Body(stream));
                None
            }
        }
    }

    fn take_body(&self) -> Option<StreamableFileStream> {
        let mut guard = self.inner.lock().ok()?;
        match guard.take()? {
            ResponseStream::Body(stream) => Some(stream),
            ResponseStream::Sse(stream) => {
                *guard = Some(ResponseStream::Sse(stream));
                None
            }
        }
    }
}

impl fmt::Debug for SharedResponseStream {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SharedResponseStream")
            .field("kind", &self.kind)
            .finish_non_exhaustive()
    }
}

impl PartialEq for SharedResponseStream {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

impl Eq for SharedResponseStream {}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ResponseStreamKind {
    Sse,
    Body,
}

enum ResponseStream {
    Sse(SseStream),
    Body(StreamableFileStream),
}

#[derive(Debug, Serialize)]
struct HttpErrorResponseBody {
    #[serde(rename = "statusCode")]
    status_code: u16,
    message: String,
    error: &'static str,
}

impl ResponseStream {
    fn kind(&self) -> ResponseStreamKind {
        match self {
            Self::Sse(_) => ResponseStreamKind::Sse,
            Self::Body(_) => ResponseStreamKind::Body,
        }
    }
}

impl Default for BootResponse {
    fn default() -> Self {
        Self::new(200, Vec::<u8>::new())
    }
}

impl BootResponse {
    pub fn new(status: u16, body: impl Into<Vec<u8>>) -> Self {
        Self {
            status,
            headers: BTreeMap::new(),
            appended_headers: Vec::new(),
            body: body.into(),
            stream: None,
        }
    }

    pub fn status(&self) -> u16 {
        self.status
    }

    pub fn body(&self) -> &[u8] {
        &self.body
    }

    pub fn into_body(self) -> Vec<u8> {
        self.body
    }

    pub fn empty(status: u16) -> Self {
        Self::new(status, Vec::<u8>::new())
    }

    pub fn no_content() -> Self {
        Self::empty(204)
    }

    pub fn redirect(location: impl Into<String>) -> Self {
        Self::redirect_with_status(302, location)
    }

    pub fn see_other(location: impl Into<String>) -> Self {
        Self::redirect_with_status(303, location)
    }

    pub fn temporary_redirect(location: impl Into<String>) -> Self {
        Self::redirect_with_status(307, location)
    }

    pub fn permanent_redirect(location: impl Into<String>) -> Self {
        Self::redirect_with_status(308, location)
    }

    pub fn redirect_with_status(status: u16, location: impl Into<String>) -> Self {
        Self::empty(status).with_location(location)
    }

    pub fn text(body: impl Into<String>) -> Self {
        Self::text_with_status(200, body)
    }

    pub fn text_with_status(status: u16, body: impl Into<String>) -> Self {
        Self::new(status, body.into()).with_header("content-type", "text/plain; charset=utf-8")
    }

    pub fn html(body: impl Into<String>) -> Self {
        Self::html_with_status(200, body)
    }

    pub fn html_with_status(status: u16, body: impl Into<String>) -> Self {
        Self::new(status, body.into()).with_header("content-type", "text/html; charset=utf-8")
    }

    pub fn json<T>(body: &T) -> Result<Self>
    where
        T: Serialize,
    {
        Self::json_with_status(200, body)
    }

    pub fn json_with_status<T>(status: u16, body: &T) -> Result<Self>
    where
        T: Serialize,
    {
        let body = serde_json::to_vec(body).map_err(|err| BootError::Internal(err.to_string()))?;
        Ok(Self::new(status, body).with_header("content-type", "application/json"))
    }

    pub fn sse<S>(stream: S) -> Self
    where
        S: Stream<Item = Result<SseEvent>> + Send + 'static,
    {
        Self::empty(200)
            .with_header("content-type", "text/event-stream; charset=utf-8")
            .with_header("cache-control", "no-cache")
            .with_header("connection", "keep-alive")
            .with_sse_stream(stream)
    }

    pub fn streamable_file(file: StreamableFile) -> Self {
        let (body, options) = file.into_parts();
        let mut response = match body {
            StreamableFileBody::Bytes(body) => {
                let content_length = options.content_length().unwrap_or(body.len() as u64);
                Self::new(200, body).with_content_length(content_length)
            }
            StreamableFileBody::Stream(stream) => {
                let response = Self::empty(200).with_body_stream(stream);
                if let Some(content_length) = options.content_length() {
                    response.with_content_length(content_length)
                } else {
                    response
                }
            }
        }
        .with_content_type(options.content_type().unwrap_or("application/octet-stream"));

        if let Some(content_disposition) = options.content_disposition() {
            response = response.with_header("content-disposition", content_disposition);
        }

        response
    }

    pub fn file(body: impl Into<Vec<u8>>) -> Self {
        Self::streamable_file(StreamableFile::bytes(body))
    }

    pub fn download(file_name: impl AsRef<str>, body: impl Into<Vec<u8>>) -> Result<Self> {
        Ok(Self::streamable_file(
            StreamableFile::bytes(body).with_attachment(file_name)?,
        ))
    }

    pub fn download_stream<S>(file_name: impl AsRef<str>, stream: S) -> Result<Self>
    where
        S: Stream<Item = Result<Vec<u8>>> + Send + 'static,
    {
        Ok(Self::streamable_file(
            StreamableFile::stream(stream).with_attachment(file_name)?,
        ))
    }

    pub fn from_error(error: &BootError) -> Self {
        let status = error.http_status_code();
        let body = HttpErrorResponseBody {
            status_code: status,
            message: error.http_response_message(),
            error: http_error_name(status),
        };
        let body = serde_json::to_vec(&body).unwrap_or_else(|_| {
            br#"{"statusCode":500,"message":"failed to encode error response","error":"Internal Server Error"}"#.to_vec()
        });

        Self::new(status, body).with_header("content-type", "application/json")
    }

    pub fn body_text(&self) -> Result<String> {
        if self.is_streaming() {
            return Err(BootError::Internal(
                "streaming response body cannot be read as text".to_string(),
            ));
        }
        String::from_utf8(self.body.clone()).map_err(|err| BootError::Internal(err.to_string()))
    }

    pub fn body_json<T>(&self) -> Result<T>
    where
        T: DeserializeOwned,
    {
        if self.is_streaming() {
            return Err(BootError::Internal(
                "streaming response body cannot be read as JSON".to_string(),
            ));
        }
        serde_json::from_slice(&self.body).map_err(|err| BootError::Internal(err.to_string()))
    }

    pub fn with_status(mut self, status: u16) -> Self {
        self.status = status;
        self
    }

    pub fn with_content_type(self, content_type: impl Into<String>) -> Self {
        self.with_header("content-type", content_type)
    }

    pub fn with_content_length(self, content_length: u64) -> Self {
        self.with_header("content-length", content_length.to_string())
    }

    pub fn with_location(self, location: impl Into<String>) -> Self {
        self.with_header("location", location)
    }

    pub fn with_www_authenticate(self, challenge: impl Into<String>) -> Self {
        self.with_header("www-authenticate", challenge)
    }

    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.headers
            .insert(normalize_header_name(name), value.into());
        self
    }

    pub fn with_headers(mut self, headers: BTreeMap<String, String>) -> Self {
        self.headers = normalize_headers(headers);
        self
    }

    pub fn append_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.appended_headers
            .push((normalize_header_name(name), value.into()));
        self
    }

    pub fn append_www_authenticate(self, challenge: impl Into<String>) -> Self {
        self.append_header("www-authenticate", challenge)
    }

    pub fn with_cookie(
        self,
        name: impl AsRef<str>,
        value: impl AsRef<str>,
        options: CookieOptions,
    ) -> Result<Self> {
        let header = options.set_cookie_header(name.as_ref(), value.as_ref())?;
        Ok(self.append_header("set-cookie", header))
    }

    pub fn delete_cookie(self, name: impl AsRef<str>, options: CookieOptions) -> Result<Self> {
        let header = options.delete_cookie_header(name.as_ref())?;
        Ok(self.append_header("set-cookie", header))
    }

    pub fn is_streaming(&self) -> bool {
        self.stream.is_some()
    }

    pub fn is_file_stream(&self) -> bool {
        self.stream
            .as_ref()
            .is_some_and(|stream| stream.kind() == ResponseStreamKind::Body)
    }

    pub fn is_event_stream(&self) -> bool {
        self.is_content_type("text/event-stream")
    }

    pub fn into_sse_stream(self) -> Option<SseStream> {
        self.stream.and_then(|stream| stream.take())
    }

    pub fn into_body_stream(self) -> Option<StreamableFileStream> {
        self.stream.and_then(|stream| stream.take_body())
    }

    pub fn header_entries(&self) -> impl Iterator<Item = (&str, &str)> {
        self.headers
            .iter()
            .map(|(name, value)| (name.as_str(), value.as_str()))
            .chain(
                self.appended_headers
                    .iter()
                    .map(|(name, value)| (name.as_str(), value.as_str())),
            )
    }

    pub fn validate_headers(&self) -> Result<()> {
        for (name, value) in self.header_entries() {
            validate_response_header(name, value)?;
        }

        Ok(())
    }

    pub fn header(&self, name: &str) -> Option<&str> {
        get_header(&self.headers, name)
    }

    pub fn header_values(&self, name: &str) -> Vec<&str> {
        let mut values = self.header(name).into_iter().collect::<Vec<_>>();
        values.extend(
            self.appended_headers
                .iter()
                .filter(|(key, _)| key.eq_ignore_ascii_case(name))
                .map(|(_, value)| value.as_str()),
        );
        values
    }

    pub fn content_type(&self) -> Option<&str> {
        self.header_values("content-type").into_iter().next()
    }

    pub fn location(&self) -> Option<&str> {
        self.header_values("location").into_iter().next()
    }

    pub fn www_authenticate(&self) -> Option<&str> {
        self.header_values("www-authenticate").into_iter().next()
    }

    pub fn www_authenticate_values(&self) -> Vec<&str> {
        self.header_values("www-authenticate")
    }

    pub fn content_length(&self) -> Result<Option<u64>> {
        let Some(content_length) = self.header_values("content-length").into_iter().next() else {
            return Ok(None);
        };

        parse_content_length(content_length)
            .map(Some)
            .ok_or_else(|| {
                BootError::Internal(format!("invalid content-length header: {content_length}"))
            })
    }

    pub fn strict_content_length(&self) -> Result<Option<u64>> {
        strict_content_length_values(
            self.header_values("content-length"),
            |content_length| {
                BootError::Internal(format!(
                    "invalid response content-length header: {content_length}"
                ))
            },
            |expected_content_length, content_length| {
                BootError::Internal(format!(
                    "conflicting response content-length headers: {expected_content_length} != {content_length}"
                ))
            },
        )
    }

    pub fn validate_content_length(&self) -> Result<()> {
        let Some(content_length) = self.strict_content_length()? else {
            return Ok(());
        };
        if self.is_streaming() {
            if self.is_file_stream() {
                return Ok(());
            }
            return Err(BootError::Internal(
                "streaming responses must not include a content-length header".to_string(),
            ));
        }

        let actual_body_length = self.body.len() as u64;
        if actual_body_length == content_length {
            return Ok(());
        }

        Err(BootError::Internal(format!(
            "response content-length header does not match response body length: expected {content_length}, got {actual_body_length}"
        )))
    }

    pub fn is_content_type(&self, media_type: &str) -> bool {
        self.content_type()
            .is_some_and(|content_type| matches_media_type(content_type, media_type))
    }

    pub fn is_json_content_type(&self) -> bool {
        self.content_type().is_some_and(is_json_media_type)
    }

    pub fn has_body(&self) -> bool {
        self.is_streaming() || !self.body.is_empty()
    }

    pub fn allows_body(&self) -> bool {
        !(self.is_informational() || self.status == 204 || self.status == 304)
    }

    pub fn validate_body_allowed(&self) -> Result<()> {
        if !self.has_body() || self.allows_body() {
            return Ok(());
        }

        Err(BootError::Internal(format!(
            "response status {} must not include a body",
            self.status
        )))
    }

    pub fn is_informational(&self) -> bool {
        (100..200).contains(&self.status)
    }

    pub fn is_success(&self) -> bool {
        (200..300).contains(&self.status)
    }

    pub fn is_redirection(&self) -> bool {
        (300..400).contains(&self.status)
    }

    pub fn is_client_error(&self) -> bool {
        (400..500).contains(&self.status)
    }

    pub fn is_server_error(&self) -> bool {
        (500..600).contains(&self.status)
    }

    pub fn is_error(&self) -> bool {
        self.is_client_error() || self.is_server_error()
    }

    pub fn is_valid_status(&self) -> bool {
        (100..1000).contains(&self.status)
    }

    pub fn validate_status(&self) -> Result<()> {
        if self.is_valid_status() {
            return Ok(());
        }

        Err(BootError::Internal(format!(
            "invalid response status {}",
            self.status
        )))
    }

    pub fn validate(&self) -> Result<()> {
        self.validate_status()?;
        self.validate_content_length()?;
        self.validate_body_allowed()?;
        self.validate_headers()
    }

    fn with_sse_stream<S>(mut self, stream: S) -> Self
    where
        S: Stream<Item = Result<SseEvent>> + Send + 'static,
    {
        self.stream = Some(SharedResponseStream::new(ResponseStream::Sse(Box::pin(
            stream,
        ))));
        self
    }

    fn with_body_stream(mut self, stream: StreamableFileStream) -> Self {
        self.stream = Some(SharedResponseStream::new(ResponseStream::Body(stream)));
        self
    }
}

fn http_error_name(status: u16) -> &'static str {
    match status {
        400 => "Bad Request",
        401 => "Unauthorized",
        402 => "Payment Required",
        403 => "Forbidden",
        404 => "Not Found",
        405 => "Method Not Allowed",
        406 => "Not Acceptable",
        407 => "Proxy Authentication Required",
        408 => "Request Timeout",
        409 => "Conflict",
        410 => "Gone",
        411 => "Length Required",
        412 => "Precondition Failed",
        413 => "Payload Too Large",
        414 => "URI Too Long",
        415 => "Unsupported Media Type",
        416 => "Range Not Satisfiable",
        417 => "Expectation Failed",
        418 => "I'm a teapot",
        421 => "Misdirected Request",
        422 => "Unprocessable Entity",
        423 => "Locked",
        424 => "Failed Dependency",
        425 => "Too Early",
        426 => "Upgrade Required",
        428 => "Precondition Required",
        429 => "Too Many Requests",
        431 => "Request Header Fields Too Large",
        451 => "Unavailable For Legal Reasons",
        500 => "Internal Server Error",
        501 => "Not Implemented",
        502 => "Bad Gateway",
        503 => "Service Unavailable",
        504 => "Gateway Timeout",
        505 => "HTTP Version Not Supported",
        506 => "Variant Also Negotiates",
        507 => "Insufficient Storage",
        508 => "Loop Detected",
        510 => "Not Extended",
        511 => "Network Authentication Required",
        _ => "Http Exception",
    }
}

fn validate_response_header(name: &str, value: &str) -> Result<()> {
    validate_header_name(name).map_err(|message| {
        BootError::Internal(format!("invalid response header name {name:?}: {message}"))
    })?;
    validate_header_value(value).map_err(|message| {
        BootError::Internal(format!(
            "invalid response header value for {name:?}: {message}"
        ))
    })
}