Skip to content
Closed
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
4 changes: 4 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion sentry-contexts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ rust-version = { workspace = true }
[dependencies]
sentry-core = { version = "0.47.0", path = "../sentry-core" }
libc = "0.2.66"

[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
hostname = "0.4"

[target."cfg(not(windows))".dependencies]
[target.'cfg(all(not(windows), not(target_arch = "wasm32")))'.dependencies]
uname = "0.1.1"

[target."cfg(windows)".dependencies]
Expand Down
20 changes: 19 additions & 1 deletion sentry-contexts/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,19 @@ mod model_support {
}

/// Returns the server name (hostname) if available.
#[cfg(not(target_arch = "wasm32"))]
pub fn server_name() -> Option<String> {
hostname::get().ok().and_then(|s| s.into_string().ok())
}

#[cfg(target_arch = "wasm32")]
pub fn server_name() -> Option<String> {
// TODO: What other options are available?
None
}

/// Returns the OS context
#[cfg(not(windows))]
#[cfg(all(not(windows), not(target_arch = "wasm32")))]
pub fn os_context() -> Option<Context> {
use uname::uname;
if let Ok(info) = uname() {
Expand Down Expand Up @@ -168,6 +175,17 @@ pub fn os_context() -> Option<Context> {
)
}

#[cfg(target_arch = "wasm32")]
pub fn os_context() -> Option<Context> {
Some(
OsContext {
name: Some("WASM".into()),
..Default::default()
}
.into(),
)
}

/// Returns the rust info.
pub fn rust_context() -> Context {
RuntimeContext {
Expand Down
1 change: 1 addition & 0 deletions sentry-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ serde = { version = "1.0.104", features = ["derive"] }
serde_json = { version = "1.0.46" }
url = { version = "2.1.1" }
uuid = { version = "1.0.0", features = ["v4", "serde"], optional = true }
chrono = { version = "0.4.44" }

[dev-dependencies]
# Because we re-export all the public API in `sentry`, we actually run all the
Expand Down
17 changes: 10 additions & 7 deletions sentry-core/src/batcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

use crate::client::TransportArc;
use crate::protocol::EnvelopeItem;
use crate::Envelope;
use chrono::{Duration, Utc};
use sentry_types::protocol::v7::Log;

// Flush when there's 100 items in the buffer
const MAX_ITEMS: usize = 100;
// Or when 5 seconds have passed from the last flush
const FLUSH_INTERVAL: Duration = Duration::from_secs(5);
const FLUSH_INTERVAL: Duration = Duration::seconds(5);

#[derive(Debug)]
struct BatchQueue<T> {
Expand Down Expand Up @@ -71,21 +71,24 @@ where
if *shutdown {
return;
}
let mut last_flush = Instant::now();
let mut last_flush = Utc::now();
loop {
let elapsed = Utc::now() - last_flush;
let timeout = FLUSH_INTERVAL
.checked_sub(last_flush.elapsed())
.unwrap_or_else(|| Duration::from_secs(0));
.checked_sub(&elapsed)
.unwrap_or_else(|| Duration::seconds(0))
.to_std()
.unwrap_or_else(|_| std::time::Duration::from_secs(0));
shutdown = cvar.wait_timeout(shutdown, timeout).unwrap().0;
if *shutdown {
return;
}
if last_flush.elapsed() >= FLUSH_INTERVAL {
if Utc::now() - last_flush >= FLUSH_INTERVAL {
Batcher::flush_queue_internal(
worker_queue.lock().unwrap(),
&worker_transport,
);
last_flush = Instant::now();
last_flush = Utc::now();
}
}
})
Expand Down
3 changes: 3 additions & 0 deletions sentry-core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,3 +163,6 @@ pub use sentry_types::protocol::v7::{Breadcrumb, Envelope, Level, User};

// utilities reused across integrations
pub mod utils;

#[doc(hidden)]
pub use crate::utils::now_system_time;
8 changes: 4 additions & 4 deletions sentry-core/src/logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ macro_rules! logger_log {
level: $level,
body: $msg.to_owned(),
trace_id: None,
timestamp: ::std::time::SystemTime::now(),
timestamp: $crate::now_system_time(),
severity_number: None,
attributes: $crate::protocol::Map::new(),
};
Expand Down Expand Up @@ -39,7 +39,7 @@ macro_rules! logger_log {
level: $level,
body: format!($fmt, $($arg),*),
trace_id: None,
timestamp: ::std::time::SystemTime::now(),
timestamp: $crate::now_system_time(),
severity_number: None,
attributes,
};
Expand All @@ -58,7 +58,7 @@ macro_rules! logger_log {
level: $level,
body: $msg.to_owned(),
trace_id: None,
timestamp: ::std::time::SystemTime::now(),
timestamp: $crate::now_system_time(),
severity_number: None,
#[allow(clippy::redundant_field_names)]
attributes: $attrs,
Expand Down Expand Up @@ -86,7 +86,7 @@ macro_rules! logger_log {
level: $level,
body: format!($fmt, $($arg),*),
trace_id: None,
timestamp: ::std::time::SystemTime::now(),
timestamp: $crate::now_system_time(),
severity_number: None,
#[allow(clippy::redundant_field_names)]
attributes: $attrs,
Expand Down
4 changes: 2 additions & 2 deletions sentry-core/src/performance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -898,7 +898,7 @@ impl Transaction {
/// This records the current timestamp as the end timestamp and sends the transaction together with
/// all finished child spans to Sentry.
pub fn finish(self) {
self.finish_with_timestamp(SystemTime::now());
self.finish_with_timestamp(crate::utils::now_system_time());
}

/// Starts a new child Span with the given `op` and `description`.
Expand Down Expand Up @@ -1149,7 +1149,7 @@ impl Span {
/// This will record the current timestamp as the end timestamp and add the span to the
/// transaction in which it was started.
pub fn finish(self) {
self.finish_with_timestamp(SystemTime::now());
self.finish_with_timestamp(crate::utils::now_system_time());
}

/// Starts a new child Span with the given `op` and `description`.
Expand Down
29 changes: 18 additions & 11 deletions sentry-core/src/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ mod session_impl {
use std::collections::HashMap;
use std::sync::{Arc, Condvar, Mutex, MutexGuard};
use std::thread::JoinHandle;
use std::time::{Duration, Instant, SystemTime};
use std::time::{Duration, SystemTime};

use chrono::{DateTime, Utc};

use crate::client::TransportArc;
use crate::clientoptions::SessionMode;
Expand All @@ -29,7 +31,7 @@ mod session_impl {
pub struct Session {
client: Arc<Client>,
session_update: SessionUpdate<'static>,
started: Instant,
started: DateTime<Utc>,
dirty: bool,
}

Expand Down Expand Up @@ -62,7 +64,7 @@ mod session_impl {
distinct_id,
sequence: None,
timestamp: None,
started: SystemTime::now(),
started: crate::utils::now_system_time(),
init: true,
duration: None,
status: SessionStatus::Ok,
Expand All @@ -74,7 +76,7 @@ mod session_impl {
user_agent: None,
},
},
started: Instant::now(),
started: Utc::now(),
dirty: true,
})
}
Expand Down Expand Up @@ -112,7 +114,8 @@ mod session_impl {
SessionStatus::Ok => SessionStatus::Exited,
s => s,
};
self.session_update.duration = Some(self.started.elapsed().as_secs_f64());
let elapsed = Utc::now() - self.started;
self.session_update.duration = Some(elapsed.as_seconds_f64());
self.session_update.status = status;
self.dirty = true;
}
Expand Down Expand Up @@ -214,23 +217,27 @@ mod session_impl {
if *shutdown {
return;
}
let mut last_flush = Instant::now();
let mut last_flush = Utc::now();
let flush_interval = chrono::Duration::from_std(FLUSH_INTERVAL).unwrap();
loop {
let timeout = FLUSH_INTERVAL
.checked_sub(last_flush.elapsed())
.unwrap_or_else(|| Duration::from_secs(0));
let elapsed = Utc::now() - last_flush;
let timeout = flush_interval
.checked_sub(&elapsed)
.unwrap_or_else(|| chrono::Duration::seconds(0))
.to_std()
.unwrap_or_else(|_| Duration::from_secs(0));
shutdown = cvar.wait_timeout(shutdown, timeout).unwrap().0;
if *shutdown {
return;
}
if last_flush.elapsed() < FLUSH_INTERVAL {
if Utc::now() - last_flush < flush_interval {
continue;
}
SessionFlusher::flush_queue_internal(
worker_queue.lock().unwrap(),
&worker_transport,
);
last_flush = Instant::now();
last_flush = Utc::now();
}
})
.unwrap();
Expand Down
12 changes: 12 additions & 0 deletions sentry-core/src/utils.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
//! Utilities reused across dependant crates and integrations.

use std::time::{Duration, SystemTime};

/// Returns the current wall-clock time as a [`std::time::SystemTime`], sourced from
/// [`chrono::Utc::now`] so it works on `wasm32-unknown-unknown` (where
/// [`std::time::SystemTime::now`] panics).
pub fn now_system_time() -> std::time::SystemTime {
let now = chrono::Utc::now();
let secs = now.timestamp() as u64;
let nanos = now.timestamp_subsec_nanos();
SystemTime::UNIX_EPOCH + Duration::new(secs, nanos)
}

const SENSITIVE_HEADERS_UPPERCASE: &[&str] = &[
"AUTHORIZATION",
"PROXY_AUTHORIZATION",
Expand Down
9 changes: 5 additions & 4 deletions sentry-log/src/converters.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use sentry_core::protocol::{Event, Value};
#[cfg(feature = "logs")]
use sentry_core::protocol::{Log, LogAttribute, LogLevel};
use sentry_core::{
protocol::{Log, LogAttribute, LogLevel},
utils::now_system_time,
};
use sentry_core::{Breadcrumb, Level};
use std::collections::BTreeMap;
#[cfg(feature = "logs")]
use std::time::SystemTime;

/// Converts a [`log::Level`] to a Sentry [`Level`], used for [`Event`] and [`Breadcrumb`].
pub fn convert_log_level(level: log::Level) -> Level {
Expand Down Expand Up @@ -160,7 +161,7 @@ pub fn log_from_record(record: &log::Record<'_>) -> Log {
level: convert_log_level_to_sentry_log_level(record.level()),
body: format!("{}", record.args()),
trace_id: None,
timestamp: SystemTime::now(),
timestamp: now_system_time(),
severity_number: None,
attributes,
}
Expand Down
3 changes: 2 additions & 1 deletion sentry-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ rand = "0.9.3"
serde = { version = "1.0.104", features = ["derive"] }
serde_json = "1.0.46"
thiserror = "2.0.12"
time = { version = "0.3.47", features = ["formatting", "parsing"] }
time = { version = "0.3.47", default-features = false, features = ["formatting", "parsing"] }
url = { version = "2.1.1", features = ["serde"] }
uuid = { version = "1.0.0", features = ["serde"] }
chrono = { version = "0.4.44" }

[dev-dependencies]
rstest = "0.25.0"
4 changes: 2 additions & 2 deletions sentry-types/src/auth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use url::form_urlencoded;

use crate::dsn::Dsn;
use crate::protocol;
use crate::utils::{datetime_to_timestamp, timestamp_to_datetime};
use crate::utils::{datetime_to_timestamp, now_system_time, timestamp_to_datetime};

/// Represents an auth header parsing error.
#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
Expand Down Expand Up @@ -175,7 +175,7 @@ impl FromStr for Auth {

pub(crate) fn auth_from_dsn_and_client(dsn: &Dsn, client: Option<&str>) -> Auth {
Auth {
timestamp: Some(SystemTime::now()),
timestamp: Some(now_system_time()),
client: client.map(|x| x.to_string()),
version: protocol::LATEST,
key: dsn.public_key().to_string(),
Expand Down
2 changes: 1 addition & 1 deletion sentry-types/src/protocol/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ pub struct SessionUpdate<'a> {
pub timestamp: Option<SystemTime>,

/// The timestamp of when the session itself started.
#[serde(default = "SystemTime::now", with = "ts_rfc3339")]
#[serde(default = "crate::utils::now_system_time", with = "ts_rfc3339")]
pub started: SystemTime,

/// A flag that indicates that this is the initial transmission of the session.
Expand Down
Loading
Loading