firestore 0.61.1

Library provides a simple API for Google Firestore and own Serde serializer based on efficient gRPC API
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
//! `#[serde(with = "...")]` attributes for storing a [`FirestoreInstant`] as a native Firestore
//! timestamp instead of the default string representation.
//!
//! Firestore keeps timestamps at microsecond precision and discards the nanoseconds on write, so
//! a `FirestoreInstant` carrying nanoseconds does not survive a round trip through these
//! attributes; [`FirestoreTimestamp`] truncates on construction instead and always round-trips.
//! All three attributes change the Firestore wire representation only - the field still
//! serializes as a string to JSON, so the same struct works for both.

use crate::FirestoreInstant;
use gcloud_sdk::google::firestore::v1::value;
use rvstruct::ValueStruct;
use serde::{Deserialize, Serialize, Serializer};

use crate::{
    errors::FirestoreSerializationError, timestamp_utils::to_timestamp, FirestoreError,
    FirestoreValue,
};

/// A wrapper around [`FirestoreInstant`](crate::FirestoreInstant) that is always serialized
/// as a Firestore timestamp value, without needing a `#[serde(with)]` attribute.
///
/// Use [`FirestoreInstant`](crate::FirestoreInstant) directly when you prefer the
/// attributes, and this wrapper when you would rather carry the behaviour in the type. It
/// still serializes as a string to JSON, so the same model can be reused for both JSON and
/// Firestore.
#[derive(
    Serialize, Deserialize, Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord, Default, ValueStruct,
)]
pub struct FirestoreTimestamp(pub FirestoreInstant);

impl FirestoreTimestamp {
    /// Returns the current instant, with the precision Firestore stores.
    #[inline]
    pub fn now() -> Self {
        FirestoreTimestamp(FirestoreInstant::now()).truncated_to_firestore_precision()
    }

    /// Truncates the value to the microsecond precision Firestore stores.
    ///
    /// Firestore keeps the timestamps with microsecond precision and discards
    /// the nanoseconds on write, so a value that carries them never comes back
    /// unchanged. Every constructor and conversion of this type truncates
    /// already; call this directly only for a value built through the public
    /// field.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use firestore::*;
    ///
    /// let exact = FirestoreTimestamp(
    ///     "2022-12-02T16:53:20.123456789Z".parse::<FirestoreInstant>().unwrap(),
    /// );
    ///
    /// assert_eq!(
    ///     exact.truncated_to_firestore_precision().to_string(),
    ///     "2022-12-02T16:53:20.123456Z"
    /// );
    /// ```
    #[inline]
    pub fn truncated_to_firestore_precision(self) -> Self {
        // Going through the protobuf representation keeps this correct for the
        // instants before the Unix epoch: it always carries a non negative
        // subsecond part, so dropping the sub microseconds rounds the value
        // down, the same way Firestore does.
        let ts = crate::timestamp_utils::to_timestamp(self.0);

        crate::timestamp_utils::from_timestamp(gcloud_sdk::prost_types::Timestamp {
            seconds: ts.seconds,
            nanos: (ts.nanos / 1_000) * 1_000,
        })
        .map(FirestoreTimestamp)
        .unwrap_or(self)
    }
}

impl std::fmt::Display for FirestoreTimestamp {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl std::str::FromStr for FirestoreTimestamp {
    type Err = crate::errors::FirestoreError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(FirestoreTimestamp(s.parse::<FirestoreInstant>()?).truncated_to_firestore_precision())
    }
}

impl From<FirestoreTimestamp> for FirestoreInstant {
    fn from(ts: FirestoreTimestamp) -> Self {
        ts.0
    }
}

/// Converting to a `SystemTime` is infallible, since every representable
/// timestamp fits into it.
impl From<FirestoreTimestamp> for std::time::SystemTime {
    fn from(ts: FirestoreTimestamp) -> Self {
        ts.0.into()
    }
}

/// Converting from a `SystemTime` is fallible, since it may be outside of the
/// range supported by Firestore timestamps.
impl TryFrom<std::time::SystemTime> for FirestoreTimestamp {
    type Error = crate::errors::FirestoreError;

    fn try_from(system_time: std::time::SystemTime) -> Result<Self, Self::Error> {
        Ok(FirestoreTimestamp(FirestoreInstant::try_from(system_time)?)
            .truncated_to_firestore_precision())
    }
}

/// Converts from a Google `prost_types::Timestamp`, as received from Firestore.
impl TryFrom<gcloud_sdk::prost_types::Timestamp> for FirestoreTimestamp {
    type Error = crate::errors::FirestoreError;

    fn try_from(ts: gcloud_sdk::prost_types::Timestamp) -> Result<Self, Self::Error> {
        Ok(
            FirestoreTimestamp(crate::timestamp_utils::from_timestamp(ts)?)
                .truncated_to_firestore_precision(),
        )
    }
}

/// Converts into a Google `prost_types::Timestamp`, as sent to Firestore.
impl From<FirestoreTimestamp> for gcloud_sdk::prost_types::Timestamp {
    fn from(ts: FirestoreTimestamp) -> Self {
        crate::timestamp_utils::to_timestamp(ts.0)
    }
}

pub(crate) const FIRESTORE_TS_TYPE_TAG_TYPE: &str = "FirestoreTimestamp";

pub(crate) const FIRESTORE_TS_NULL_TYPE_TAG_TYPE: &str = "FirestoreTimestampAsNull";

/// Stores a `FirestoreInstant` field as a native Firestore timestamp instead of a string.
///
/// ```rust
/// use firestore::{firestore_document_from_serializable, FirestoreInstant};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Event {
///     #[serde(with = "firestore::serialize_as_timestamp")]
///     created_at: FirestoreInstant,
/// }
///
/// let event = Event {
///     created_at: FirestoreInstant::now(),
/// };
/// let document = firestore_document_from_serializable("events/e1", &event).unwrap();
///
/// assert!(matches!(
///     document.fields["created_at"].value_type,
///     Some(gcloud_sdk::google::firestore::v1::value::ValueType::TimestampValue(_))
/// ));
/// ```
pub mod serialize_as_timestamp {
    use crate::FirestoreInstant;
    use serde::{Deserialize, Deserializer, Serializer};

    /// Serializes `ts` as a native Firestore timestamp.
    pub fn serialize<S>(ts: &FirestoreInstant, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_newtype_struct(crate::firestore_serde::FIRESTORE_TS_TYPE_TAG_TYPE, &ts)
    }

    /// Deserializes a Firestore timestamp or a timestamp string back into a [`FirestoreInstant`].
    pub fn deserialize<'de, D>(deserializer: D) -> Result<FirestoreInstant, D::Error>
    where
        D: Deserializer<'de>,
    {
        FirestoreInstant::deserialize(deserializer)
    }
}

/// Stores an `Option<FirestoreInstant>` field as a native Firestore timestamp when present.
///
/// `None` serializes as an absent field, the same as a plain `Option` with no attribute; pair
/// this with `#[serde(default)]` so a document that omits the field deserializes back to `None`
/// instead of failing. Use [`serialize_as_null_timestamp`] instead when `None` should write an
/// explicit Firestore null rather than leave the field out.
///
/// ```rust
/// use firestore::{firestore_document_from_serializable, FirestoreInstant};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Event {
///     #[serde(default)]
///     #[serde(with = "firestore::serialize_as_optional_timestamp")]
///     updated_at: Option<FirestoreInstant>,
/// }
///
/// let with_value = Event {
///     updated_at: Some(FirestoreInstant::now()),
/// };
/// let document = firestore_document_from_serializable("events/e1", &with_value).unwrap();
/// assert!(matches!(
///     document.fields["updated_at"].value_type,
///     Some(gcloud_sdk::google::firestore::v1::value::ValueType::TimestampValue(_))
/// ));
///
/// let without_value = Event { updated_at: None };
/// let document = firestore_document_from_serializable("events/e2", &without_value).unwrap();
/// assert!(!document.fields.contains_key("updated_at"));
/// ```
pub mod serialize_as_optional_timestamp {
    use crate::FirestoreInstant;
    use serde::{Deserialize, Deserializer, Serializer};

    /// Serializes `ts` as a native Firestore timestamp when `Some`, or omits the field.
    pub fn serialize<S>(ts: &Option<FirestoreInstant>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match ts {
            Some(v) => serializer
                .serialize_newtype_struct(crate::firestore_serde::FIRESTORE_TS_TYPE_TAG_TYPE, v),
            None => serializer.serialize_none(),
        }
    }

    /// Deserializes a Firestore timestamp, a timestamp string, or an absent field.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<FirestoreInstant>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Option::<FirestoreInstant>::deserialize(deserializer)
    }
}

/// Stores an `Option<FirestoreInstant>` field as a native Firestore timestamp when present, or
/// an explicit Firestore null when `None`.
///
/// By default `None` serializes as an absent field; use this instead of
/// [`serialize_as_optional_timestamp`] when the field must write a null value Firestore clients
/// can see and clear, rather than leave the field unsent. Pair it with `#[serde(default)]` so a
/// document that omits the field still deserializes.
///
/// ```rust
/// use firestore::{firestore_document_from_serializable, FirestoreInstant};
/// use serde::Serialize;
///
/// #[derive(Serialize)]
/// struct Event {
///     #[serde(default)]
///     #[serde(with = "firestore::serialize_as_null_timestamp")]
///     cleared_at: Option<FirestoreInstant>,
/// }
///
/// let event = Event { cleared_at: None };
/// let document = firestore_document_from_serializable("events/e1", &event).unwrap();
///
/// assert!(matches!(
///     document.fields["cleared_at"].value_type,
///     Some(gcloud_sdk::google::firestore::v1::value::ValueType::NullValue(_))
/// ));
/// ```
pub mod serialize_as_null_timestamp {
    use crate::FirestoreInstant;
    use serde::{Deserialize, Deserializer, Serializer};

    /// Serializes `ts` as a native Firestore timestamp when `Some`, or an explicit null.
    pub fn serialize<S>(ts: &Option<FirestoreInstant>, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer
            .serialize_newtype_struct(crate::firestore_serde::FIRESTORE_TS_NULL_TYPE_TAG_TYPE, ts)
    }

    /// Deserializes a Firestore timestamp, a timestamp string, or a null value.
    pub fn deserialize<'de, D>(deserializer: D) -> Result<Option<FirestoreInstant>, D::Error>
    where
        D: Deserializer<'de>,
    {
        Option::<FirestoreInstant>::deserialize(deserializer)
    }
}

/// Serializes `value` as a Firestore timestamp value, writing an explicit null for `None` when
/// `none_as_null` is set.
///
/// Called internally by the [`serialize_as_timestamp`] family once the newtype tag they attach
/// has been recognised; not meant to be called directly from a `#[serde(with = "...")]`
/// attribute.
///
/// Returns an error if `value` is not a string parseable as a [`FirestoreInstant`], or is a
/// shape other than a string, `Option`, unit, or newtype wrapper around one of those - the
/// serializers above only ever hand it one of the shapes it accepts.
pub fn serialize_timestamp_for_firestore<T: ?Sized + Serialize>(
    value: &T,
    none_as_null: bool,
) -> Result<FirestoreValue, FirestoreError> {
    struct TimestampSerializer {
        none_as_null: bool,
    }

    impl Serializer for TimestampSerializer {
        type Ok = FirestoreValue;
        type Error = FirestoreError;
        type SerializeSeq = crate::firestore_serde::serializer::SerializeVec;
        type SerializeTuple = crate::firestore_serde::serializer::SerializeVec;
        type SerializeTupleStruct = crate::firestore_serde::serializer::SerializeVec;
        type SerializeTupleVariant = crate::firestore_serde::serializer::SerializeTupleVariant;
        type SerializeMap = crate::firestore_serde::serializer::SerializeMap;
        type SerializeStruct = crate::firestore_serde::serializer::SerializeMap;
        type SerializeStructVariant = crate::firestore_serde::serializer::SerializeStructVariant;

        fn serialize_bool(self, _v: bool) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_i8(self, _v: i8) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_i16(self, _v: i16) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_i32(self, _v: i32) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_i64(self, _v: i64) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_u8(self, _v: u8) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_u16(self, _v: u16) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_u32(self, _v: u32) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_u64(self, _v: u64) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_f32(self, _v: f32) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_f64(self, _v: f64) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_char(self, _v: char) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
            let ts = v.parse::<FirestoreInstant>()?;
            Ok(FirestoreValue::from(
                gcloud_sdk::google::firestore::v1::Value {
                    value_type: Some(value::ValueType::TimestampValue(to_timestamp(ts))),
                },
            ))
        }

        fn serialize_bytes(self, _v: &[u8]) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
            if self.none_as_null {
                Ok(FirestoreValue::from(
                    gcloud_sdk::google::firestore::v1::Value {
                        value_type: Some(value::ValueType::NullValue(0)),
                    },
                ))
            } else {
                Ok(FirestoreValue::from(
                    gcloud_sdk::google::firestore::v1::Value { value_type: None },
                ))
            }
        }

        fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok, Self::Error> {
            value.serialize(self)
        }

        fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
            Ok(FirestoreValue::from(
                gcloud_sdk::google::firestore::v1::Value { value_type: None },
            ))
        }

        fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
            self.serialize_unit()
        }

        fn serialize_unit_variant(
            self,
            _name: &'static str,
            _variant_index: u32,
            variant: &'static str,
        ) -> Result<Self::Ok, Self::Error> {
            self.serialize_str(variant)
        }

        fn serialize_newtype_struct<T: ?Sized + Serialize>(
            self,
            _name: &'static str,
            value: &T,
        ) -> Result<Self::Ok, Self::Error> {
            value.serialize(self)
        }

        fn serialize_newtype_variant<T: ?Sized + Serialize>(
            self,
            _name: &'static str,
            _variant_index: u32,
            _variant: &'static str,
            _value: &T,
        ) -> Result<Self::Ok, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_tuple_struct(
            self,
            _name: &'static str,
            _len: usize,
        ) -> Result<Self::SerializeTupleStruct, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_tuple_variant(
            self,
            _name: &'static str,
            _variant_index: u32,
            _variant: &'static str,
            _len: usize,
        ) -> Result<Self::SerializeTupleVariant, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_struct(
            self,
            _name: &'static str,
            _len: usize,
        ) -> Result<Self::SerializeStruct, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }

        fn serialize_struct_variant(
            self,
            _name: &'static str,
            _variant_index: u32,
            _variant: &'static str,
            _len: usize,
        ) -> Result<Self::SerializeStructVariant, Self::Error> {
            Err(FirestoreError::SerializeError(
                FirestoreSerializationError::from_message(
                    "Timestamp serializer doesn't support this type",
                ),
            ))
        }
    }

    value.serialize(TimestampSerializer { none_as_null })
}

#[cfg(test)]
mod tests {
    use crate::{
        firestore_document_from_serializable, firestore_document_to_serializable, FirestoreInstant,
        FirestoreTimestamp,
    };
    use rvstruct::ValueStruct;
    use serde::{Deserialize, Serialize};

    #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
    struct TestStructure {
        #[serde(with = "crate::serialize_as_timestamp")]
        created_at: FirestoreInstant,
        #[serde(default)]
        #[serde(with = "crate::serialize_as_optional_timestamp")]
        updated_at: Option<FirestoreInstant>,
        wrapped_at: FirestoreTimestamp,
    }

    #[test]
    fn test_timestamp_serde_roundtrip() {
        let created_at: FirestoreInstant = "2022-12-02T16:53:20.123456789Z".parse().unwrap();
        let wrapped_at: FirestoreInstant = "2018-01-01T00:00:00Z".parse().unwrap();

        let test_structure = TestStructure {
            created_at,
            updated_at: Some(created_at),
            wrapped_at: FirestoreTimestamp(wrapped_at),
        };

        let document =
            firestore_document_from_serializable("test/doc-id", &test_structure).unwrap();

        // The timestamps must land as Firestore timestamp values, not as strings
        assert!(matches!(
            document.fields["created_at"].value_type,
            Some(gcloud_sdk::google::firestore::v1::value::ValueType::TimestampValue(_))
        ));

        let deserialized: TestStructure =
            firestore_document_to_serializable(&document).expect("Unable to deserialize");

        assert_eq!(deserialized, test_structure);
        // Firestore timestamps keep nanosecond precision
        assert_eq!(deserialized.created_at.subsec_nanosecond(), 123_456_789);
    }

    #[test]
    fn test_firestore_precision_truncation() {
        use std::str::FromStr;
        use std::time::{Duration, SystemTime, UNIX_EPOCH};

        // Firestore keeps microseconds, so the nanoseconds are dropped
        assert_eq!(
            FirestoreTimestamp::from_str("2022-12-02T16:53:20.123456789Z")
                .unwrap()
                .to_string(),
            "2022-12-02T16:53:20.123456Z"
        );

        // Rounding down, not towards zero, so that the instants before the Unix
        // epoch truncate the same way Firestore does
        assert_eq!(
            FirestoreTimestamp::from_str("1969-12-31T23:59:59.542758875Z")
                .unwrap()
                .to_string(),
            "1969-12-31T23:59:59.542758Z"
        );

        // Every constructor and conversion applies it
        let from_system_time: FirestoreTimestamp = (UNIX_EPOCH + Duration::new(1, 542_758_875))
            .try_into()
            .unwrap();
        assert_eq!(from_system_time.to_string(), "1970-01-01T00:00:01.542758Z");

        let from_proto: FirestoreTimestamp = gcloud_sdk::prost_types::Timestamp {
            seconds: 1,
            nanos: 542_758_875,
        }
        .try_into()
        .unwrap();
        assert_eq!(from_proto.to_string(), "1970-01-01T00:00:01.542758Z");

        assert_eq!(FirestoreTimestamp::now().0.subsec_nanosecond() % 1_000, 0);

        // Truncating is idempotent, and a value already at that precision is left alone
        let already_truncated =
            FirestoreTimestamp::from_str("2022-12-02T16:53:20.123456Z").unwrap();
        assert_eq!(
            already_truncated.truncated_to_firestore_precision(),
            already_truncated
        );

        // The public field stays an exact escape hatch
        let exact = FirestoreTimestamp(
            FirestoreInstant::from_str("2022-12-02T16:53:20.123456789Z").unwrap(),
        );
        assert_eq!(exact.0.subsec_nanosecond(), 123_456_789);

        let _ = SystemTime::from(exact);
    }

    #[test]
    fn test_timestamp_conversions() {
        use std::str::FromStr;
        use std::time::SystemTime;

        // Already at the precision Firestore stores, so nothing is truncated here
        let ts = FirestoreTimestamp::from_str("2022-12-02T16:53:20.123456Z").unwrap();

        // Display round trips through FromStr
        assert_eq!(FirestoreTimestamp::from_str(&ts.to_string()).unwrap(), ts);

        // SystemTime, infallible one way and fallible back
        let system_time: SystemTime = ts.into();
        assert_eq!(FirestoreTimestamp::try_from(system_time).unwrap(), ts);

        // Google protobuf timestamps
        let proto: gcloud_sdk::prost_types::Timestamp = ts.into();
        assert_eq!(proto.seconds, 1670000000);
        assert_eq!(proto.nanos, 123_456_000);
        assert_eq!(FirestoreTimestamp::try_from(proto).unwrap(), ts);

        // The inner instant, both ways
        let instant: FirestoreInstant = ts.into();
        assert_eq!(FirestoreTimestamp::from(instant), ts);
        assert_eq!(ts.value(), &instant);

        assert_eq!(
            FirestoreTimestamp::try_from(SystemTime::UNIX_EPOCH).unwrap(),
            FirestoreTimestamp::default()
        );
    }

    /// Mirrors the structure used by `examples/timestamp.rs`, so that all the
    /// documented ways of writing a Firestore timestamp stay verified.
    #[test]
    fn test_all_documented_timestamp_forms() {
        use gcloud_sdk::google::firestore::v1::value::ValueType;
        use std::time::SystemTime;

        #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
        struct ExampleStructure {
            some_id: String,
            created_at_system_time: std::time::SystemTime,
            created_at: FirestoreTimestamp,
            updated_at: Option<FirestoreTimestamp>,
            updated_at_always_none: Option<FirestoreTimestamp>,
            #[serde(with = "crate::serialize_as_timestamp")]
            created_at_attr: FirestoreInstant,
            #[serde(default)]
            #[serde(with = "crate::serialize_as_optional_timestamp")]
            updated_at_attr: Option<FirestoreInstant>,
            #[serde(default)]
            #[serde(with = "crate::serialize_as_optional_timestamp")]
            updated_at_attr_always_none: Option<FirestoreInstant>,
        }

        let from_system_time: FirestoreTimestamp = SystemTime::now().try_into().unwrap();

        let example = ExampleStructure {
            some_id: "test-1".to_string(),
            created_at_system_time: std::time::SystemTime::now(),
            created_at: FirestoreTimestamp::now(),
            updated_at: Some(from_system_time),
            updated_at_always_none: None,
            created_at_attr: FirestoreInstant::now(),
            updated_at_attr: Some(FirestoreInstant::now()),
            updated_at_attr_always_none: None,
        };

        let document = firestore_document_from_serializable("test/doc-id", &example).unwrap();

        // Every populated form must land as a Firestore timestamp value, not a string
        for field in [
            "created_at",
            "updated_at",
            "created_at_attr",
            "updated_at_attr",
        ] {
            assert!(
                matches!(
                    document.fields[field].value_type,
                    Some(ValueType::TimestampValue(_))
                ),
                "{field} must serialize as a Firestore timestamp"
            );
        }

        let deserialized: ExampleStructure =
            firestore_document_to_serializable(&document).expect("Unable to deserialize");
        assert_eq!(deserialized, example);
    }

    #[test]
    fn test_optional_timestamp_none_roundtrip() {
        let created_at: FirestoreInstant = "2022-12-02T16:53:20Z".parse().unwrap();

        let test_structure = TestStructure {
            created_at,
            updated_at: None,
            wrapped_at: FirestoreTimestamp(created_at),
        };

        let document =
            firestore_document_from_serializable("test/doc-id", &test_structure).unwrap();

        let deserialized: TestStructure =
            firestore_document_to_serializable(&document).expect("Unable to deserialize");

        assert_eq!(deserialized, test_structure);
    }
}