glacier-web 0.4.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! HTTP responses and the `IntoResponse` conversion trait.

use bytes::Bytes;
use http::{Extensions, HeaderMap, HeaderName, HeaderValue, StatusCode, header};
use http_body_util::Full;
use serde::Serialize;

use crate::error::Error;

/// Marks a [`Response::head`] response.
#[derive(Debug, Clone, Copy)]
struct Head;

/// A fully buffered HTTP response.
#[derive(Debug, Clone)]
pub struct Response {
    status: StatusCode,
    headers: HeaderMap,
    body: Bytes,
    extensions: Extensions,
}

impl Default for Response {
    fn default() -> Self {
        Self::new(StatusCode::OK)
    }
}

impl Response {
    /// An empty response with the given status.
    pub fn new(status: StatusCode) -> Self {
        Self {
            status,
            headers: HeaderMap::new(),
            body: Bytes::new(),
            extensions: Extensions::new(),
        }
    }

    pub fn text(body: impl Into<String>) -> Self {
        Self::with_body(body.into(), "text/plain; charset=utf-8")
    }

    pub fn html(body: impl Into<String>) -> Self {
        Self::with_body(body.into(), "text/html; charset=utf-8")
    }

    /// Serializes `value` as JSON. Serialization failures become a 500.
    /// With [`escape_html_entities_in_json`] on, `<`, `>` and `&` are
    /// written `\u003c`, `\u003e` and `\u0026`, as Rails writes them.
    pub fn json<T: Serialize + ?Sized>(value: &T) -> Self {
        match serde_json::to_vec(value) {
            Ok(body) if ESCAPE_HTML.load(std::sync::atomic::Ordering::Relaxed) => {
                Self::with_body(escape_html(&body), "application/json; charset=utf-8")
            }
            Ok(body) => Self::with_body(body, "application/json; charset=utf-8"),
            Err(err) => Error::from(err).into_response(),
        }
    }

    /// A `303 See Other` redirect, the right status after a form submission.
    pub fn redirect(location: &str) -> Self {
        Self::new(StatusCode::SEE_OTHER).with_header(header::LOCATION, location)
    }

    /// A file for the browser to save, as Rails' `send_data`: its type
    /// from the name's extension (`application/octet-stream` if unknown)
    /// and a `Content-Disposition: attachment` naming it.
    pub fn download(bytes: impl Into<Bytes>, filename: &str) -> Self {
        Self::send_data(bytes, filename, "attachment")
    }

    /// A file for the browser to show, such as a PDF in its viewer, as
    /// Rails' `send_data …, disposition: "inline"`.
    pub fn inline(bytes: impl Into<Bytes>, filename: &str) -> Self {
        Self::send_data(bytes, filename, "inline")
    }

    fn send_data(bytes: impl Into<Bytes>, filename: &str, disposition: &str) -> Self {
        let extension = filename
            .rsplit_once('.')
            .map(|(_, ext)| ext.to_ascii_lowercase());
        let content_type = extension
            .as_deref()
            .and_then(crate::mime::for_format)
            .unwrap_or("application/octet-stream");
        // An ASCII fallback and the exact name, as Rails writes it.
        let ascii: String = filename
            .chars()
            .map(|c| {
                if c.is_ascii_graphic() && c != '"' && c != '\\' || c == ' ' {
                    c
                } else {
                    '_'
                }
            })
            .collect();
        const UNRESERVED: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
            .remove(b'-')
            .remove(b'.')
            .remove(b'_')
            .remove(b'~');
        let exact = percent_encoding::utf8_percent_encode(filename, UNRESERVED);
        Self::new(StatusCode::OK)
            .with_body_bytes(bytes)
            .with_header(header::CONTENT_TYPE, content_type)
            .with_header(
                header::CONTENT_DISPOSITION,
                format!("{disposition}; filename=\"{ascii}\"; filename*=UTF-8''{exact}"),
            )
    }

    /// A response with only a status and no body, as Rails' `head :ok`.
    /// Error statuses stay empty too: `Pipeline::api` leaves them be.
    pub fn head(status: StatusCode) -> Self {
        let mut response = Self::new(status);
        response.extensions.insert(Head);
        response
    }

    pub fn no_content() -> Self {
        Self::new(StatusCode::NO_CONTENT)
    }

    fn with_body(body: impl Into<Bytes>, content_type: &'static str) -> Self {
        let mut res = Self::new(StatusCode::OK);
        res.body = body.into();
        res.headers
            .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
        res
    }

    /// Replaces the body, leaving headers untouched.
    pub fn with_body_bytes(mut self, body: impl Into<Bytes>) -> Self {
        self.body = body.into();
        self
    }

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

    /// Sets a header, replacing any existing value. Invalid names or values
    /// are dropped with a warning rather than panicking mid-request.
    pub fn with_header<K, V>(mut self, name: K, value: V) -> Self
    where
        K: TryInto<HeaderName>,
        V: TryInto<HeaderValue>,
    {
        match (name.try_into(), value.try_into()) {
            (Ok(name), Ok(value)) => {
                self.headers.insert(name, value);
            }
            _ => tracing::warn!("ignoring invalid response header"),
        }
        self
    }

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

    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.headers
    }

    pub fn header(&self, name: impl http::header::AsHeaderName) -> Option<&str> {
        self.headers.get(name).and_then(|v| v.to_str().ok())
    }

    /// Data attached for middleware further up the stack; never sent to
    /// the client.
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }

    pub fn body(&self) -> &Bytes {
        &self.body
    }

    /// This response for a conditional GET, as Rails' `stale?`/`fresh_when`:
    /// it gets `Last-Modified` and a weak `ETag` of its body, and becomes an
    /// empty `304 Not Modified` when the request's `If-None-Match` matches
    /// the ETag, or (without one) its `If-Modified-Since` isn't older than
    /// `last_modified`.
    ///
    /// ```ignore
    /// Response::json(&action).fresh_when(&ctx, action.updated_at.and_utc())
    /// ```
    pub fn fresh_when(
        mut self,
        ctx: &crate::Context,
        last_modified: chrono::DateTime<chrono::Utc>,
    ) -> Self {
        use sha2::Digest;
        let modified = last_modified
            .format("%a, %d %b %Y %H:%M:%S GMT")
            .to_string();
        let digest = sha2::Sha256::digest(&self.body);
        let etag = format!(
            "W/\"{}\"",
            digest[..16]
                .iter()
                .map(|b| format!("{b:02x}"))
                .collect::<String>()
        );
        let fresh = match ctx.header(header::IF_NONE_MATCH) {
            Some(tags) => tags.split(',').any(|tag| {
                // Weakly: `W/"x"` matches `"x"`, as RFC 9110 has it for GETs.
                let tag = tag.trim();
                tag == "*" || tag.trim_start_matches("W/") == etag.trim_start_matches("W/")
            }),
            None => ctx
                .header(header::IF_MODIFIED_SINCE)
                .and_then(crate::time::parse_http_date)
                .is_some_and(|since| since.timestamp() >= last_modified.timestamp()),
        };
        if let Ok(value) = HeaderValue::from_str(&modified) {
            self.headers.insert(header::LAST_MODIFIED, value);
        }
        if let Ok(value) = HeaderValue::from_str(&etag) {
            self.headers.insert(header::ETAG, value);
        }
        if fresh && self.status == StatusCode::OK {
            self.status = StatusCode::NOT_MODIFIED;
            self.body = Bytes::new();
            self.headers.remove(header::CONTENT_TYPE);
        }
        self
    }

    /// Whether this is a [`head`](Self::head) response, meant to be empty.
    pub fn is_head(&self) -> bool {
        self.extensions.get::<Head>().is_some()
    }

    /// The body decoded as UTF-8 (lossily). Mostly useful in tests.
    pub fn body_text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    /// The body parsed as JSON (`null` if it isn't). Mostly useful in
    /// tests: `res.body_json()["id"]`.
    pub fn body_json(&self) -> serde_json::Value {
        serde_json::from_slice(&self.body).unwrap_or_default()
    }

    pub(crate) fn into_http(self) -> http::Response<Full<Bytes>> {
        let mut res = http::Response::new(Full::new(self.body));
        *res.status_mut() = self.status;
        *res.headers_mut() = self.headers;
        res
    }
}

/// Anything a handler can return.
pub trait IntoResponse {
    fn into_response(self) -> Response;
}

static ESCAPE_HTML: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Writes `<`, `>`, `&`, U+2028 and U+2029 in JSON responses as `\u` escapes,
/// as Rails does by default (`escape_html_entities_in_json`), so JSON put
/// into a page can't close a `<script>`. Call it once at startup.
pub fn escape_html_entities_in_json(on: bool) {
    ESCAPE_HTML.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// The escaping itself. These characters only appear inside JSON strings,
/// so replacing them anywhere is safe.
fn escape_html(json: &[u8]) -> Vec<u8> {
    let text = String::from_utf8_lossy(json);
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '<' => out.push_str("\\u003c"),
            '>' => out.push_str("\\u003e"),
            '&' => out.push_str("\\u0026"),
            '\u{2028}' => out.push_str("\\u2028"),
            '\u{2029}' => out.push_str("\\u2029"),
            c => out.push(c),
        }
    }
    out.into_bytes()
}

#[cfg(test)]
mod escape_tests {
    #[test]
    fn escapes_as_rails_does() {
        let json = br#"{"url":"/a?b=1&c=<x>"}"#;
        assert_eq!(
            String::from_utf8(super::escape_html(json)).unwrap(),
            r#"{"url":"/a?b=1\u0026c=\u003cx\u003e"}"#
        );
    }
}

impl IntoResponse for Response {
    fn into_response(self) -> Response {
        self
    }
}

impl IntoResponse for &'static str {
    fn into_response(self) -> Response {
        Response::text(self)
    }
}

impl IntoResponse for String {
    fn into_response(self) -> Response {
        Response::text(self)
    }
}

impl IntoResponse for StatusCode {
    fn into_response(self) -> Response {
        Response::new(self)
    }
}

impl<R: IntoResponse> IntoResponse for (StatusCode, R) {
    fn into_response(self) -> Response {
        self.1.into_response().with_status(self.0)
    }
}

impl<R: IntoResponse, E: IntoResponse> IntoResponse for Result<R, E> {
    fn into_response(self) -> Response {
        match self {
            Ok(r) => r.into_response(),
            Err(e) => e.into_response(),
        }
    }
}

/// An HTML response body.
#[derive(Debug, Clone)]
pub struct Html<T>(pub T);

impl<T: Into<String>> IntoResponse for Html<T> {
    fn into_response(self) -> Response {
        Response::html(self.0)
    }
}

/// A JSON response body.
#[derive(Debug, Clone)]
pub struct Json<T>(pub T);

impl Json<()> {
    /// A JSON object to build field by field: `Json.object()` in
    /// `.glacier`, then `.field("name", value)`; see
    /// [`Object`](crate::serialize::Object).
    pub fn object() -> crate::serialize::Object {
        crate::serialize::Object::new()
    }
}

impl<T: Serialize> IntoResponse for Json<T> {
    fn into_response(self) -> Response {
        Response::json(&self.0)
    }
}

/// What an action may give back, as it is: a [`Response`] or anything that
/// becomes one, an [`Error`](crate::Error) (the request fails with it), or
/// a [`Result`](crate::Result) of either. In `.glacier`, `return error` and
/// an action's last value use it, so neither needs an `Ok(…)`.
pub trait Returned {
    /// As the action's `Result`.
    fn returned(self) -> crate::Result;
}

/// `x` as an action's `Result`; see [`Returned`].
#[doc(hidden)]
pub fn returned(value: impl Returned) -> crate::Result {
    value.returned()
}

impl<R: IntoResponse> Returned for crate::Result<R> {
    fn returned(self) -> crate::Result {
        self.map(IntoResponse::into_response)
    }
}

impl Returned for crate::Error {
    fn returned(self) -> crate::Result {
        Err(self)
    }
}

macro_rules! returned_as_response {
    ($($ty:ty),* $(,)?) => {$(
        impl Returned for $ty {
            fn returned(self) -> crate::Result {
                Ok(self.into_response())
            }
        }
    )*};
}

returned_as_response!(
    Response,
    &'static str,
    String,
    StatusCode,
    crate::view::Rendered
);

impl<R: IntoResponse> Returned for (StatusCode, R) {
    fn returned(self) -> crate::Result {
        Ok(self.into_response())
    }
}

impl<T: Into<String>> Returned for Html<T> {
    fn returned(self) -> crate::Result {
        Ok(self.into_response())
    }
}

impl<T: Serialize> Returned for Json<T> {
    fn returned(self) -> crate::Result {
        Ok(self.into_response())
    }
}

/// One `key: value` of `redirect!`: `status: :found` (a name, number or
/// [`StatusCode`]) sets the redirect's status, as Rails' `redirect_to …,
/// status: :found`; any other key is a flash (`notice: "Saved."`).
#[doc(hidden)]
pub trait RedirectOption {
    fn apply(self, key: &str, status: &mut StatusCode);
}

macro_rules! redirect_text {
    ($($ty:ty),*) => {$(
        impl RedirectOption for $ty {
            #[track_caller]
            fn apply(self, key: &str, status: &mut StatusCode) {
                if key == "status" {
                    *status = IntoStatus::into_status(AsRef::<str>::as_ref(&self));
                } else {
                    crate::request::put_flash(key, AsRef::<str>::as_ref(&self));
                }
            }
        }
    )*};
}
redirect_text!(&str, String, &String);

macro_rules! redirect_status {
    ($($ty:ty),*) => {$(
        impl RedirectOption for $ty {
            #[track_caller]
            fn apply(self, key: &str, status: &mut StatusCode) {
                assert!(key == "status", "a flash (`{key}:`) is text");
                *status = self.into_status();
            }
        }
    )*};
}
redirect_status!(StatusCode, u16, i32);

/// A response status from a number (`201`), a [`StatusCode`] or a
/// snake_case name (`"created"`, `"unprocessable_entity"`), for
/// `json!(…, status = …)` and `.glacier`'s `status: :created`.
pub trait IntoStatus {
    fn into_status(self) -> StatusCode;
}

impl IntoStatus for StatusCode {
    fn into_status(self) -> StatusCode {
        self
    }
}

impl IntoStatus for u16 {
    #[track_caller]
    fn into_status(self) -> StatusCode {
        StatusCode::from_u16(self).unwrap_or_else(|_| panic!("{self} isn't an HTTP status"))
    }
}

impl IntoStatus for i32 {
    #[track_caller]
    fn into_status(self) -> StatusCode {
        u16::try_from(self)
            .ok()
            .and_then(|code| StatusCode::from_u16(code).ok())
            .unwrap_or_else(|| panic!("{self} isn't an HTTP status"))
    }
}

impl IntoStatus for &str {
    /// # Panics
    ///
    /// On a name no status has, so a typo fails loudly.
    #[track_caller]
    fn into_status(self) -> StatusCode {
        status_named(self).unwrap_or_else(|| panic!("no HTTP status is called `:{self}`"))
    }
}

/// The snake_case name of a status: `see_other`, `unprocessable_entity`.
pub fn status_name(status: StatusCode) -> String {
    let reason = status.canonical_reason().unwrap_or(status.as_str());
    reason
        .to_ascii_lowercase()
        .replace(['-', '\''], "")
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|word| !word.is_empty())
        .collect::<Vec<_>>()
        .join("_")
}

/// The status with this snake_case name, if any.
pub fn status_named(name: &str) -> Option<StatusCode> {
    (100..600)
        .filter_map(|code| StatusCode::from_u16(code).ok())
        .find(|status| status_name(*status) == name)
}