Skip to main content

glacier/
serialize.rs

1//! Serializers: the JSON shape of a model, as active_model_serializers
2//! gives Rails apps.
3//!
4//! ```text
5//! serializer CountrySerializer do
6//!   attributes :id, :iso_code, :name
7//!   has_many :installations
8//! end
9//! ```
10//!
11//! compiles to a type implementing [`Serializer`]; a controller renders
12//! with `json countries, each_serializer: CountrySerializer, root:
13//! "countries"`. An association without a serializer of its own is written
14//! with all its columns ([`attributes`]), as Rails' `as_json` does. Values
15//! are written as Rails writes them: timestamps as
16//! `2024-01-02T10:00:00.000Z`.
17
18use serde::Serialize;
19use serde_json::{Map, Value as Json};
20
21use crate::db::{ToValue, Value};
22use crate::model::Model;
23use crate::response::{IntoStatus, Response};
24
25/// A model's JSON shape.
26pub trait Serializer {
27    type Model;
28
29    fn serialize(record: &Self::Model) -> Json;
30
31    /// The root key for one record: the model's name in snake case,
32    /// `country` for `Country`.
33    fn root() -> String {
34        let name = std::any::type_name::<Self::Model>();
35        let name = name.rsplit("::").next().unwrap_or(name);
36        glacier_inflect::snake_case(name)
37    }
38
39    /// The root key for many records: `countries`.
40    fn root_many() -> String {
41        glacier_inflect::pluralize(&Self::root())
42    }
43
44    /// One record.
45    fn one(record: &Self::Model) -> Json {
46        Self::serialize(record)
47    }
48
49    /// The JSON Schema of what [`one`](Self::one) writes, for OpenAPI.
50    /// `.glacier` serializers generate it; written by hand, a serializer
51    /// is any object unless it says more.
52    fn schema() -> Json {
53        serde_json::json!({"type": "object"})
54    }
55
56    /// Records as a JSON array.
57    fn many(records: &[Self::Model]) -> Json {
58        Json::Array(records.iter().map(Self::serialize).collect())
59    }
60}
61
62/// Every column of `record`, in column order: Rails' `as_json` for a model
63/// without a serializer, less its hidden ones (`Model::HIDDEN`).
64pub fn attributes<M: Model>(record: &M) -> Json {
65    let mut object = Map::new();
66    for (column, value) in record.values() {
67        if !M::HIDDEN.contains(&column) {
68            object.insert(column.to_owned(), value_json(&value));
69        }
70    }
71    Json::Object(object)
72}
73
74/// `{"<name>": value}`, for a response's root key.
75pub fn root(name: &str, value: Json) -> Json {
76    let mut object = Map::new();
77    object.insert(name.to_owned(), value);
78    Json::Object(object)
79}
80
81/// How serializers write timestamps.
82#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83pub enum TimeFormat {
84    /// `"2024-01-02T10:00:00.000Z"`, as Rails does by default.
85    Iso8601,
86    /// Seconds since 1970 (`1704189600`), as apps that override
87    /// `TimeWithZone#as_json` with `to_i` write them.
88    UnixSeconds,
89}
90
91static UNIX_SECONDS: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
92
93/// Sets how every serializer in the app writes timestamps; call it once at
94/// startup, as a Rails app's initializer would.
95pub fn set_time_format(format: TimeFormat) {
96    UNIX_SECONDS.store(
97        format == TimeFormat::UnixSeconds,
98        std::sync::atomic::Ordering::Relaxed,
99    );
100}
101
102fn time_format() -> TimeFormat {
103    if UNIX_SECONDS.load(std::sync::atomic::Ordering::Relaxed) {
104        TimeFormat::UnixSeconds
105    } else {
106        TimeFormat::Iso8601
107    }
108}
109
110/// A column value as Rails writes it in JSON.
111pub fn value_json(value: &Value) -> Json {
112    match value {
113        Value::Null => Json::Null,
114        Value::Bool(b) => Json::Bool(*b),
115        Value::Int(i) => Json::from(*i),
116        Value::Float(f) => serde_json::Number::from_f64(*f).map_or(Json::Null, Json::Number),
117        Value::Text(s) => Json::String(s.clone()),
118        Value::Bytes(b) => Json::String(String::from_utf8_lossy(b).into_owned()),
119        Value::Timestamp(t) => match time_format() {
120            TimeFormat::Iso8601 => Json::String(t.format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string()),
121            TimeFormat::UnixSeconds => Json::from(t.timestamp()),
122        },
123        // Rails writes a date as `2026-10-03` in either time format.
124        Value::Date(d) => Json::String(d.format("%Y-%m-%d").to_string()),
125        Value::Json(json) => json.clone(),
126        Value::Decimal(d) => Json::String(d.to_string()),
127        Value::Uuid(u) => Json::String(u.to_string()),
128        Value::List(items) => Json::Array(items.iter().map(value_json).collect()),
129    }
130}
131
132/// A JSON response with active_model_serializers' options, built by
133/// `json!(countries, each_serializer = CountrySerializer)`: the value as
134/// serde writes it, until a serializer is given.
135pub struct Render<'a, T: ?Sized> {
136    value: &'a T,
137    status: Option<http::StatusCode>,
138    root: Option<Root>,
139    page: Option<(crate::pagination::Page, u64)>,
140    headers: Vec<(String, String)>,
141}
142
143/// A response whose value has been through a serializer, wrapped in its
144/// root key unless `root = false`.
145pub struct Rendered {
146    json: Json,
147    status: Option<http::StatusCode>,
148    root: Option<String>,
149    page: Option<(crate::pagination::Page, u64)>,
150    headers: Vec<(String, String)>,
151}
152
153/// The `root` option: a key, or `false` for none.
154#[doc(hidden)]
155pub enum Root {
156    Key(String),
157    None,
158}
159
160#[doc(hidden)]
161pub trait IntoRoot {
162    fn into_root(self) -> Root;
163}
164
165impl IntoRoot for &str {
166    fn into_root(self) -> Root {
167        Root::Key(self.to_owned())
168    }
169}
170
171impl IntoRoot for String {
172    fn into_root(self) -> Root {
173        Root::Key(self)
174    }
175}
176
177impl IntoRoot for bool {
178    fn into_root(self) -> Root {
179        // `root = true` keeps the serializer's own root.
180        if self {
181            Root::Key(String::new())
182        } else {
183            Root::None
184        }
185    }
186}
187
188impl<'a, T: ?Sized> Render<'a, T> {
189    pub fn new(value: &'a T) -> Self {
190        Self {
191            value,
192            status: None,
193            root: None,
194            page: None,
195            headers: Vec::new(),
196        }
197    }
198
199    /// A response header: `json user, header: ("location", "/")`.
200    pub fn header(mut self, (name, value): (impl Into<String>, impl Into<String>)) -> Self {
201        self.headers.push((name.into(), value.into()));
202        self
203    }
204
205    /// The `Link` header to a cursor page's neighbours: `json
206    /// page.records, cursor: page`.
207    pub fn cursor<M>(mut self, page: &crate::pagination::Cursored<M>) -> Self {
208        self.headers
209            .extend(page.link().map(|link| ("link".to_owned(), link)));
210        self
211    }
212
213    /// api-pagination's headers for this page of `total` records.
214    pub fn paginate(mut self, (page, total): (crate::pagination::Page, impl TryInto<u64>)) -> Self {
215        self.page = Some((page, total.try_into().unwrap_or(0)));
216        self
217    }
218
219    pub fn status(mut self, status: impl IntoStatus) -> Self {
220        self.status = Some(status.into_status());
221        self
222    }
223
224    pub fn root(mut self, root: impl IntoRoot) -> Self {
225        self.root = Some(root.into_root());
226        self
227    }
228
229    /// Each record through `S`, under `S::root_many()`.
230    pub fn each_serializer<S: Serializer>(self, _: S) -> Rendered
231    where
232        T: AsRef<[S::Model]>,
233    {
234        let json = S::many(self.value.as_ref());
235        self.rendered(json, S::root_many())
236    }
237
238    /// The record through `S`, under `S::root()`.
239    pub fn serializer<S: Serializer>(self, _: S) -> Rendered
240    where
241        T: std::borrow::Borrow<S::Model>,
242    {
243        let json = S::one(self.value.borrow());
244        self.rendered(json, S::root())
245    }
246
247    fn rendered(self, json: Json, default_root: String) -> Rendered {
248        let root = match self.root {
249            None => Some(default_root),
250            Some(Root::Key(key)) if key.is_empty() => Some(default_root),
251            Some(Root::Key(key)) => Some(key),
252            Some(Root::None) => None,
253        };
254        Rendered {
255            json,
256            status: self.status,
257            root,
258            page: self.page,
259            headers: self.headers,
260        }
261    }
262
263    pub fn respond(self) -> crate::Result<Response>
264    where
265        T: Serialize,
266    {
267        let json = serde_json::to_value(self.value)?;
268        let json = match self.root {
269            Some(Root::Key(key)) if !key.is_empty() => root(&key, json),
270            _ => json,
271        };
272        Ok(respond(&json, self.status, self.page, self.headers))
273    }
274}
275
276impl Rendered {
277    /// A response header: `json user, serializer: UserSerializer, header:
278    /// ("location", "/")`.
279    pub fn header(mut self, (name, value): (impl Into<String>, impl Into<String>)) -> Self {
280        self.headers.push((name.into(), value.into()));
281        self
282    }
283
284    pub fn status(mut self, status: impl IntoStatus) -> Self {
285        self.status = Some(status.into_status());
286        self
287    }
288
289    pub fn paginate(mut self, (page, total): (crate::pagination::Page, impl TryInto<u64>)) -> Self {
290        self.page = Some((page, total.try_into().unwrap_or(0)));
291        self
292    }
293
294    pub fn cursor<M>(mut self, page: &crate::pagination::Cursored<M>) -> Self {
295        self.headers
296            .extend(page.link().map(|link| ("link".to_owned(), link)));
297        self
298    }
299
300    pub fn root(mut self, key: impl IntoRoot) -> Self {
301        match key.into_root() {
302            Root::Key(key) if key.is_empty() => {}
303            Root::Key(key) => self.root = Some(key),
304            Root::None => self.root = None,
305        }
306        self
307    }
308
309    pub fn respond(self) -> crate::Result<Response> {
310        let json = match self.root {
311            Some(key) => root(&key, self.json),
312            None => self.json,
313        };
314        Ok(respond(&json, self.status, self.page, self.headers))
315    }
316}
317
318fn respond(
319    json: &Json,
320    status: Option<http::StatusCode>,
321    page: Option<(crate::pagination::Page, u64)>,
322    headers: Vec<(String, String)>,
323) -> Response {
324    let mut response = Response::json(json);
325    for (name, value) in headers {
326        response = response.with_header(name, value);
327    }
328    if let Some(status) = status {
329        response = response.with_status(status);
330    }
331    match page {
332        Some((page, total)) => page.headers(total, response),
333        None => response,
334    }
335}
336
337/// A JSON object being built by a serializer, in insertion order; or, for
338/// [`Serializer::schema`], the schema of one.
339#[derive(Default)]
340pub struct Object(Map<String, Json>, bool, Vec<String>);
341
342impl Object {
343    pub fn new() -> Self {
344        Self::default()
345    }
346
347    /// An object collecting each field's schema instead of its value.
348    pub fn schema() -> Self {
349        Self(Map::new(), true, Vec::new())
350    }
351
352    /// The fields `add` writes, only when `keep` says so: a serializer's
353    /// `attribute :email, …, if: …`. In a schema they're there, but not
354    /// required.
355    #[doc(hidden)]
356    pub fn when(&mut self, keep: impl FnOnce() -> bool, add: impl FnOnce(&mut Self)) -> &mut Self {
357        if self.1 {
358            let before: Vec<String> = self.0.keys().cloned().collect();
359            add(self);
360            let added: Vec<String> = self
361                .0
362                .keys()
363                .filter(|k| !before.contains(k))
364                .cloned()
365                .collect();
366            self.2.extend(added);
367        } else if keep() {
368            add(self);
369        }
370        self
371    }
372
373    /// A field: its value from `value`, or in a schema its schema from
374    /// `schema`. The serializer macros call this.
375    #[doc(hidden)]
376    pub fn field(
377        &mut self,
378        name: &str,
379        value: impl FnOnce() -> Json,
380        schema: impl FnOnce() -> Json,
381    ) -> &mut Self {
382        let json = if self.1 { schema() } else { value() };
383        self.0.insert(name.to_owned(), json);
384        self
385    }
386
387    /// A column-like value, written as Rails writes it.
388    pub fn attr(&mut self, name: &str, value: &impl ToValue) -> &mut Self {
389        self.0
390            .insert(name.to_owned(), value_json(&value.to_value()));
391        self
392    }
393
394    /// Any serializable value, as serde writes it.
395    pub fn value(&mut self, name: &str, value: &impl Serialize) -> &mut Self {
396        let json = serde_json::to_value(value).unwrap_or(Json::Null);
397        self.0.insert(name.to_owned(), json);
398        self
399    }
400
401    /// An already built JSON value.
402    pub fn json(&mut self, name: &str, value: Json) -> &mut Self {
403        self.0.insert(name.to_owned(), value);
404        self
405    }
406
407    /// A loaded `has_many`, each record through `serialize`; `null` when it
408    /// wasn't preloaded.
409    pub fn many<M>(
410        &mut self,
411        name: &str,
412        records: Option<&[M]>,
413        serialize: impl Fn(&M) -> Json,
414    ) -> &mut Self {
415        let json = records.map_or(Json::Null, |records| {
416            Json::Array(records.iter().map(serialize).collect())
417        });
418        self.json(name, json)
419    }
420
421    /// A loaded `belongs_to` or `has_one` through `serialize`; `null` when
422    /// there's none or it wasn't preloaded.
423    pub fn one<M>(
424        &mut self,
425        name: &str,
426        record: Option<&M>,
427        serialize: impl Fn(&M) -> Json,
428    ) -> &mut Self {
429        let json = record.map_or(Json::Null, serialize);
430        self.json(name, json)
431    }
432
433    pub fn into_json(self) -> Json {
434        if self.1 {
435            let required: Vec<&String> = self.0.keys().filter(|k| !self.2.contains(k)).collect();
436            let required = serde_json::json!(required);
437            return serde_json::json!({
438                "type": "object",
439                "properties": Json::Object(self.0),
440                "required": required,
441            });
442        }
443        Json::Object(self.0)
444    }
445}
446
447/// A Rust type's JSON Schema, as Glacier writes its values: for OpenAPI.
448pub trait Schema {
449    fn schema() -> Json;
450}
451
452macro_rules! schema {
453    ($schema:tt: $($ty:ty),*) => {
454        $(impl Schema for $ty {
455            fn schema() -> Json {
456                serde_json::json!($schema)
457            }
458        })*
459    };
460}
461
462schema!({"type": "integer", "format": "int32"}: i8, i16, i32, u8, u16);
463schema!({"type": "integer", "format": "int64"}: i64, u32, u64, isize, usize);
464schema!({"type": "number"}: f32, f64);
465schema!({"type": "boolean"}: bool);
466schema!({"type": "string"}: String, str, char);
467schema!({"type": "string", "format": "decimal"}: crate::db::Decimal);
468schema!({"type": "string", "format": "date-time"}: crate::db::Timestamp, crate::db::NaiveTimestamp);
469schema!({"type": "string", "format": "date"}: crate::db::Date);
470schema!({"type": "string", "format": "uuid"}: crate::db::Uuid);
471schema!({}: Json);
472
473impl<T: Schema + ?Sized> Schema for &T {
474    fn schema() -> Json {
475        T::schema()
476    }
477}
478
479impl<T: Schema + ?Sized> Schema for Box<T> {
480    fn schema() -> Json {
481        T::schema()
482    }
483}
484
485impl<T: Schema> Schema for Option<T> {
486    fn schema() -> Json {
487        nullable(T::schema())
488    }
489}
490
491impl<T: Schema> Schema for Vec<T> {
492    fn schema() -> Json {
493        serde_json::json!({"type": "array", "items": T::schema()})
494    }
495}
496
497impl<T: Schema> Schema for [T] {
498    fn schema() -> Json {
499        serde_json::json!({"type": "array", "items": T::schema()})
500    }
501}
502
503/// `schema`, or `null`.
504pub fn nullable(schema: Json) -> Json {
505    match schema {
506        Json::Object(mut object) => match object.get("type").cloned() {
507            Some(Json::String(ty)) => {
508                object.insert("type".to_owned(), serde_json::json!([ty, "null"]));
509                Json::Object(object)
510            }
511            _ if object.is_empty() => Json::Object(object),
512            _ => serde_json::json!({"anyOf": [Json::Object(object), {"type": "null"}]}),
513        },
514        other => other,
515    }
516}
517
518/// The type of a value a closure would give, without calling it, for
519/// [`schema_of!`](crate::schema_of): `Schema` types give their schema,
520/// any other type `{}`.
521#[doc(hidden)]
522pub struct Probe<T>(std::marker::PhantomData<fn() -> T>);
523
524impl<T> Probe<T> {
525    pub fn of(_value: impl FnOnce() -> T) -> Self {
526        Self(std::marker::PhantomData)
527    }
528
529    pub fn new() -> Self {
530        Self(std::marker::PhantomData)
531    }
532}
533
534impl<T> Default for Probe<T> {
535    fn default() -> Self {
536        Self::new()
537    }
538}
539
540#[doc(hidden)]
541pub trait ProbeSchema {
542    fn schema(&self) -> Json;
543}
544
545impl<T: Schema> ProbeSchema for &Probe<T> {
546    fn schema(&self) -> Json {
547        T::schema()
548    }
549}
550
551#[doc(hidden)]
552pub trait ProbeAny {
553    fn schema(&self) -> Json;
554}
555
556impl<T> ProbeAny for Probe<T> {
557    fn schema(&self) -> Json {
558        serde_json::json!({})
559    }
560}
561
562/// A column-like value as JSON, as `Object::attr` writes it.
563#[doc(hidden)]
564pub fn attr_json(value: &impl ToValue) -> Json {
565    value_json(&value.to_value())
566}
567
568/// Any serializable value as JSON, as `Object::value` writes it.
569#[doc(hidden)]
570pub fn value_to_json(value: &impl Serialize) -> Json {
571    serde_json::to_value(value).unwrap_or(Json::Null)
572}
573
574/// A loaded association through `serialize`; `null` when not loaded.
575#[doc(hidden)]
576pub fn one_json<M>(record: Option<&M>, serialize: impl Fn(&M) -> Json) -> Json {
577    record.map_or(Json::Null, serialize)
578}
579
580/// Loaded records through `serialize`; `null` when not loaded.
581#[doc(hidden)]
582pub fn many_json<M>(records: Option<&[M]>, serialize: impl Fn(&M) -> Json) -> Json {
583    records.map_or(Json::Null, |records| {
584        Json::Array(records.iter().map(serialize).collect())
585    })
586}
587
588#[cfg(test)]
589mod tests {
590    use super::*;
591
592    #[test]
593    fn writes_values_as_rails_does() {
594        let at = chrono::NaiveDate::from_ymd_opt(2024, 1, 2)
595            .unwrap()
596            .and_hms_milli_opt(10, 0, 0, 5)
597            .unwrap()
598            .and_utc();
599        assert_eq!(
600            value_json(&Value::Timestamp(at)),
601            "2024-01-02T10:00:00.005Z"
602        );
603        let mut object = Object::new();
604        object
605            .attr("zeta", &1)
606            .attr("alpha", &Some("a".to_owned()))
607            .attr("none", &None::<i32>);
608        assert_eq!(
609            serde_json::to_string(&object.into_json()).unwrap(),
610            r#"{"zeta":1,"alpha":"a","none":null}"#,
611            "keys stay in the order written"
612        );
613        assert_eq!(
614            root("items", Json::Array(vec![])),
615            serde_json::json!({"items": []})
616        );
617    }
618
619    #[test]
620    fn root_keys_come_from_the_model_name() {
621        struct FaqSection;
622        struct FaqSectionSerializer;
623        impl Serializer for FaqSectionSerializer {
624            type Model = FaqSection;
625            fn serialize(_: &FaqSection) -> Json {
626                Json::Null
627            }
628        }
629        assert_eq!(FaqSectionSerializer::root(), "faq_section");
630        assert_eq!(FaqSectionSerializer::root_many(), "faq_sections");
631    }
632}