From d44fdc92ca95ecf15ce2d3f6c235e4218ce36e77 Mon Sep 17 00:00:00 2001 From: Jordan Rose Date: Fri, 9 Aug 2024 16:37:08 -0700 Subject: [PATCH] backup: Canonicalize Timestamps and Durations as milliseconds This is closer to the raw value used for most protobuf fields, and avoids printing as an object containing secs+nsecs. --- rust/message-backup/src/backup/time.rs | 31 +++++++++++++++++-- .../tests/res/canonical-backup.expected.json | 5 +-- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/rust/message-backup/src/backup/time.rs b/rust/message-backup/src/backup/time.rs index 9482ec77..c16f6f5f 100644 --- a/rust/message-backup/src/backup/time.rs +++ b/rust/message-backup/src/backup/time.rs @@ -6,10 +6,10 @@ use std::ops::Add; use std::time::{SystemTime, UNIX_EPOCH}; -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Timestamp(SystemTime); -#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] +#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] pub struct Duration(std::time::Duration); impl Timestamp { @@ -34,6 +34,19 @@ impl Timestamp { } } +impl serde::Serialize for Timestamp { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let offset = self + .0 + .duration_since(UNIX_EPOCH) + .expect("should not be possible to construct a Timestamp older than UNIX_EPOCH"); + serde::Serialize::serialize(&Duration(offset), serializer) + } +} + impl Duration { pub(super) const ZERO: Self = Self(std::time::Duration::ZERO); pub(super) const TWELVE_HOURS: Self = Self(std::time::Duration::from_secs(60 * 60 * 12)); @@ -43,6 +56,20 @@ impl Duration { } } +impl serde::Serialize for Duration { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + assert!( + self.0.as_millis() * 1_000_000 == self.0.as_nanos(), + "should not be possible to construct a Duration with sub-millisecond precision ({:?})", + self.0 + ); + self.0.as_millis().serialize(serializer) + } +} + impl Add for Timestamp { type Output = Timestamp; diff --git a/rust/message-backup/tests/res/canonical-backup.expected.json b/rust/message-backup/tests/res/canonical-backup.expected.json index a40ddddb..8988decf 100644 --- a/rust/message-backup/tests/res/canonical-backup.expected.json +++ b/rust/message-backup/tests/res/canonical-backup.expected.json @@ -31,10 +31,7 @@ "story_view_receipts_enabled": true, "has_seen_group_story_education_sheet": true, "has_completed_username_onboarding": true, - "universal_expire_timer": { - "secs": 3600, - "nanos": 0 - }, + "universal_expire_timer": 3600000, "preferred_reaction_emoji": [ "🏎️" ],