Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent the potential for a panic in the string_to_timestamp coercions #205

Merged
merged 1 commit into from
Dec 11, 2024
Merged
Show file tree
Hide file tree
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
25 changes: 15 additions & 10 deletions src/coercions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ fn apply_coercion(value: &mut Value, node: &CoercionNode) {
}
}

/// Convert a given datetime looking string into microseconds using chrono's [DateTime] parsing
///
/// Since this will convert to microseconds, if the value is outside of the realm of conversion a None is returned
fn string_to_timestamp(string: &str) -> Option<Value> {
let parsed = DateTime::from_str(string);
if let Err(e) = parsed {
Expand All @@ -131,23 +134,25 @@ fn string_to_timestamp(string: &str) -> Option<Value> {
e
)
}
parsed.ok().map(|dt: DateTime<Utc>| {
Value::Number(
(dt.timestamp_nanos_opt()
.expect("Failed to turn timestamp nanoseconds")
/ 1000)
.into(),
)
})
parsed
.ok()
.map(|dt: DateTime<Utc>| Value::Number(dt.timestamp_micros().into()))
}

#[cfg(test)]
mod tests {

use super::*;
// use maplit::hashmap;
use serde_json::json;

#[test]
fn test_string_to_timestamp() {
let result = string_to_timestamp("2010-01-01T22:11:58Z");
assert!(result.is_some());
// exceeds nanos size
let result = string_to_timestamp("2400-01-01T22:11:58Z");
assert!(result.is_some());
}

lazy_static! {
static ref SCHEMA: Value = json!({
"type": "struct",
Expand Down
3 changes: 1 addition & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -476,8 +476,7 @@ fn convert_matches_to_message_format(
.map(MessageFormat::Avro);
}

return to_schema_source(ingest_matches.get_one::<String>("json"), true)
.map(MessageFormat::Json);
to_schema_source(ingest_matches.get_one::<String>("json"), true).map(MessageFormat::Json)
}

#[cfg(test)]
Expand Down
Loading