diff --git a/.github/workflows/build-events.yml b/.github/workflows/build-events.yml index 8f0e6d1dc..416e5f67b 100644 --- a/.github/workflows/build-events.yml +++ b/.github/workflows/build-events.yml @@ -19,7 +19,7 @@ jobs: strategy: matrix: toolchain: - - "1.84.0" # Current MSRV + - "1.85.0" # Current MSRV - stable env: RUST_BACKTRACE: 1 diff --git a/.github/workflows/build-extension.yml b/.github/workflows/build-extension.yml index 90d5bf593..22073b7e2 100644 --- a/.github/workflows/build-extension.yml +++ b/.github/workflows/build-extension.yml @@ -25,7 +25,7 @@ jobs: strategy: matrix: toolchain: - - "1.84.0" # Current MSRV + - "1.85.0" # Current MSRV - stable env: RUST_BACKTRACE: 1 diff --git a/.github/workflows/build-integration-test.yml b/.github/workflows/build-integration-test.yml index 4308c6d62..947ddb289 100644 --- a/.github/workflows/build-integration-test.yml +++ b/.github/workflows/build-integration-test.yml @@ -26,7 +26,7 @@ jobs: strategy: matrix: toolchain: - - "1.84.0" # Current MSRV + - "1.85.0" # Current MSRV - stable env: RUST_BACKTRACE: 1 diff --git a/.github/workflows/build-runtime.yml b/.github/workflows/build-runtime.yml index 16603df2f..2389ca738 100644 --- a/.github/workflows/build-runtime.yml +++ b/.github/workflows/build-runtime.yml @@ -24,7 +24,7 @@ jobs: strategy: matrix: toolchain: - - "1.84.0" # Current MSRV + - "1.85.0" # Current MSRV - stable env: RUST_BACKTRACE: 1 diff --git a/Cargo.toml b/Cargo.toml index ce1f66402..45e44924e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,11 +14,6 @@ exclude = ["examples","lambda-events/lambda-events-examples"] [workspace.dependencies] base64 = "0.22" bytes = "1" -chrono = { version = "0.4.35", default-features = false, features = [ - "clock", - "serde", - "std", -] } futures = "0.3" futures-channel = "0.3" futures-util = "0.3" @@ -28,6 +23,7 @@ http-body-util = "0.1" http-serde = "2.0" hyper = "1.0" hyper-util = "0.1.1" +jiff = { version = "1", default-features = false, features = ["serde", "std"] } pin-project-lite = "0.2" tower = "0.5" tower-layer = "0.3" diff --git a/README.md b/README.md index 7b0cc9438..e04a5a6f2 100644 --- a/README.md +++ b/README.md @@ -601,7 +601,7 @@ async fn handler( ## Supported Rust Versions (MSRV) -The AWS Lambda Rust Runtime requires a minimum of Rust 1.84.0, and is not guaranteed to build on compiler versions earlier than that. +The AWS Lambda Rust Runtime requires a minimum of Rust 1.85.0, and is not guaranteed to build on compiler versions earlier than that. ## Security diff --git a/examples/basic-s3-thumbnail/Cargo.toml b/examples/basic-s3-thumbnail/Cargo.toml index fdbd79be1..b3c2926f2 100644 --- a/examples/basic-s3-thumbnail/Cargo.toml +++ b/examples/basic-s3-thumbnail/Cargo.toml @@ -26,4 +26,4 @@ async-trait = "0.1.88" [dev-dependencies] mockall = "0.13.1" -chrono = "0.4" +jiff = "1" diff --git a/examples/basic-s3-thumbnail/src/main.rs b/examples/basic-s3-thumbnail/src/main.rs index 0d647b05c..618a9f605 100644 --- a/examples/basic-s3-thumbnail/src/main.rs +++ b/examples/basic-s3-thumbnail/src/main.rs @@ -138,7 +138,6 @@ mod tests { use super::*; use async_trait::async_trait; - //use aws_lambda_events::chrono::DateTime; use aws_lambda_events::s3::{S3Bucket, S3Entity, S3Object, S3RequestParameters, S3UserIdentity}; use aws_sdk_s3::operation::get_object::GetObjectError; use lambda_runtime::{Context, LambdaEvent}; @@ -218,7 +217,7 @@ mod tests { s3_event_record.event_version = Some(String::default()); s3_event_record.event_source = Some(String::default()); s3_event_record.aws_region = Some(String::default()); - s3_event_record.event_time = chrono::DateTime::default(); + s3_event_record.event_time = jiff::Timestamp::default(); s3_event_record.event_name = Some(event_name.to_string()); s3_event_record.principal_id = { let mut s3_user_identity = S3UserIdentity::default(); diff --git a/lambda-events/Cargo.toml b/lambda-events/Cargo.toml index f20987022..0a8a92eec 100644 --- a/lambda-events/Cargo.toml +++ b/lambda-events/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "aws_lambda_events" version = "1.2.1" -rust-version = "1.84.0" +rust-version = "1.85.0" description = "AWS Lambda event definitions" authors = [ "Christian Legnitto ", @@ -19,7 +19,7 @@ edition = "2021" [dependencies] base64 = { workspace = true } bytes = { workspace = true, features = ["serde"], optional = true } -chrono = { workspace = true, optional = true } +jiff = { workspace = true, optional = true } bon = { version = "3", optional = true } flate2 = { version = "1.0.24", optional = true } http = { workspace = true, optional = true } @@ -87,47 +87,47 @@ activemq = [] alb = ["bytes", "http", "http-body", "http-serde", "query_map"] apigw = ["bytes", "http", "http-body", "http-serde", "iam", "query_map"] appsync = [] -autoscaling = ["chrono"] +autoscaling = ["jiff"] bedrock_agent_runtime = [] -chime_bot = ["chrono"] +chime_bot = ["jiff"] clientvpn = [] cloudformation = [] -cloudwatch_alarms = ["chrono"] -cloudwatch_events = ["chrono"] +cloudwatch_alarms = ["jiff"] +cloudwatch_events = ["jiff"] cloudwatch_logs = ["flate2"] -code_commit = ["chrono"] -codebuild = ["chrono"] -codedeploy = ["chrono"] +code_commit = ["jiff"] +codebuild = ["jiff"] +codedeploy = ["jiff"] codepipeline = [] -codepipeline_cloudwatch = ["chrono"] +codepipeline_cloudwatch = ["jiff"] codepipeline_job = [] cognito = [] config = [] connect = [] controltower = [] -dynamodb = ["chrono", "serde_dynamo", "streams"] +dynamodb = ["jiff", "serde_dynamo", "streams"] ecr_scan = [] -firehose = ["chrono"] +firehose = ["jiff"] iam = [] iot = ["bytes", "http", "http-body", "http-serde", "iam"] iot_1_click = [] iot_button = [] iot_deprecated = ["iot"] -kafka = ["chrono"] -kinesis = ["chrono"] +kafka = ["jiff"] +kinesis = ["jiff"] kinesis_analytics = ["kinesis"] lambda_function_urls = ["bytes", "http", "http-body", "http-serde"] lex = [] rabbitmq = [] -s3 = ["bytes", "chrono", "http", "http-body", "http-serde"] +s3 = ["bytes", "jiff", "http", "http-body", "http-serde"] s3_batch_job = ["s3"] secretsmanager = [] -ses = ["chrono"] -sns = ["chrono", "serde_with"] +ses = ["jiff"] +sns = ["jiff", "serde_with"] sqs = ["serde_with"] streams = [] documentdb = [] -eventbridge = ["chrono", "serde_with"] +eventbridge = ["jiff", "serde_with"] vpc_lattice = ["bytes", "http", "http-body", "http-serde", "iam", "query_map"] catch-all-fields = [] diff --git a/lambda-events/lambda-events-examples/Cargo.toml b/lambda-events/lambda-events-examples/Cargo.toml index 216faa082..b85a5b724 100644 --- a/lambda-events/lambda-events-examples/Cargo.toml +++ b/lambda-events/lambda-events-examples/Cargo.toml @@ -9,7 +9,7 @@ aws_lambda_events = { path = "..", features = ["builders"] } lambda_runtime = { path = "../../lambda-runtime" } serde = { version = "1", features = ["derive"] } serde_json = "1" -chrono = { version = "0.4", default-features = false, features = ["clock"] } +jiff = { version = "1", default-features = false, features = ["std"] } serde_dynamo = "4" [[example]] diff --git a/lambda-events/lambda-events-examples/examples/comprehensive-builders.rs b/lambda-events/lambda-events-examples/examples/comprehensive-builders.rs index 148594068..9ae145fca 100644 --- a/lambda-events/lambda-events-examples/examples/comprehensive-builders.rs +++ b/lambda-events/lambda-events-examples/examples/comprehensive-builders.rs @@ -12,7 +12,7 @@ use std::collections::HashMap; fn main() { // S3 Event - Object storage notifications with nested structures let s3_record = S3EventRecord::builder() - .event_time(chrono::Utc::now()) + .event_time(jiff::Timestamp::now()) .principal_id(S3UserIdentity::builder().build()) .request_parameters(S3RequestParameters::builder().build()) .response_elements(HashMap::new()) @@ -42,7 +42,7 @@ fn main() { let dynamodb_record = DynamoDbEventRecord::builder() .aws_region("us-east-1".to_string()) .change(StreamRecord::builder() - .approximate_creation_date_time(chrono::Utc::now()) + .approximate_creation_date_time(jiff::Timestamp::now()) .keys(keys.into()) .new_image(HashMap::new().into()) .old_image(HashMap::new().into()) @@ -63,7 +63,7 @@ fn main() { .sns_message_type("Notification".to_string()) .message_id("msg-123".to_string()) .topic_arn("arn:aws:sns:us-east-1:123456789012:topic".to_string()) - .timestamp(chrono::Utc::now()) + .timestamp(jiff::Timestamp::now()) .signature_version("1".to_string()) .signature("sig".to_string()) .signing_cert_url("https://cert.url".to_string()) diff --git a/lambda-events/src/custom_serde/codebuild_time.rs b/lambda-events/src/custom_serde/codebuild_time.rs index 8d90203fc..e5ecb7059 100644 --- a/lambda-events/src/custom_serde/codebuild_time.rs +++ b/lambda-events/src/custom_serde/codebuild_time.rs @@ -1,4 +1,4 @@ -use chrono::{DateTime, NaiveDateTime, Utc}; +use jiff::{civil::DateTime, tz::TimeZone, Timestamp}; use serde::{ de::{Deserializer, Error as DeError, Visitor}, ser::Serializer, @@ -11,31 +11,35 @@ const CODEBUILD_TIME_FORMAT: &str = "%b %e, %Y %l:%M:%S %p"; struct TimeVisitor; impl Visitor<'_> for TimeVisitor { - type Value = DateTime; + type Value = Timestamp; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "valid codebuild time: {CODEBUILD_TIME_FORMAT}") } fn visit_str(self, val: &str) -> Result { - NaiveDateTime::parse_from_str(val, CODEBUILD_TIME_FORMAT) - .map(|naive| naive.and_utc()) - .map_err(|e| DeError::custom(format!("Parse error {e} for {val}"))) + parse(val).map_err(|e| DeError::custom(format!("Parse error {e} for {val}"))) } } +fn parse(val: &str) -> Result { + DateTime::strptime(CODEBUILD_TIME_FORMAT, val)? + .to_zoned_datetime(TimeZone::UTC) + .map(|zdt| zdt.timestamp()) +} + pub(crate) mod str_time { use super::*; - pub(crate) fn deserialize<'de, D>(d: D) -> Result, D::Error> + pub(crate) fn deserialize<'de, D>(d: D) -> Result where D: Deserializer<'de>, { d.deserialize_str(TimeVisitor) } - pub fn serialize(date: &DateTime, ser: S) -> Result { - let s = format!("{}", date.format(CODEBUILD_TIME_FORMAT)); + pub fn serialize(date: &Timestamp, ser: S) -> Result { + let s = date.strftime(CODEBUILD_TIME_FORMAT).to_string(); ser.serialize_str(&s) } } @@ -43,7 +47,7 @@ pub(crate) mod str_time { pub(crate) mod optional_time { use super::*; - pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result>, D::Error> + pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, { @@ -56,7 +60,7 @@ pub(crate) mod optional_time { Ok(None) } - pub fn serialize(date: &Option>, ser: S) -> Result { + pub fn serialize(date: &Option, ser: S) -> Result { if let Some(date) = date { return str_time::serialize(date, ser); } @@ -69,7 +73,7 @@ pub(crate) mod optional_time { mod tests { use super::*; - type TestTime = DateTime; + type TestTime = Timestamp; #[test] fn test_deserialize_codebuild_time() { @@ -82,9 +86,7 @@ mod tests { "date": "Sep 1, 2017 4:12:29 PM" }); - let expected = NaiveDateTime::parse_from_str("Sep 1, 2017 4:12:29 PM", CODEBUILD_TIME_FORMAT) - .unwrap() - .and_utc(); + let expected: Timestamp = "2017-09-01T16:12:29Z".parse().unwrap(); let decoded: Test = serde_json::from_value(data).unwrap(); assert_eq!(expected, decoded.date); } @@ -100,9 +102,7 @@ mod tests { "date": "Sep 1, 2017 4:12:29 PM" }); - let expected = NaiveDateTime::parse_from_str("Sep 1, 2017 4:12:29 PM", CODEBUILD_TIME_FORMAT) - .unwrap() - .and_utc(); + let expected: Timestamp = "2017-09-01T16:12:29Z".parse().unwrap(); let decoded: Test = serde_json::from_value(data).unwrap(); assert_eq!(Some(expected), decoded.date); } diff --git a/lambda-events/src/custom_serde/float_unix_epoch.rs b/lambda-events/src/custom_serde/float_unix_epoch.rs index 164b4c7e6..817c63f86 100644 --- a/lambda-events/src/custom_serde/float_unix_epoch.rs +++ b/lambda-events/src/custom_serde/float_unix_epoch.rs @@ -1,70 +1,29 @@ use serde::{de, ser}; use std::fmt; -use chrono::{offset::TimeZone, DateTime, LocalResult, Utc}; +use super::floor_millis; +use jiff::Timestamp; -enum SerdeError { - NonExistent { timestamp: V }, - Ambiguous { timestamp: V, min: D, max: D }, -} - -fn ne_timestamp(ts: T) -> SerdeError { - SerdeError::NonExistent:: { timestamp: ts } -} - -impl fmt::Debug for SerdeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "ChronoSerdeError({self})") - } -} - -impl fmt::Display for SerdeError { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - match *self { - SerdeError::NonExistent { ref timestamp } => { - write!(f, "value is not a legal timestamp: {timestamp}") - } - SerdeError::Ambiguous { - ref timestamp, - ref min, - ref max, - } => write!( - f, - "value is an ambiguous timestamp: {timestamp}, could be either of {min}, {max}", - ), - } - } -} - -fn serde_from(me: LocalResult, ts: &V) -> Result +fn serde_from(me: Result, ts: &V) -> Result where E: de::Error, V: fmt::Display, - T: fmt::Display, { - match me { - LocalResult::None => Err(E::custom(ne_timestamp(ts))), - LocalResult::Ambiguous(min, max) => Err(E::custom(SerdeError::Ambiguous { - timestamp: ts, - min, - max, - })), - LocalResult::Single(val) => Ok(val), - } + me.map_err(|_| E::custom(format!("value is not a legal timestamp: {ts}"))) } struct SecondsFloatTimestampVisitor; /// Serialize a UTC datetime into an float number of seconds since the epoch -pub fn serialize(dt: &DateTime, serializer: S) -> Result +pub fn serialize(dt: &Timestamp, serializer: S) -> Result where S: ser::Serializer, { - serializer.serialize_i64(dt.timestamp_millis() / 1000) + serializer.serialize_i64(floor_millis(dt) / 1000) } -/// Deserialize a `DateTime` from a float seconds timestamp -pub fn deserialize<'de, D>(d: D) -> Result, D::Error> +/// Deserialize a `Timestamp` from a float seconds timestamp +pub fn deserialize<'de, D>(d: D) -> Result where D: de::Deserializer<'de>, { @@ -72,35 +31,35 @@ where } impl de::Visitor<'_> for SecondsFloatTimestampVisitor { - type Value = DateTime; + type Value = Timestamp; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("a unix timestamp as a float") } /// Deserialize a timestamp in seconds since the epoch - fn visit_u64(self, value: u64) -> Result, E> + fn visit_u64(self, value: u64) -> Result where E: de::Error, { - serde_from(Utc.timestamp_opt(value as i64, 0), &value) + serde_from(Timestamp::from_second(value as i64), &value) } /// Deserialize a timestamp in seconds since the epoch - fn visit_i64(self, value: i64) -> Result, E> + fn visit_i64(self, value: i64) -> Result where E: de::Error, { - serde_from(Utc.timestamp_opt(value, 0), &value) + serde_from(Timestamp::from_second(value), &value) } /// Deserialize a timestamp in seconds since the epoch - fn visit_f64(self, value: f64) -> Result, E> + fn visit_f64(self, value: f64) -> Result where E: de::Error, { let time_ms = (value.fract() * 1_000_000.).floor() as u32; let time_s = value.trunc() as i64; - serde_from(Utc.timestamp_opt(time_s, time_ms), &value) + serde_from(Timestamp::new(time_s, time_ms as i32), &value) } } diff --git a/lambda-events/src/custom_serde/mod.rs b/lambda-events/src/custom_serde/mod.rs index d7b340f27..d3c3f4c1d 100644 --- a/lambda-events/src/custom_serde/mod.rs +++ b/lambda-events/src/custom_serde/mod.rs @@ -40,6 +40,15 @@ mod query_string_parameters; #[cfg(feature = "alb")] pub(crate) use self::query_string_parameters::*; +#[cfg(feature = "jiff")] +pub(crate) mod rfc3339; + +/// Milliseconds since the Unix epoch, rounded towards negative infinity. +#[cfg(feature = "jiff")] +pub(crate) fn floor_millis(ts: &jiff::Timestamp) -> i64 { + ts.as_nanosecond().div_euclid(1_000_000) as i64 +} + pub(crate) fn deserialize_base64<'de, D>(deserializer: D) -> Result, D::Error> where D: Deserializer<'de>, diff --git a/lambda-events/src/custom_serde/rfc3339.rs b/lambda-events/src/custom_serde/rfc3339.rs new file mode 100644 index 000000000..785900585 --- /dev/null +++ b/lambda-events/src/custom_serde/rfc3339.rs @@ -0,0 +1,148 @@ +use jiff::Timestamp; +use serde::{ + de::{Deserializer, Error as DeError, Visitor}, + ser::Serializer, +}; +use std::fmt; + +struct TimeVisitor; +impl Visitor<'_> for TimeVisitor { + type Value = Timestamp; + + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { + formatter.write_str("an RFC 3339 timestamp") + } + + fn visit_str(self, val: &str) -> Result { + val.parse() + .or_else(|err| { + // Whitespace inside the timestamp, like `12: 36: 15.490+0000`, was accepted with chrono + // and the CloudWatch alarm fixtures have it. + let mut compact = String::with_capacity(val.len()); + for part in val.split_ascii_whitespace() { + // A space after the date stands in for the `T`. + if compact.len() == "2023-08-04".len() { + compact.push('T'); + } + compact.push_str(part); + } + compact.parse().map_err(|_| err) + }) + .map_err(DeError::custom) + } +} + +pub(crate) fn deserialize<'de, D>(d: D) -> Result +where + D: Deserializer<'de>, +{ + d.deserialize_str(TimeVisitor) +} + +/// Serialize a `Timestamp` with zero, three, six or nine fractional digits, +/// instead of the shortest representation that `Timestamp` uses by default. +pub(crate) fn serialize(date: &Timestamp, ser: S) -> Result { + let precision = match date.subsec_nanosecond() { + 0 => 0, + n if n % 1_000_000 == 0 => 3, + n if n % 1_000 == 0 => 6, + _ => 9, + }; + ser.collect_str(&format_args!("{date:.precision$}")) +} + +#[cfg(any(feature = "cloudwatch_alarms", feature = "eventbridge"))] +pub(crate) mod optional { + use super::*; + use serde::Deserialize; + + pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + let s: Option = Option::deserialize(deserializer)?; + s.map(|val| TimeVisitor.visit_str(&val)).transpose() + } + + pub(crate) fn serialize(date: &Option, ser: S) -> Result { + match date { + Some(date) => super::serialize(date, ser), + None => ser.serialize_none(), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde::{Deserialize, Serialize}; + + #[derive(Deserialize, Serialize)] + struct Test { + #[serde(with = "super")] + v: Timestamp, + } + + #[test] + fn test_serialize_rfc3339() { + let cases = [ + "2017-10-05T15:33:44Z", + "2017-10-05T15:33:44.100Z", + "2017-10-05T15:33:44.120Z", + "2017-10-05T15:33:44.123Z", + "2017-10-05T15:33:44.123400Z", + "2017-10-05T15:33:44.123456Z", + "2017-10-05T15:33:44.123456700Z", + "2017-10-05T15:33:44.123456789Z", + "1969-12-31T23:59:59.500Z", + ]; + for case in cases { + let data = format!(r#"{{"v":"{case}"}}"#); + let decoded: Test = serde_json::from_str(&data).unwrap(); + assert_eq!(data, serde_json::to_string(&decoded).unwrap()); + } + } + + #[test] + fn test_deserialize_rfc3339() { + let expected: Timestamp = "2023-08-04T12:36:15.490Z".parse().unwrap(); + let cases = [ + "2023-08-04T12:36:15.49Z", + "2023-08-04T12:36:15.490+0000", + "2023-08-04T12:36:15.490+00:00", + "2023-08-04T14:36:15.490+02:00", + "2023-08-04 12:36:15.490Z", + "2023-08-04T12: 36: 15.490+0000", + "2023-08-04 12: 36: 15.490+0000", + "2023-08-04 12:36:15.490 +00:00", + " 2023-08-04T12:36:15.490Z ", + ]; + for case in cases { + let decoded: Test = serde_json::from_value(serde_json::json!({ "v": case })).unwrap(); + assert_eq!(expected, decoded.v, "{case}"); + } + assert!(serde_json::from_str::(r#"{"v":"2023-08-04T12:36:15"}"#).is_err()); + } + + #[test] + #[cfg(any(feature = "cloudwatch_alarms", feature = "eventbridge"))] + fn test_optional_rfc3339() { + #[derive(Deserialize, Serialize)] + struct OptionalTest { + #[serde(default, with = "optional")] + v: Option, + } + + let data = r#"{"v":"2017-10-05T15:33:44.500Z"}"#; + let decoded: OptionalTest = serde_json::from_str(data).unwrap(); + assert_eq!(Some("2017-10-05T15:33:44.5Z".parse().unwrap()), decoded.v); + assert_eq!(data, serde_json::to_string(&decoded).unwrap()); + + let decoded: OptionalTest = serde_json::from_str(r#"{"v":null}"#).unwrap(); + assert_eq!(None, decoded.v); + assert_eq!(r#"{"v":null}"#, serde_json::to_string(&decoded).unwrap()); + + let decoded: OptionalTest = serde_json::from_str("{}").unwrap(); + assert_eq!(None, decoded.v); + } +} diff --git a/lambda-events/src/encodings/mod.rs b/lambda-events/src/encodings/mod.rs index 8b3089477..010a9548f 100644 --- a/lambda-events/src/encodings/mod.rs +++ b/lambda-events/src/encodings/mod.rs @@ -1,12 +1,12 @@ use serde::{Deserialize, Serialize}; use std::ops::{Deref, DerefMut}; -#[cfg(feature = "chrono")] +#[cfg(feature = "jiff")] mod time; use crate::custom_serde::{deserialize_base64, serialize_base64}; -#[cfg(feature = "chrono")] -#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))] +#[cfg(feature = "jiff")] +#[cfg_attr(docsrs, doc(cfg(feature = "jiff")))] pub use self::time::*; #[cfg(feature = "http")] mod http; diff --git a/lambda-events/src/encodings/time.rs b/lambda-events/src/encodings/time.rs index c7ca04a61..7710b287d 100644 --- a/lambda-events/src/encodings/time.rs +++ b/lambda-events/src/encodings/time.rs @@ -1,4 +1,5 @@ -use chrono::{DateTime, TimeDelta, TimeZone, Utc}; +use crate::custom_serde::floor_millis; +use jiff::{SignedDuration, Timestamp}; use serde::{ de::{Deserializer, Error as DeError}, ser::Serializer, @@ -11,11 +12,11 @@ use std::ops::{Deref, DerefMut}; pub struct MillisecondTimestamp( #[serde(deserialize_with = "deserialize_milliseconds")] #[serde(serialize_with = "serialize_milliseconds")] - pub DateTime, + pub Timestamp, ); impl Deref for MillisecondTimestamp { - type Target = DateTime; + type Target = Timestamp; fn deref(&self) -> &Self::Target { &self.0 @@ -33,11 +34,11 @@ impl DerefMut for MillisecondTimestamp { pub struct SecondTimestamp( #[serde(deserialize_with = "deserialize_seconds")] #[serde(serialize_with = "serialize_seconds")] - pub DateTime, + pub Timestamp, ); impl Deref for SecondTimestamp { - type Target = DateTime; + type Target = Timestamp; fn deref(&self) -> &Self::Target { &self.0 @@ -55,11 +56,11 @@ impl DerefMut for SecondTimestamp { pub struct SecondDuration( #[serde(deserialize_with = "deserialize_duration_seconds")] #[serde(serialize_with = "serialize_duration_seconds")] - pub TimeDelta, + pub SignedDuration, ); impl Deref for SecondDuration { - type Target = TimeDelta; + type Target = SignedDuration; fn deref(&self) -> &Self::Target { &self.0 @@ -77,11 +78,11 @@ impl DerefMut for SecondDuration { pub struct MinuteDuration( #[serde(deserialize_with = "deserialize_duration_minutes")] #[serde(serialize_with = "serialize_duration_minutes")] - pub TimeDelta, + pub SignedDuration, ); impl Deref for MinuteDuration { - type Target = TimeDelta; + type Target = SignedDuration; fn deref(&self) -> &Self::Target { &self.0 @@ -94,15 +95,15 @@ impl DerefMut for MinuteDuration { } } -fn serialize_milliseconds(date: &DateTime, serializer: S) -> Result +fn serialize_milliseconds(date: &Timestamp, serializer: S) -> Result where S: Serializer, { - let ts_with_millis = date.timestamp_millis(); + let ts_with_millis = floor_millis(date); serializer.serialize_str(&ts_with_millis.to_string()) } -fn deserialize_milliseconds<'de, D>(deserializer: D) -> Result, D::Error> +fn deserialize_milliseconds<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, { @@ -111,20 +112,17 @@ where let seconds: f64 = whole as f64 / 1000.0; let milliseconds: u32 = (seconds.fract() * 1000f64) as u32; let nanos = milliseconds * 1_000_000; - Utc.timestamp_opt(seconds as i64, nanos) - .latest() - .ok_or_else(|| D::Error::custom("invalid timestamp")) + Timestamp::new(seconds as i64, nanos as i32).map_err(|_| D::Error::custom("invalid timestamp")) } -fn serialize_seconds(date: &DateTime, serializer: S) -> Result +fn serialize_seconds(date: &Timestamp, serializer: S) -> Result where S: Serializer, { - let seconds = date.timestamp(); - let milliseconds = date.timestamp_subsec_millis(); - let whole_seconds = seconds + (milliseconds as i64 / 1000); - let subsec_millis = milliseconds % 1000; - if milliseconds > 0 { + let millis = floor_millis(date); + let whole_seconds = millis.div_euclid(1000); + let subsec_millis = millis.rem_euclid(1000); + if subsec_millis > 0 { let combined = format!("{whole_seconds}.{subsec_millis:03}"); serializer.serialize_str(&combined) } else { @@ -132,51 +130,51 @@ where } } -fn deserialize_seconds<'de, D>(deserializer: D) -> Result, D::Error> +fn deserialize_seconds<'de, D>(deserializer: D) -> Result 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) - .latest() + i32::try_from(nanos as u32) + .ok() + .and_then(|nanos| Timestamp::new(seconds as i64, nanos).ok()) .ok_or_else(|| D::Error::custom("invalid timestamp")) } -fn serialize_duration_seconds(duration: &TimeDelta, serializer: S) -> Result +fn serialize_duration_seconds(duration: &SignedDuration, serializer: S) -> Result where S: Serializer, { - let seconds = duration.num_seconds(); + let seconds = duration.as_secs(); serializer.serialize_i64(seconds) } -fn deserialize_duration_seconds<'de, D>(deserializer: D) -> Result +fn deserialize_duration_seconds<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, { let seconds = f64::deserialize(deserializer)?; - TimeDelta::try_seconds(seconds as i64) - .ok_or_else(|| D::Error::custom(format!("invalid time delta seconds `{seconds}`"))) + Ok(SignedDuration::from_secs(seconds as i64)) } -fn serialize_duration_minutes(duration: &TimeDelta, serializer: S) -> Result +fn serialize_duration_minutes(duration: &SignedDuration, serializer: S) -> Result where S: Serializer, { - let minutes = duration.num_minutes(); + let minutes = duration.as_mins(); serializer.serialize_i64(minutes) } -fn deserialize_duration_minutes<'de, D>(deserializer: D) -> Result +fn deserialize_duration_minutes<'de, D>(deserializer: D) -> Result where D: Deserializer<'de>, { let minutes = f64::deserialize(deserializer)?; - TimeDelta::try_minutes(minutes as i64) + SignedDuration::try_from_mins(minutes as i64) .ok_or_else(|| D::Error::custom(format!("invalid time delta minutes `{minutes}`"))) } @@ -213,19 +211,17 @@ where } #[cfg(test)] -#[allow(deprecated)] mod test { use super::*; - use chrono::TimeZone; #[test] fn test_deserialize_milliseconds() { #[derive(Deserialize)] struct Test { #[serde(deserialize_with = "deserialize_milliseconds")] - v: DateTime, + v: Timestamp, } - let expected = Utc.ymd(2017, 10, 5).and_hms_nano(15, 33, 44, 302_000_000); + let expected: Timestamp = "2017-10-05T15:33:44.302Z".parse().unwrap(); // Test parsing strings. let data = serde_json::json!({ @@ -249,10 +245,10 @@ mod test { #[derive(Serialize)] struct Test { #[serde(serialize_with = "serialize_milliseconds")] - v: DateTime, + v: Timestamp, } let instance = Test { - v: Utc.ymd(1983, 7, 22).and_hms_nano(1, 0, 0, 99_888_777), + v: "1983-07-22T01:00:00.099888777Z".parse().unwrap(), }; let encoded = serde_json::to_string(&instance).unwrap(); assert_eq!(encoded, String::from(r#"{"v":"427683600099"}"#)); @@ -263,29 +259,22 @@ mod test { #[derive(Serialize)] struct Test { #[serde(serialize_with = "serialize_seconds")] - v: DateTime, + v: Timestamp, } // Make sure nanoseconds are chopped off. let instance = Test { - v: Utc.ymd(1983, 7, 22).and_hms_nano(1, 0, 0, 99), + v: "1983-07-22T01:00:00.000000099Z".parse().unwrap(), }; let encoded = serde_json::to_string(&instance).unwrap(); assert_eq!(encoded, String::from(r#"{"v":"427683600"}"#)); // Make sure milliseconds are included. let instance = Test { - v: Utc.ymd(1983, 7, 22).and_hms_nano(1, 0, 0, 2_000_000), + v: "1983-07-22T01:00:00.002Z".parse().unwrap(), }; let encoded = serde_json::to_string(&instance).unwrap(); assert_eq!(encoded, String::from(r#"{"v":"427683600.002"}"#)); - - // Make sure leap seconds are included. - let instance = Test { - v: Utc.ymd(1983, 7, 22).and_hms_nano(23, 59, 59, 1_999_999_999), - }; - let encoded = serde_json::to_string(&instance).unwrap(); - assert_eq!(encoded, String::from(r#"{"v":"427766400.999"}"#)); } #[test] @@ -293,10 +282,10 @@ mod test { #[derive(Deserialize)] struct Test { #[serde(deserialize_with = "deserialize_duration_seconds")] - v: TimeDelta, + v: SignedDuration, } - let expected = TimeDelta::try_seconds(36).unwrap(); + let expected = SignedDuration::from_secs(36); let data = serde_json::json!({ "v": 36, @@ -316,10 +305,10 @@ mod test { #[derive(Serialize)] struct Test { #[serde(serialize_with = "serialize_duration_seconds")] - v: TimeDelta, + v: SignedDuration, } let instance = Test { - v: TimeDelta::try_seconds(36).unwrap(), + v: SignedDuration::from_secs(36), }; let encoded = serde_json::to_string(&instance).unwrap(); assert_eq!(encoded, String::from(r#"{"v":36}"#)); @@ -330,10 +319,10 @@ mod test { #[derive(Deserialize)] struct Test { #[serde(deserialize_with = "deserialize_duration_minutes")] - v: TimeDelta, + v: SignedDuration, } - let expected = TimeDelta::try_minutes(36).unwrap(); + let expected = SignedDuration::from_mins(36); let data = serde_json::json!({ "v": 36, @@ -353,10 +342,10 @@ mod test { #[derive(Serialize)] struct Test { #[serde(serialize_with = "serialize_duration_minutes")] - v: TimeDelta, + v: SignedDuration, } let instance = Test { - v: TimeDelta::try_minutes(36).unwrap(), + v: SignedDuration::from_mins(36), }; let encoded = serde_json::to_string(&instance).unwrap(); assert_eq!(encoded, String::from(r#"{"v":36}"#)); diff --git a/lambda-events/src/event/autoscaling/mod.rs b/lambda-events/src/event/autoscaling/mod.rs index d14bc1b00..f23b13bfc 100644 --- a/lambda-events/src/event/autoscaling/mod.rs +++ b/lambda-events/src/event/autoscaling/mod.rs @@ -1,11 +1,11 @@ #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value; use std::collections::HashMap; -use crate::custom_serde::deserialize_nullish; +use crate::custom_serde::{deserialize_nullish, rfc3339}; /// `AutoScalingEvent` struct is used to parse the json for auto scaling event types // #[non_exhaustive] @@ -35,7 +35,8 @@ where #[serde(rename = "account")] pub account_id: Option, /// Event timestamp - pub time: DateTime, + #[serde(with = "rfc3339")] + pub time: Timestamp, /// Region of event #[serde(default)] pub region: Option, diff --git a/lambda-events/src/event/chime_bot/mod.rs b/lambda-events/src/event/chime_bot/mod.rs index 92a6d3910..ba9305d0d 100644 --- a/lambda-events/src/event/chime_bot/mod.rs +++ b/lambda-events/src/event/chime_bot/mod.rs @@ -1,6 +1,7 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; @@ -20,7 +21,8 @@ pub struct ChimeBotEvent { #[serde(rename = "InboundHttpsEndpoint")] pub inbound_https_endpoint: Option, #[serde(rename = "EventTimestamp")] - pub event_timestamp: DateTime, + #[serde(with = "rfc3339")] + pub event_timestamp: Timestamp, #[serde(rename = "Message")] pub message: Option, /// Catchall to catch any additional fields that were present but not explicitly defined by this struct. diff --git a/lambda-events/src/event/cloudwatch_alarms/mod.rs b/lambda-events/src/event/cloudwatch_alarms/mod.rs index aa66a7de1..ab0dd3363 100644 --- a/lambda-events/src/event/cloudwatch_alarms/mod.rs +++ b/lambda-events/src/event/cloudwatch_alarms/mod.rs @@ -1,8 +1,9 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; use std::collections::HashMap; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{ de::{DeserializeOwned, Visitor}, ser::Error as SerError, @@ -33,7 +34,8 @@ where pub source: Option, #[serde(default)] pub region: Option, - pub time: DateTime, + #[serde(with = "rfc3339")] + pub time: Timestamp, #[serde(default, bound = "")] pub alarm_data: CloudWatchAlarmData, @@ -97,7 +99,8 @@ where pub reason: String, #[serde(default, bound = "")] pub reason_data: Option, - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, pub actions_suppressed_by: Option, pub actions_suppressed_reason: Option, /// Catchall to catch any additional fields that were present but not explicitly defined by this struct. @@ -219,6 +222,7 @@ pub enum CloudWatchAlarmStateValue { #[non_exhaustive] #[derive(Clone, Debug, PartialEq)] +#[allow(clippy::large_enum_variant)] pub enum CloudWatchAlarmStateReasonData { Metric(CloudWatchAlarmStateReasonDataMetric), Composite(ClodWatchAlarmStateReasonDataComposite), @@ -238,9 +242,11 @@ impl Default for CloudWatchAlarmStateReasonData { pub struct CloudWatchAlarmStateReasonDataMetric { pub version: String, #[serde(default)] - pub query_date: Option>, + #[serde(with = "rfc3339::optional")] + pub query_date: Option, #[serde(default)] - pub start_date: Option>, + #[serde(with = "rfc3339::optional")] + pub start_date: Option, #[serde(default)] pub unit: Option, #[serde(default)] @@ -270,7 +276,8 @@ pub struct CloudWatchAlarmStateReasonDataMetric { #[derive(Clone, Debug, Default, Deserialize, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct CloudWatchAlarmStateEvaluatedDatapoint { - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, #[serde(default)] pub sample_count: Option, #[serde(default)] @@ -326,7 +333,8 @@ pub struct CloudWatchAlarmStateTriggeringAlarm { #[derive(Clone, Debug, Default, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct CloudWatchAlarmStateTriggeringAlarmState { - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, #[serde(default)] pub value: CloudWatchAlarmStateValue, /// Catchall to catch any additional fields that were present but not explicitly defined by this struct. diff --git a/lambda-events/src/event/cloudwatch_events/cloudtrail.rs b/lambda-events/src/event/cloudwatch_events/cloudtrail.rs index 2b4d8f378..3df7dc463 100644 --- a/lambda-events/src/event/cloudwatch_events/cloudtrail.rs +++ b/lambda-events/src/event/cloudwatch_events/cloudtrail.rs @@ -1,6 +1,7 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; use serde_json::Value; @@ -80,7 +81,8 @@ pub struct WebIdFederationData { #[serde(rename_all = "camelCase")] pub struct Attributes { pub mfa_authenticated: String, - pub creation_date: DateTime, + #[serde(with = "rfc3339")] + pub creation_date: Timestamp, /// Catchall to catch any additional fields that were present but not explicitly defined by this struct. /// Enabled with Cargo feature `catch-all-fields`. /// If `catch-all-fields` is disabled, any additional fields that are present will be ignored. diff --git a/lambda-events/src/event/cloudwatch_events/mod.rs b/lambda-events/src/event/cloudwatch_events/mod.rs index da93b2bc9..a628cef77 100644 --- a/lambda-events/src/event/cloudwatch_events/mod.rs +++ b/lambda-events/src/event/cloudwatch_events/mod.rs @@ -1,6 +1,7 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value; @@ -44,7 +45,8 @@ where #[serde(default)] #[serde(rename = "account")] pub account_id: Option, - pub time: DateTime, + #[serde(with = "rfc3339")] + pub time: Timestamp, #[serde(default)] pub region: Option, pub resources: Vec, diff --git a/lambda-events/src/event/code_commit/mod.rs b/lambda-events/src/event/code_commit/mod.rs index dc6574a33..e064348f5 100644 --- a/lambda-events/src/event/code_commit/mod.rs +++ b/lambda-events/src/event/code_commit/mod.rs @@ -1,11 +1,11 @@ #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; -use crate::custom_serde::deserialize_nullish; +use crate::custom_serde::{deserialize_nullish, rfc3339}; /// `CodeCommitEvent` represents a CodeCommit event #[non_exhaustive] @@ -25,7 +25,7 @@ pub struct CodeCommitEvent { pub other: serde_json::Map, } -pub type CodeCommitEventTime = DateTime; +pub type CodeCommitEventTime = Timestamp; /// `CodeCommitRecord` represents a CodeCommit record #[non_exhaustive] @@ -37,6 +37,7 @@ pub struct CodeCommitRecord { pub event_id: Option, #[serde(default)] pub event_version: Option, + #[serde(with = "rfc3339")] pub event_time: CodeCommitEventTime, #[serde(default)] pub event_trigger_name: Option, diff --git a/lambda-events/src/event/codebuild/mod.rs b/lambda-events/src/event/codebuild/mod.rs index 26ad4c165..2a395ad96 100644 --- a/lambda-events/src/event/codebuild/mod.rs +++ b/lambda-events/src/event/codebuild/mod.rs @@ -1,10 +1,10 @@ use crate::{ - custom_serde::{codebuild_time, CodeBuildNumber}, + custom_serde::{codebuild_time, rfc3339, CodeBuildNumber}, encodings::{MinuteDuration, SecondDuration}, }; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value; @@ -39,7 +39,8 @@ pub struct CodeBuildEvent { #[serde(default)] pub version: Option, /// Time is the event's timestamp. - pub time: DateTime, + #[serde(with = "rfc3339")] + pub time: Timestamp, /// ID is the GUID of this event. #[serde(default)] pub id: Option, @@ -300,7 +301,7 @@ where pub other: serde_json::Map, } -pub type CodeBuildTime = DateTime; +pub type CodeBuildTime = Timestamp; #[cfg(test)] mod test { diff --git a/lambda-events/src/event/codedeploy/mod.rs b/lambda-events/src/event/codedeploy/mod.rs index 7f3944b8d..ebadad8a7 100644 --- a/lambda-events/src/event/codedeploy/mod.rs +++ b/lambda-events/src/event/codedeploy/mod.rs @@ -1,6 +1,7 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; @@ -35,7 +36,8 @@ pub struct CodeDeployEvent { #[serde(default)] pub version: Option, /// Time is the event's timestamp. - pub time: DateTime, + #[serde(with = "rfc3339")] + pub time: Timestamp, /// ID is the GUID of this event. #[serde(default)] pub id: Option, diff --git a/lambda-events/src/event/codepipeline_cloudwatch/mod.rs b/lambda-events/src/event/codepipeline_cloudwatch/mod.rs index 5ffe7a9ca..6cf89d4da 100644 --- a/lambda-events/src/event/codepipeline_cloudwatch/mod.rs +++ b/lambda-events/src/event/codepipeline_cloudwatch/mod.rs @@ -1,6 +1,7 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; @@ -39,7 +40,8 @@ pub struct CodePipelineCloudWatchEvent { #[serde(rename = "account")] pub account_id: Option, /// Time is the event's timestamp. - pub time: DateTime, + #[serde(with = "rfc3339")] + pub time: Timestamp, /// Region is the AWS region from which the event originated. #[serde(default)] pub region: Option, diff --git a/lambda-events/src/event/dynamodb/mod.rs b/lambda-events/src/event/dynamodb/mod.rs index 0f67dc0af..7bedf9549 100644 --- a/lambda-events/src/event/dynamodb/mod.rs +++ b/lambda-events/src/event/dynamodb/mod.rs @@ -5,7 +5,7 @@ use crate::{ }; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; @@ -286,7 +286,7 @@ pub struct StreamRecord { #[serde(rename = "ApproximateCreationDateTime")] #[serde(with = "float_unix_epoch")] #[serde(default)] - pub approximate_creation_date_time: DateTime, + pub approximate_creation_date_time: Timestamp, /// The primary key attribute(s) for the DynamoDB item that was modified. #[serde(deserialize_with = "deserialize_nullish")] #[serde(default)] @@ -325,11 +325,9 @@ pub struct StreamRecord { } #[cfg(test)] -#[allow(deprecated)] mod test { use super::*; use crate::fixtures::verify_serde_roundtrip; - use chrono::TimeZone; #[test] #[cfg(feature = "dynamodb")] @@ -341,7 +339,7 @@ mod test { assert_eq!(parsed, reparsed); let event = parsed.records.pop().unwrap(); - let date = Utc.ymd(2016, 12, 2).and_hms(1, 27, 0); + let date: Timestamp = "2016-12-02T01:27:00Z".parse().unwrap(); assert_eq!(date, event.change.approximate_creation_date_time); } @@ -363,7 +361,7 @@ mod test { let output: String = serde_json::to_string(&parsed).unwrap(); let reparsed: EventRecord = serde_json::from_slice(output.as_bytes()).unwrap(); assert_eq!(parsed, reparsed); - let date = Utc.timestamp_micros(0).unwrap(); // 1970-01-01T00:00:00Z + let date = Timestamp::UNIX_EPOCH; assert_eq!(date, reparsed.change.approximate_creation_date_time); } } diff --git a/lambda-events/src/event/eventbridge/mod.rs b/lambda-events/src/event/eventbridge/mod.rs index 36dc43b09..ce831a2b2 100644 --- a/lambda-events/src/event/eventbridge/mod.rs +++ b/lambda-events/src/event/eventbridge/mod.rs @@ -1,6 +1,7 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use serde_json::Value; @@ -27,7 +28,8 @@ where #[serde(default)] pub account: Option, #[serde(default)] - pub time: Option>, + #[serde(with = "rfc3339::optional")] + pub time: Option, #[serde(default)] pub region: Option, #[serde(default)] diff --git a/lambda-events/src/event/s3/event.rs b/lambda-events/src/event/s3/event.rs index f2d69165a..a3ce634d7 100644 --- a/lambda-events/src/event/s3/event.rs +++ b/lambda-events/src/event/s3/event.rs @@ -1,12 +1,12 @@ #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; use std::collections::HashMap; -use crate::custom_serde::deserialize_nullish; +use crate::custom_serde::{deserialize_nullish, rfc3339}; /// `S3Event` which wrap an array of `S3Event`Record #[non_exhaustive] @@ -38,7 +38,8 @@ pub struct S3EventRecord { pub event_source: Option, #[serde(default)] pub aws_region: Option, - pub event_time: DateTime, + #[serde(with = "rfc3339")] + pub event_time: Timestamp, #[serde(default)] pub event_name: Option, #[serde(rename = "userIdentity")] diff --git a/lambda-events/src/event/ses/mod.rs b/lambda-events/src/event/ses/mod.rs index 0b8bec55e..ccd2ad0e3 100644 --- a/lambda-events/src/event/ses/mod.rs +++ b/lambda-events/src/event/ses/mod.rs @@ -1,6 +1,7 @@ +use crate::custom_serde::rfc3339; #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; @@ -69,7 +70,8 @@ pub struct SimpleEmailMessage { pub common_headers: SimpleEmailCommonHeaders, #[serde(default)] pub source: Option, - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, pub destination: Vec, pub headers: Vec, pub headers_truncated: bool, @@ -91,7 +93,8 @@ pub struct SimpleEmailMessage { #[serde(rename_all = "camelCase")] pub struct SimpleEmailReceipt { pub recipients: Vec, - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, pub spam_verdict: SimpleEmailVerdict, pub dkim_verdict: SimpleEmailVerdict, pub dmarc_verdict: SimpleEmailVerdict, diff --git a/lambda-events/src/event/sns/mod.rs b/lambda-events/src/event/sns/mod.rs index 5879bc873..3a5a81b19 100644 --- a/lambda-events/src/event/sns/mod.rs +++ b/lambda-events/src/event/sns/mod.rs @@ -1,12 +1,12 @@ #[cfg(feature = "builders")] use bon::Builder; -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{de::DeserializeOwned, Deserialize, Serialize}; #[cfg(feature = "catch-all-fields")] use serde_json::Value; use std::collections::HashMap; -use crate::custom_serde::deserialize_nullish; +use crate::custom_serde::{deserialize_nullish, rfc3339}; /// The `Event` notification event handled by Lambda /// @@ -85,7 +85,8 @@ pub struct SnsMessage { pub subject: Option, /// The time (UTC) when the notification was published. - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, /// Version of the Amazon SNS signature used. pub signature_version: String, @@ -166,7 +167,8 @@ pub struct SnsSubscriptionMessage { pub subject: Option, /// The time (UTC) when the message was sent. - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, /// Version of the Amazon SNS signature used. pub signature_version: String, @@ -289,7 +291,8 @@ pub struct SnsMessageObj { pub subject: Option, /// The time (UTC) when the notification was published. - pub timestamp: DateTime, + #[serde(with = "rfc3339")] + pub timestamp: Timestamp, /// Version of the Amazon SNS signature used. pub signature_version: String, diff --git a/lambda-events/src/lib.rs b/lambda-events/src/lib.rs index 541a4dc83..ee7a651a0 100644 --- a/lambda-events/src/lib.rs +++ b/lambda-events/src/lib.rs @@ -10,8 +10,8 @@ pub use query_map; mod custom_serde; /// Encodings used in AWS Lambda json event values. pub mod encodings; -#[cfg(feature = "chrono")] -#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))] +#[cfg(feature = "jiff")] +#[cfg_attr(docsrs, doc(cfg(feature = "jiff")))] pub mod time_window; /// AWS Lambda event definitions. diff --git a/lambda-events/src/time_window.rs b/lambda-events/src/time_window.rs index 35c038979..daa7cb2d3 100644 --- a/lambda-events/src/time_window.rs +++ b/lambda-events/src/time_window.rs @@ -1,8 +1,8 @@ -use chrono::{DateTime, Utc}; +use jiff::Timestamp; use serde::{Deserialize, Serialize}; use std::collections::HashMap; -use crate::custom_serde::deserialize_nullish; +use crate::custom_serde::{deserialize_nullish, rfc3339}; /// `Window` is the object that captures the time window for the records in the event when using the tumbling windows feature /// Kinesis: @@ -11,15 +11,17 @@ use crate::custom_serde::deserialize_nullish; #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Window { - pub start: DateTime, - pub end: DateTime, + #[serde(with = "rfc3339")] + pub start: Timestamp, + #[serde(with = "rfc3339")] + pub end: Timestamp, } impl Default for Window { fn default() -> Self { Window { - start: Utc::now(), - end: Utc::now(), + start: Timestamp::now(), + end: Timestamp::now(), } } } @@ -77,7 +79,7 @@ mod test { }); let parsed: Window = serde_json::from_value(v).unwrap(); - assert_eq!("2020-12-09T07:04:00+00:00", &parsed.start.to_rfc3339()); - assert_eq!("2020-12-09T07:06:00+00:00", &parsed.end.to_rfc3339()); + assert_eq!("2020-12-09T07:04:00Z", &parsed.start.to_string()); + assert_eq!("2020-12-09T07:06:00Z", &parsed.end.to_string()); } } diff --git a/lambda-extension/Cargo.toml b/lambda-extension/Cargo.toml index 0aefbd84d..dc2a1c79b 100644 --- a/lambda-extension/Cargo.toml +++ b/lambda-extension/Cargo.toml @@ -2,7 +2,7 @@ name = "lambda-extension" version = "1.1.1" edition = "2021" -rust-version = "1.84.0" +rust-version = "1.85.0" authors = [ "David Calavera ", "Harold Sun ", @@ -20,11 +20,11 @@ tracing = ["lambda_runtime_api_client/tracing"] [dependencies] async-stream = "0.3" -chrono = { workspace = true, features = ["serde"] } http = { workspace = true } http-body-util = { workspace = true } hyper = { workspace = true, features = ["http1", "client", "server"] } hyper-util = { workspace = true } +jiff = { workspace = true } lambda_runtime_api_client = { version = "1.1.1", path = "../lambda-runtime-api-client" } serde = { version = "1", features = ["derive"] } serde_json = "^1" diff --git a/lambda-extension/src/logs.rs b/lambda-extension/src/logs.rs index 541dedc2d..d55deb0c3 100644 --- a/lambda-extension/src/logs.rs +++ b/lambda-extension/src/logs.rs @@ -1,7 +1,7 @@ -use chrono::{DateTime, Utc}; use http::{Request, Response}; use http_body_util::BodyExt; use hyper::body::Incoming; +use jiff::Timestamp; use lambda_runtime_api_client::body::Body; use serde::{Deserialize, Serialize}; use std::{fmt, sync::Arc}; @@ -16,7 +16,7 @@ use crate::{Error, ExtensionError}; #[derive(Clone, Debug, Deserialize, PartialEq)] pub struct LambdaLog { /// Time when the log was generated - pub time: DateTime, + pub time: Timestamp, /// Log record entry #[serde(flatten)] pub record: LambdaLogRecord, @@ -233,17 +233,12 @@ where #[cfg(test)] mod tests { use super::*; - use chrono::{TimeDelta, TimeZone}; #[test] fn deserialize_full() { let data = r#"{"time": "2020-08-20T12:31:32.123Z","type": "function", "record": "hello world"}"#; let expected = LambdaLog { - time: Utc - .with_ymd_and_hms(2020, 8, 20, 12, 31, 32) - .unwrap() - .checked_add_signed(TimeDelta::try_milliseconds(123).unwrap()) - .unwrap(), + time: "2020-08-20T12:31:32.123Z".parse().unwrap(), record: LambdaLogRecord::Function("hello world".to_string()), }; diff --git a/lambda-extension/src/telemetry.rs b/lambda-extension/src/telemetry.rs index 6227001f9..3558f4f92 100644 --- a/lambda-extension/src/telemetry.rs +++ b/lambda-extension/src/telemetry.rs @@ -1,9 +1,9 @@ -use chrono::{DateTime, Utc}; use http::{Request, Response}; use http_body_util::BodyExt; use hyper::body::Incoming; +use jiff::Timestamp; use lambda_runtime_api_client::body::Body; -use serde::{de::DeserializeOwned, Deserialize, Serialize}; +use serde::{de::DeserializeOwned, Deserialize, Serialize, Serializer}; use std::{boxed::Box, fmt, sync::Arc}; use tokio::sync::Mutex; use tower::Service; @@ -13,7 +13,8 @@ use tracing::{error, trace}; #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)] pub struct LambdaTelemetry { /// Time when the telemetry was generated - pub time: DateTime, + #[serde(serialize_with = "serialize_timestamp")] + pub time: Timestamp, /// Telemetry record entry #[serde(flatten)] pub record: LambdaTelemetryRecord, @@ -202,7 +203,20 @@ pub struct Span { /// Name of the span pub name: String, /// Start of the span - pub start: DateTime, + #[serde(serialize_with = "serialize_timestamp")] + pub start: Timestamp, +} + +/// Serialize a `Timestamp` with zero, three, six or nine fractional digits, +/// instead of the shortest representation that `Timestamp` uses by default. +fn serialize_timestamp(time: &Timestamp, serializer: S) -> Result { + let precision = match time.subsec_nanosecond() { + 0 => 0, + n if n % 1_000_000 == 0 => 3, + n if n % 1_000 == 0 => 6, + _ => 9, + }; + serializer.collect_str(&format_args!("{time:.precision$}")) } /// Tracing Context @@ -317,7 +331,6 @@ where #[cfg(test)] mod deserialization_tests { use super::*; - use chrono::{TimeDelta, TimeZone}; macro_rules! deserialize_tests { ($($name:ident$(<$log:ty>)?: $value:expr,)*) => { @@ -395,20 +408,12 @@ mod deserialization_tests { spans: vec!( Span { name:"responseLatency".to_string(), - start: Utc - .with_ymd_and_hms(2022, 10, 21, 14, 5, 3) - .unwrap() - .checked_add_signed(TimeDelta::try_milliseconds(165).unwrap()) - .unwrap(), + start: "2022-10-21T14:05:03.165Z".parse().unwrap(), duration_ms: 2598.0 }, Span { name:"responseDuration".to_string(), - start: Utc - .with_ymd_and_hms(2022, 10, 21, 14, 5, 5) - .unwrap() - .checked_add_signed(TimeDelta::try_milliseconds(763).unwrap()) - .unwrap(), + start: "2022-10-21T14:05:05.763Z".parse().unwrap(), duration_ms: 0.0 }, ), @@ -486,8 +491,6 @@ mod deserialization_tests { #[cfg(test)] mod serialization_tests { - use chrono::{TimeDelta, TimeZone}; - use super::*; macro_rules! serialize_tests { ($($name:ident$(<$log:ty>)?: $value:expr,)*) => { @@ -510,15 +513,23 @@ mod serialization_tests { // function function: ( LambdaTelemetry { - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::Function("hello world".to_string()), }, r#"{"time":"2023-11-28T12:00:09Z","type":"function","record":"hello world"}"#, ), + // function (trailing zeros in the fraction) + function_millis: ( + LambdaTelemetry { + time: "2023-11-28T12:00:09.120Z".parse().unwrap(), + record: LambdaTelemetryRecord::Function("hello world".to_string()), + }, + r#"{"time":"2023-11-28T12:00:09.120Z","type":"function","record":"hello world"}"#, + ), // function (json) function_generic: ( LambdaTelemetry { - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::Function(true), }, r#"{"time":"2023-11-28T12:00:09Z","type":"function","record":true}"#, @@ -526,7 +537,7 @@ mod serialization_tests { // extension extension: ( LambdaTelemetry { - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::Extension("hello world".to_string()), }, r#"{"time":"2023-11-28T12:00:09Z","type":"extension","record":"hello world"}"#, @@ -534,7 +545,7 @@ mod serialization_tests { // extension (json) extension_generic: ( LambdaTelemetry { - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::Extension(true), }, r#"{"time":"2023-11-28T12:00:09Z","type":"extension","record":true}"#, @@ -542,7 +553,7 @@ mod serialization_tests { //platform.Start platform_start: ( LambdaTelemetry{ - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformStart { request_id: "459921b5-681c-4a96-beb0-81e0aa586026".to_string(), version: Some("$LATEST".to_string()), @@ -558,7 +569,7 @@ mod serialization_tests { // platform.initStart platform_init_start: ( LambdaTelemetry{ - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformInitStart { initialization_type: InitType::OnDemand, phase: InitPhase::Init, @@ -571,7 +582,7 @@ mod serialization_tests { // platform.runtimeDone platform_runtime_done: ( LambdaTelemetry{ - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformRuntimeDone { request_id: "459921b5-681c-4a96-beb0-81e0aa586026".to_string(), status: Status::Success, @@ -583,20 +594,12 @@ mod serialization_tests { spans: vec!( Span { name:"responseLatency".to_string(), - start: Utc - .with_ymd_and_hms(2022, 10, 21, 14, 5, 3) - .unwrap() - .checked_add_signed(TimeDelta::try_milliseconds(165).unwrap()) - .unwrap(), + start: "2022-10-21T14:05:03.165Z".parse().unwrap(), duration_ms: 2598.0 }, Span { name:"responseDuration".to_string(), - start: Utc - .with_ymd_and_hms(2022, 10, 21, 14, 5, 5) - .unwrap() - .checked_add_signed(TimeDelta::try_milliseconds(763).unwrap()) - .unwrap(), + start: "2022-10-21T14:05:05.763Z".parse().unwrap(), duration_ms: 0.0 }, ), @@ -612,7 +615,7 @@ mod serialization_tests { // platform.report platform_report: ( LambdaTelemetry{ - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformReport { request_id: "459921b5-681c-4a96-beb0-81e0aa586026".to_string(), status: Status::Success, @@ -638,7 +641,7 @@ mod serialization_tests { // platform.telemetrySubscription platform_telemetry_subscription: ( LambdaTelemetry{ - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformTelemetrySubscription { name: "my-extension".to_string(), state: "Subscribed".to_string(), @@ -650,7 +653,7 @@ mod serialization_tests { // platform.initRuntimeDone platform_init_runtime_done: ( LambdaTelemetry{ - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformInitRuntimeDone { initialization_type: InitType::OnDemand, status: Status::Success, @@ -664,7 +667,7 @@ mod serialization_tests { // platform.extension platform_extension: ( LambdaTelemetry { - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformExtension { name: "my-extension".to_string(), state: "Ready".to_string(), @@ -676,7 +679,7 @@ mod serialization_tests { // platform.initReport platform_init_report: ( LambdaTelemetry { - time: Utc.with_ymd_and_hms(2023, 11, 28, 12, 0, 9).unwrap(), + time: "2023-11-28T12:00:09Z".parse().unwrap(), record: LambdaTelemetryRecord::PlatformInitReport { initialization_type: InitType::OnDemand, phase: InitPhase::Init, diff --git a/lambda-http/Cargo.toml b/lambda-http/Cargo.toml index 245c126b0..27d9c32be 100644 --- a/lambda-http/Cargo.toml +++ b/lambda-http/Cargo.toml @@ -6,7 +6,7 @@ authors = [ "Harold Sun ", ] edition = "2021" -rust-version = "1.84.0" +rust-version = "1.85.0" description = "Application Load Balancer and API Gateway event types for AWS Lambda" keywords = ["AWS", "Lambda", "APIGateway", "ALB", "API"] license = "Apache-2.0" diff --git a/lambda-integration-tests/Cargo.toml b/lambda-integration-tests/Cargo.toml index 9a4d3056b..9532a8ef7 100644 --- a/lambda-integration-tests/Cargo.toml +++ b/lambda-integration-tests/Cargo.toml @@ -3,7 +3,7 @@ name = "lambda-integration-tests" version = "1.0.1" authors = ["Maxime David"] edition = "2021" -rust-version = "1.84.0" +rust-version = "1.85.0" description = "AWS Lambda Runtime integration tests" license = "Apache-2.0" repository = "https://github.com/aws/aws-lambda-rust-runtime" diff --git a/lambda-runtime-api-client/Cargo.toml b/lambda-runtime-api-client/Cargo.toml index 146f12e0c..3bb77b4fc 100644 --- a/lambda-runtime-api-client/Cargo.toml +++ b/lambda-runtime-api-client/Cargo.toml @@ -2,7 +2,7 @@ name = "lambda_runtime_api_client" version = "1.1.1" edition = "2021" -rust-version = "1.84.0" +rust-version = "1.85.0" authors = [ "David Calavera ", "Harold Sun ", diff --git a/lambda-runtime/Cargo.toml b/lambda-runtime/Cargo.toml index b4876663b..e710037e3 100644 --- a/lambda-runtime/Cargo.toml +++ b/lambda-runtime/Cargo.toml @@ -7,7 +7,7 @@ authors = [ ] description = "AWS Lambda Runtime" edition = "2021" -rust-version = "1.84.0" +rust-version = "1.85.0" license = "Apache-2.0" repository = "https://github.com/aws/aws-lambda-rust-runtime" categories = ["web-programming::http-server"]