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
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
//! Serializers: the JSON shape of a model, as active_model_serializers
//! gives Rails apps.
//!
//! ```text
//! serializer CountrySerializer do
//!   attributes :id, :iso_code, :name
//!   has_many :installations
//! end
//! ```
//!
//! compiles to a type implementing [`Serializer`]; a controller renders
//! with `json countries, each_serializer: CountrySerializer, root:
//! "countries"`. An association without a serializer of its own is written
//! with all its columns ([`attributes`]), as Rails' `as_json` does. Values
//! are written as Rails writes them: timestamps as
//! `2024-01-02T10:00:00.000Z`.

use serde::Serialize;
use serde_json::{Map, Value as Json};

use crate::db::{ToValue, Value};
use crate::model::Model;
use crate::response::{IntoStatus, Response};

/// A model's JSON shape.
pub trait Serializer {
    type Model;

    fn serialize(record: &Self::Model) -> Json;

    /// The root key for one record: the model's name in snake case,
    /// `country` for `Country`.
    fn root() -> String {
        let name = std::any::type_name::<Self::Model>();
        let name = name.rsplit("::").next().unwrap_or(name);
        glacier_inflect::snake_case(name)
    }

    /// The root key for many records: `countries`.
    fn root_many() -> String {
        glacier_inflect::pluralize(&Self::root())
    }

    /// One record.
    fn one(record: &Self::Model) -> Json {
        Self::serialize(record)
    }

    /// The JSON Schema of what [`one`](Self::one) writes, for OpenAPI.
    /// `.glacier` serializers generate it; written by hand, a serializer
    /// is any object unless it says more.
    fn schema() -> Json {
        serde_json::json!({"type": "object"})
    }

    /// Records as a JSON array.
    fn many(records: &[Self::Model]) -> Json {
        Json::Array(records.iter().map(Self::serialize).collect())
    }
}

/// Every column of `record`, in column order: Rails' `as_json` for a model
/// without a serializer, less its hidden ones (`Model::HIDDEN`).
pub fn attributes<M: Model>(record: &M) -> Json {
    let mut object = Map::new();
    for (column, value) in record.values() {
        if !M::HIDDEN.contains(&column) {
            object.insert(column.to_owned(), value_json(&value));
        }
    }
    Json::Object(object)
}

/// `{"<name>": value}`, for a response's root key.
pub fn root(name: &str, value: Json) -> Json {
    let mut object = Map::new();
    object.insert(name.to_owned(), value);
    Json::Object(object)
}

/// How serializers write timestamps.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TimeFormat {
    /// `"2024-01-02T10:00:00.000Z"`, as Rails does by default.
    Iso8601,
    /// Seconds since 1970 (`1704189600`), as apps that override
    /// `TimeWithZone#as_json` with `to_i` write them.
    UnixSeconds,
}

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

/// Sets how every serializer in the app writes timestamps; call it once at
/// startup, as a Rails app's initializer would.
pub fn set_time_format(format: TimeFormat) {
    UNIX_SECONDS.store(
        format == TimeFormat::UnixSeconds,
        std::sync::atomic::Ordering::Relaxed,
    );
}

fn time_format() -> TimeFormat {
    if UNIX_SECONDS.load(std::sync::atomic::Ordering::Relaxed) {
        TimeFormat::UnixSeconds
    } else {
        TimeFormat::Iso8601
    }
}

/// A column value as Rails writes it in JSON.
pub fn value_json(value: &Value) -> Json {
    match value {
        Value::Null => Json::Null,
        Value::Bool(b) => Json::Bool(*b),
        Value::Int(i) => Json::from(*i),
        Value::Float(f) => serde_json::Number::from_f64(*f).map_or(Json::Null, Json::Number),
        Value::Text(s) => Json::String(s.clone()),
        Value::Bytes(b) => Json::String(String::from_utf8_lossy(b).into_owned()),
        Value::Timestamp(t) => match time_format() {
            TimeFormat::Iso8601 => Json::String(t.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()),
            TimeFormat::UnixSeconds => Json::from(t.timestamp()),
        },
        // Rails writes a date as `2026-10-03` in either time format.
        Value::Date(d) => Json::String(d.format("%Y-%m-%d").to_string()),
        Value::Json(json) => json.clone(),
        Value::Decimal(d) => Json::String(d.to_string()),
        Value::Uuid(u) => Json::String(u.to_string()),
        Value::List(items) => Json::Array(items.iter().map(value_json).collect()),
    }
}

/// A JSON response with active_model_serializers' options, built by
/// `json!(countries, each_serializer = CountrySerializer)`: the value as
/// serde writes it, until a serializer is given.
pub struct Render<'a, T: ?Sized> {
    value: &'a T,
    status: Option<http::StatusCode>,
    root: Option<Root>,
    page: Option<(crate::pagination::Page, u64)>,
    headers: Vec<(String, String)>,
}

/// A response whose value has been through a serializer, wrapped in its
/// root key unless `root = false`.
pub struct Rendered {
    json: Json,
    status: Option<http::StatusCode>,
    root: Option<String>,
    page: Option<(crate::pagination::Page, u64)>,
    headers: Vec<(String, String)>,
}

/// The `root` option: a key, or `false` for none.
#[doc(hidden)]
pub enum Root {
    Key(String),
    None,
}

#[doc(hidden)]
pub trait IntoRoot {
    fn into_root(self) -> Root;
}

impl IntoRoot for &str {
    fn into_root(self) -> Root {
        Root::Key(self.to_owned())
    }
}

impl IntoRoot for String {
    fn into_root(self) -> Root {
        Root::Key(self)
    }
}

impl IntoRoot for bool {
    fn into_root(self) -> Root {
        // `root = true` keeps the serializer's own root.
        if self {
            Root::Key(String::new())
        } else {
            Root::None
        }
    }
}

impl<'a, T: ?Sized> Render<'a, T> {
    pub fn new(value: &'a T) -> Self {
        Self {
            value,
            status: None,
            root: None,
            page: None,
            headers: Vec::new(),
        }
    }

    /// A response header: `json user, header: ("location", "/")`.
    pub fn header(mut self, (name, value): (impl Into<String>, impl Into<String>)) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    /// The `Link` header to a cursor page's neighbours: `json
    /// page.records, cursor: page`.
    pub fn cursor<M>(mut self, page: &crate::pagination::Cursored<M>) -> Self {
        self.headers
            .extend(page.link().map(|link| ("link".to_owned(), link)));
        self
    }

    /// api-pagination's headers for this page of `total` records.
    pub fn paginate(mut self, (page, total): (crate::pagination::Page, impl TryInto<u64>)) -> Self {
        self.page = Some((page, total.try_into().unwrap_or(0)));
        self
    }

    pub fn status(mut self, status: impl IntoStatus) -> Self {
        self.status = Some(status.into_status());
        self
    }

    pub fn root(mut self, root: impl IntoRoot) -> Self {
        self.root = Some(root.into_root());
        self
    }

    /// Each record through `S`, under `S::root_many()`.
    pub fn each_serializer<S: Serializer>(self, _: S) -> Rendered
    where
        T: AsRef<[S::Model]>,
    {
        let json = S::many(self.value.as_ref());
        self.rendered(json, S::root_many())
    }

    /// The record through `S`, under `S::root()`.
    pub fn serializer<S: Serializer>(self, _: S) -> Rendered
    where
        T: std::borrow::Borrow<S::Model>,
    {
        let json = S::one(self.value.borrow());
        self.rendered(json, S::root())
    }

    fn rendered(self, json: Json, default_root: String) -> Rendered {
        let root = match self.root {
            None => Some(default_root),
            Some(Root::Key(key)) if key.is_empty() => Some(default_root),
            Some(Root::Key(key)) => Some(key),
            Some(Root::None) => None,
        };
        Rendered {
            json,
            status: self.status,
            root,
            page: self.page,
            headers: self.headers,
        }
    }

    pub fn respond(self) -> crate::Result<Response>
    where
        T: Serialize,
    {
        let json = serde_json::to_value(self.value)?;
        let json = match self.root {
            Some(Root::Key(key)) if !key.is_empty() => root(&key, json),
            _ => json,
        };
        Ok(respond(&json, self.status, self.page, self.headers))
    }
}

impl Rendered {
    /// A response header: `json user, serializer: UserSerializer, header:
    /// ("location", "/")`.
    pub fn header(mut self, (name, value): (impl Into<String>, impl Into<String>)) -> Self {
        self.headers.push((name.into(), value.into()));
        self
    }

    pub fn status(mut self, status: impl IntoStatus) -> Self {
        self.status = Some(status.into_status());
        self
    }

    pub fn paginate(mut self, (page, total): (crate::pagination::Page, impl TryInto<u64>)) -> Self {
        self.page = Some((page, total.try_into().unwrap_or(0)));
        self
    }

    pub fn cursor<M>(mut self, page: &crate::pagination::Cursored<M>) -> Self {
        self.headers
            .extend(page.link().map(|link| ("link".to_owned(), link)));
        self
    }

    pub fn root(mut self, key: impl IntoRoot) -> Self {
        match key.into_root() {
            Root::Key(key) if key.is_empty() => {}
            Root::Key(key) => self.root = Some(key),
            Root::None => self.root = None,
        }
        self
    }

    pub fn respond(self) -> crate::Result<Response> {
        let json = match self.root {
            Some(key) => root(&key, self.json),
            None => self.json,
        };
        Ok(respond(&json, self.status, self.page, self.headers))
    }
}

fn respond(
    json: &Json,
    status: Option<http::StatusCode>,
    page: Option<(crate::pagination::Page, u64)>,
    headers: Vec<(String, String)>,
) -> Response {
    let mut response = Response::json(json);
    for (name, value) in headers {
        response = response.with_header(name, value);
    }
    if let Some(status) = status {
        response = response.with_status(status);
    }
    match page {
        Some((page, total)) => page.headers(total, response),
        None => response,
    }
}

/// A JSON object being built by a serializer, in insertion order; or, for
/// [`Serializer::schema`], the schema of one.
#[derive(Default)]
pub struct Object(Map<String, Json>, bool);

impl Object {
    pub fn new() -> Self {
        Self::default()
    }

    /// An object collecting each field's schema instead of its value.
    pub fn schema() -> Self {
        Self(Map::new(), true)
    }

    /// A field: its value from `value`, or in a schema its schema from
    /// `schema`. The serializer macros call this.
    #[doc(hidden)]
    pub fn field(
        &mut self,
        name: &str,
        value: impl FnOnce() -> Json,
        schema: impl FnOnce() -> Json,
    ) -> &mut Self {
        let json = if self.1 { schema() } else { value() };
        self.0.insert(name.to_owned(), json);
        self
    }

    /// A column-like value, written as Rails writes it.
    pub fn attr(&mut self, name: &str, value: &impl ToValue) -> &mut Self {
        self.0
            .insert(name.to_owned(), value_json(&value.to_value()));
        self
    }

    /// Any serializable value, as serde writes it.
    pub fn value(&mut self, name: &str, value: &impl Serialize) -> &mut Self {
        let json = serde_json::to_value(value).unwrap_or(Json::Null);
        self.0.insert(name.to_owned(), json);
        self
    }

    /// An already built JSON value.
    pub fn json(&mut self, name: &str, value: Json) -> &mut Self {
        self.0.insert(name.to_owned(), value);
        self
    }

    /// A loaded `has_many`, each record through `serialize`; `null` when it
    /// wasn't preloaded.
    pub fn many<M>(
        &mut self,
        name: &str,
        records: Option<&[M]>,
        serialize: impl Fn(&M) -> Json,
    ) -> &mut Self {
        let json = records.map_or(Json::Null, |records| {
            Json::Array(records.iter().map(serialize).collect())
        });
        self.json(name, json)
    }

    /// A loaded `belongs_to` or `has_one` through `serialize`; `null` when
    /// there's none or it wasn't preloaded.
    pub fn one<M>(
        &mut self,
        name: &str,
        record: Option<&M>,
        serialize: impl Fn(&M) -> Json,
    ) -> &mut Self {
        let json = record.map_or(Json::Null, serialize);
        self.json(name, json)
    }

    pub fn into_json(self) -> Json {
        if self.1 {
            let required: Vec<&String> = self.0.keys().collect();
            let required = serde_json::json!(required);
            return serde_json::json!({
                "type": "object",
                "properties": Json::Object(self.0),
                "required": required,
            });
        }
        Json::Object(self.0)
    }
}

/// A Rust type's JSON Schema, as Glacier writes its values: for OpenAPI.
pub trait Schema {
    fn schema() -> Json;
}

macro_rules! schema {
    ($schema:tt: $($ty:ty),*) => {
        $(impl Schema for $ty {
            fn schema() -> Json {
                serde_json::json!($schema)
            }
        })*
    };
}

schema!({"type": "integer", "format": "int32"}: i8, i16, i32, u8, u16);
schema!({"type": "integer", "format": "int64"}: i64, u32, u64, isize, usize);
schema!({"type": "number"}: f32, f64);
schema!({"type": "boolean"}: bool);
schema!({"type": "string"}: String, str, char);
schema!({"type": "string", "format": "decimal"}: crate::db::Decimal);
schema!({"type": "string", "format": "date-time"}: crate::db::Timestamp, crate::db::NaiveTimestamp);
schema!({"type": "string", "format": "date"}: crate::db::Date);
schema!({"type": "string", "format": "uuid"}: crate::db::Uuid);
schema!({}: Json);

impl<T: Schema + ?Sized> Schema for &T {
    fn schema() -> Json {
        T::schema()
    }
}

impl<T: Schema + ?Sized> Schema for Box<T> {
    fn schema() -> Json {
        T::schema()
    }
}

impl<T: Schema> Schema for Option<T> {
    fn schema() -> Json {
        nullable(T::schema())
    }
}

impl<T: Schema> Schema for Vec<T> {
    fn schema() -> Json {
        serde_json::json!({"type": "array", "items": T::schema()})
    }
}

impl<T: Schema> Schema for [T] {
    fn schema() -> Json {
        serde_json::json!({"type": "array", "items": T::schema()})
    }
}

/// `schema`, or `null`.
pub fn nullable(schema: Json) -> Json {
    match schema {
        Json::Object(mut object) => match object.get("type").cloned() {
            Some(Json::String(ty)) => {
                object.insert("type".to_owned(), serde_json::json!([ty, "null"]));
                Json::Object(object)
            }
            _ if object.is_empty() => Json::Object(object),
            _ => serde_json::json!({"anyOf": [Json::Object(object), {"type": "null"}]}),
        },
        other => other,
    }
}

/// The type of a value a closure would give, without calling it, for
/// [`schema_of!`](crate::schema_of): `Schema` types give their schema,
/// any other type `{}`.
#[doc(hidden)]
pub struct Probe<T>(std::marker::PhantomData<fn() -> T>);

impl<T> Probe<T> {
    pub fn of(_value: impl FnOnce() -> T) -> Self {
        Self(std::marker::PhantomData)
    }

    pub fn new() -> Self {
        Self(std::marker::PhantomData)
    }
}

impl<T> Default for Probe<T> {
    fn default() -> Self {
        Self::new()
    }
}

#[doc(hidden)]
pub trait ProbeSchema {
    fn schema(&self) -> Json;
}

impl<T: Schema> ProbeSchema for &Probe<T> {
    fn schema(&self) -> Json {
        T::schema()
    }
}

#[doc(hidden)]
pub trait ProbeAny {
    fn schema(&self) -> Json;
}

impl<T> ProbeAny for Probe<T> {
    fn schema(&self) -> Json {
        serde_json::json!({})
    }
}

/// A column-like value as JSON, as `Object::attr` writes it.
#[doc(hidden)]
pub fn attr_json(value: &impl ToValue) -> Json {
    value_json(&value.to_value())
}

/// Any serializable value as JSON, as `Object::value` writes it.
#[doc(hidden)]
pub fn value_to_json(value: &impl Serialize) -> Json {
    serde_json::to_value(value).unwrap_or(Json::Null)
}

/// A loaded association through `serialize`; `null` when not loaded.
#[doc(hidden)]
pub fn one_json<M>(record: Option<&M>, serialize: impl Fn(&M) -> Json) -> Json {
    record.map_or(Json::Null, serialize)
}

/// Loaded records through `serialize`; `null` when not loaded.
#[doc(hidden)]
pub fn many_json<M>(records: Option<&[M]>, serialize: impl Fn(&M) -> Json) -> Json {
    records.map_or(Json::Null, |records| {
        Json::Array(records.iter().map(serialize).collect())
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn writes_values_as_rails_does() {
        let at = chrono::NaiveDate::from_ymd_opt(2024, 1, 2)
            .unwrap()
            .and_hms_milli_opt(10, 0, 0, 5)
            .unwrap()
            .and_utc();
        assert_eq!(
            value_json(&Value::Timestamp(at)),
            "2024-01-02T10:00:00.005Z"
        );
        let mut object = Object::new();
        object
            .attr("zeta", &1)
            .attr("alpha", &Some("a".to_owned()))
            .attr("none", &None::<i32>);
        assert_eq!(
            serde_json::to_string(&object.into_json()).unwrap(),
            r#"{"zeta":1,"alpha":"a","none":null}"#,
            "keys stay in the order written"
        );
        assert_eq!(
            root("items", Json::Array(vec![])),
            serde_json::json!({"items": []})
        );
    }

    #[test]
    fn root_keys_come_from_the_model_name() {
        struct FaqSection;
        struct FaqSectionSerializer;
        impl Serializer for FaqSectionSerializer {
            type Model = FaqSection;
            fn serialize(_: &FaqSection) -> Json {
                Json::Null
            }
        }
        assert_eq!(FaqSectionSerializer::root(), "faq_section");
        assert_eq!(FaqSectionSerializer::root_many(), "faq_sections");
    }
}