Skip to content

Commit baea6f6

Browse files
committed
fix(opentelemetry): ensure timestamps are handled consistently
Previously the converted timestamp used an incorrect value for the calculated offset. Ref: LOG-19371
1 parent e7d4a61 commit baea6f6

File tree

1 file changed

+46
-14
lines changed

1 file changed

+46
-14
lines changed

src/sinks/opentelemetry/models.rs

+46-14
Original file line numberDiff line numberDiff line change
@@ -91,11 +91,10 @@ pub fn value_to_otlp_array(values: Vec<Value>) -> OtlpArray {
9191
pub fn value_to_system_time(value: &Value) -> SystemTime {
9292
match value {
9393
Value::Timestamp(time) => {
94-
let now = SystemTime::now()
95-
.duration_since(SystemTime::UNIX_EPOCH)
96-
.unwrap();
94+
let mut now = SystemTime::now();
95+
let now_unix = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
9796

98-
let diff = now
97+
let diff = now_unix
9998
- Duration::from_nanos(
10099
time.to_owned()
101100
.timestamp_nanos_opt()
@@ -104,18 +103,15 @@ pub fn value_to_system_time(value: &Value) -> SystemTime {
104103
.unwrap(),
105104
);
106105

107-
let mut ts = SystemTime::now();
108-
ts.sub_assign(diff);
109-
ts
106+
now.sub_assign(diff);
107+
now
110108
}
111109
Value::Integer(time) => {
112-
let now = SystemTime::now()
113-
.duration_since(SystemTime::UNIX_EPOCH)
114-
.unwrap();
115-
let diff = now - Duration::from_millis((*time).try_into().unwrap());
116-
let mut ts = SystemTime::now();
117-
ts.sub_assign(diff);
118-
ts
110+
let mut now = SystemTime::now();
111+
let now_unix = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
112+
let diff = now_unix - Duration::from_millis((*time).try_into().unwrap());
113+
now.sub_assign(diff);
114+
now
119115
}
120116
_ => SystemTime::now(),
121117
}
@@ -230,3 +226,39 @@ pub trait OpentelemetryModelMatch {
230226
where
231227
Self: Sized;
232228
}
229+
230+
#[cfg(test)]
231+
mod test {
232+
233+
use super::*;
234+
use chrono::{NaiveDateTime, TimeZone, Utc};
235+
236+
#[test]
237+
fn test_value_to_system_time_timestamp() {
238+
let value = Value::Timestamp(
239+
Utc.from_utc_datetime(
240+
&NaiveDateTime::from_timestamp_opt(1_579_134_612_i64, 11_u32)
241+
.expect("timestamp should be a valid timestamp"),
242+
),
243+
);
244+
245+
let expected =
246+
SystemTime::UNIX_EPOCH + std::time::Duration::from_nanos(1_579_134_612_000_000_011);
247+
assert_eq!(value_to_system_time(&value), expected);
248+
}
249+
250+
#[test]
251+
fn test_value_to_system_time_int() {
252+
let value = Value::Integer(1_579_134_612);
253+
254+
let expected = SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(1_579_134_612);
255+
assert_eq!(value_to_system_time(&value), expected);
256+
}
257+
258+
#[test]
259+
fn test_value_to_system_time_invalid_default_now() {
260+
let value = Value::from("invalid".to_string());
261+
262+
assert!(matches!(value_to_system_time(&value), SystemTime { .. }));
263+
}
264+
}

0 commit comments

Comments
 (0)