Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 101 additions & 18 deletions lambda-events/src/encodings/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,9 +108,10 @@ where
{
let (whole, frac) = normalize_timestamp(deserializer)?;
assert_eq!(frac, 0);
let seconds: f64 = whole as f64 / 1000.0;
let milliseconds: u32 = (seconds.fract() * 1000f64) as u32;
let nanos = milliseconds * 1_000_000;
// Stay in integers: going through `whole as f64 / 1000.0` and back
// drops a millisecond whenever the quotient is not exact in binary.
let seconds = whole / 1000;
let nanos = (whole % 1000) as u32 * 1_000_000;
Utc.timestamp_opt(seconds as i64, nanos)
.latest()
.ok_or_else(|| D::Error::custom("invalid timestamp"))
Expand All @@ -136,10 +137,8 @@ fn deserialize_seconds<'de, D>(deserializer: D) -> Result<DateTime<Utc>, D::Erro
where
D: Deserializer<'de>,
{
let (whole, frac) = normalize_timestamp(deserializer)?;
let seconds = whole;
let nanos = frac * 1_000_000;
Utc.timestamp_opt(seconds as i64, nanos as u32)
let (seconds, nanos) = normalize_timestamp(deserializer)?;
Utc.timestamp_opt(seconds as i64, nanos)
.latest()
.ok_or_else(|| D::Error::custom("invalid timestamp"))
}
Expand Down Expand Up @@ -180,7 +179,12 @@ where
.ok_or_else(|| D::Error::custom(format!("invalid time delta minutes `{minutes}`")))
}

fn normalize_timestamp<'de, D>(deserializer: D) -> Result<(u64, u64), D::Error>
/// Splits a timestamp into its whole part and its fraction.
///
/// The fraction is returned in billionths of a unit, so that the position of
/// each digit is kept: `.5` is `500_000_000`, `.05` is `50_000_000` and `.477`
/// is `477_000_000`. Digits past the ninth are dropped.
fn normalize_timestamp<'de, D>(deserializer: D) -> Result<(u64, u32), D::Error>
where
D: Deserializer<'de>,
{
Expand All @@ -200,16 +204,11 @@ where

// We need to do this due to floating point issues.
let input_as_string = input.to_string();
let parts: Result<Vec<u64>, _> = input_as_string
.split('.')
.map(|x| x.parse::<u64>().map_err(DeError::custom))
.collect();
let parts = parts?;
if parts.len() > 1 {
Ok((parts[0], parts[1]))
} else {
Ok((parts[0], 0))
}
let (whole, frac) = input_as_string.split_once('.').unwrap_or((&input_as_string, ""));
let whole = whole.parse::<u64>().map_err(DeError::custom)?;
// Pad on the right so that the digits keep their decimal place.
let frac = format!("{frac:0<9.9}").parse::<u32>().map_err(DeError::custom)?;
Ok((whole, frac))
}

#[cfg(test)]
Expand Down Expand Up @@ -244,6 +243,90 @@ mod test {
assert_eq!(expected, decoded.v,);
}

#[test]
fn test_deserialize_milliseconds_keeps_every_millisecond() {
#[derive(Deserialize)]
struct Test {
#[serde(deserialize_with = "deserialize_milliseconds")]
v: DateTime<Utc>,
}

// Dividing by 1000.0 and multiplying the fraction back used to
// truncate some of these values to the millisecond before.
for millis in [
1507217624349_i64,
1595035749701,
1709814735349,
1700000000001,
1700000000999,
] {
let expected = Utc.timestamp_millis_opt(millis).unwrap();

let decoded: Test = serde_json::from_str(&format!(r#"{{"v":{millis}}}"#)).unwrap();
assert_eq!(expected, decoded.v, "integer {millis}");

let decoded: Test = serde_json::from_str(&format!(r#"{{"v":"{millis}"}}"#)).unwrap();
assert_eq!(expected, decoded.v, "string {millis}");

let decoded: Test = serde_json::from_str(&format!(r#"{{"v":{millis}.0}}"#)).unwrap();
assert_eq!(expected, decoded.v, "float {millis}");
}
}

#[test]
fn test_deserialize_seconds() {
#[derive(Deserialize)]
struct Test {
#[serde(deserialize_with = "deserialize_seconds")]
v: DateTime<Utc>,
}

let cases = [
// Three fractional digits, as in the Kinesis fixture.
("1480641523.477", 1480641523, 477_000_000),
// A JSON number drops trailing zeros, so .470 arrives as .47
// and .500 arrives as .5.
("1480641523.47", 1480641523, 470_000_000),
("1480641523.5", 1480641523, 500_000_000),
// Leading zeros in the fraction are significant.
("1480641523.05", 1480641523, 50_000_000),
("1480641523.007", 1480641523, 7_000_000),
// More than three digits.
("1480641523.4775", 1480641523, 477_500_000),
("1480641523.123456", 1480641523, 123_456_000),
// No fraction at all.
("1480641523", 1480641523, 0),
("1480641523.0", 1480641523, 0),
];

for (input, seconds, nanos) in cases {
let expected = Utc.timestamp_opt(seconds, nanos).unwrap();

let decoded: Test = serde_json::from_str(&format!(r#"{{"v":{input}}}"#)).unwrap();
assert_eq!(expected, decoded.v, "number {input}");

let decoded: Test = serde_json::from_str(&format!(r#"{{"v":"{input}"}}"#)).unwrap();
assert_eq!(expected, decoded.v, "string {input}");
}
}

#[test]
fn test_seconds_round_trip() {
#[derive(Debug, Deserialize, PartialEq, Serialize)]
struct Test {
v: SecondTimestamp,
}

for nanos in [0, 7_000_000, 50_000_000, 470_000_000, 500_000_000, 999_000_000] {
let instance = Test {
v: SecondTimestamp(Utc.timestamp_opt(1480641523, nanos).unwrap()),
};
let encoded = serde_json::to_string(&instance).unwrap();
let decoded: Test = serde_json::from_str(&encoded).unwrap();
assert_eq!(instance, decoded, "{encoded}");
}
}

#[test]
fn test_serialize_milliseconds() {
#[derive(Serialize)]
Expand Down