Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(error-tracking): bump posthog-rs to 0.12 and add common-posthog (#63355)

Catalin Irimie222f8f2e5dd9
diff --git a/rust/Cargo.lock b/rust/Cargo.lock
index 36ed801bc97e..9c4fe571fc31 100644
--- a/rust/Cargo.lock
+++ b/rust/Cargo.lock
@@ -1460,6 +1460,15 @@ dependencies = [
"generic-array",
]
+[[package]]
+name = "block2"
+version = "0.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5"
+dependencies = [
+ "objc2",
+]
+
[[package]]
name = "blocking"
version = "1.6.2"
@@ -2278,6 +2287,16 @@ dependencies = [
"tokio",
]
+[[package]]
+name = "common-posthog"
+version = "0.1.0"
+dependencies = [
+ "posthog-rs 0.12.0",
+ "serde_json",
+ "tokio",
+ "tracing",
+]
+
[[package]]
name = "common-profiler"
version = "0.1.0"
@@ -2698,6 +2717,7 @@ dependencies = [
"common-dns",
"common-kafka",
"common-metrics",
+ "common-posthog",
"common-redis",
"common-types",
"cymbal-proto",
@@ -2711,7 +2731,7 @@ dependencies = [
"metrics",
"mockall",
"moka",
- "posthog-rs 0.3.7",
+ "posthog-rs 0.12.0",
"posthog-symbol-data",
"proguard",
"rand 0.8.5",
@@ -2755,13 +2775,13 @@ dependencies = [
"axum 0.7.9",
"common-alloc",
"common-metrics",
+ "common-posthog",
"cymbal",
"cymbal-proto",
"envconfig",
"futures",
"metrics",
"personhog-common",
- "posthog-rs 0.3.7",
"serde_json",
"subtle",
"tokio",
@@ -3075,6 +3095,16 @@ dependencies = [
"winapi",
]
+[[package]]
+name = "dispatch2"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"
+dependencies = [
+ "bitflags 2.11.0",
+ "objc2",
+]
+
[[package]]
name = "displaydoc"
version = "0.2.5"
@@ -3202,6 +3232,7 @@ dependencies = [
"common-continuous-profiling",
"common-kafka",
"common-metrics",
+ "common-posthog",
"common-types",
"envconfig",
"futures",
@@ -3209,7 +3240,6 @@ dependencies = [
"leaky-bucket",
"metrics",
"moka",
- "posthog-rs 0.3.7",
"rand 0.8.5",
"reqwest 0.12.28",
"serde",
@@ -5191,6 +5221,55 @@ dependencies = [
"jiff-tzdb",
]
+[[package]]
+name = "jni"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498"
+dependencies = [
+ "cfg-if",
+ "combine",
+ "jni-macros",
+ "jni-sys",
+ "log",
+ "simd_cesu8",
+ "thiserror 2.0.18",
+ "walkdir",
+ "windows-link",
+]
+
+[[package]]
+name = "jni-macros"
+version = "0.22.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "rustc_version",
+ "simd_cesu8",
+ "syn 2.0.117",
+]
+
+[[package]]
+name = "jni-sys"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2"
+dependencies = [
+ "jni-sys-macros",
+]
+
+[[package]]
+name = "jni-sys-macros"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"
+dependencies = [
+ "quote",
+ "syn 2.0.117",
+]
+
[[package]]
name = "jobserver"
version = "0.1.34"
@@ -5599,9 +5678,9 @@ checksum = "2c4a545a15244c7d945065b5d392b2d2d7f21526fba56ce51467b06ed445e8f7"
[[package]]
name = "libc"
-version = "0.2.185"
+version = "0.2.186"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "52ff2c0fe9bc6cb6b14a0592c2ff4fa9ceb83eea9db979b0487cd054946a2b8f"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
[[package]]
name = "libflate"
@@ -6261,6 +6340,18 @@ dependencies = [
"libc",
]
+[[package]]
+name = "nix"
+version = "0.31.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"
+dependencies = [
+ "bitflags 2.11.0",
+ "cfg-if",
+ "cfg_aliases",
+ "libc",
+]
+
[[package]]
name = "no-std-compat"
version = "0.4.1"
@@ -6450,6 +6541,165 @@ dependencies = [
"syn 2.0.117",
]
+[[package]]
+name = "objc2"
+version = "0.6.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3a12a8ed07aefc768292f076dc3ac8c48f3781c8f2d5851dd3d98950e8c5a89f"
+dependencies = [
+ "objc2-encode",
+]
+
+[[package]]
+name = "objc2-cloud-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"
+dependencies = [
+ "bitflags 2.11.0",
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-data"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"
+dependencies = [
+ "bitflags 2.11.0",
+ "dispatch2",
+ "objc2",
+]
+
+[[package]]
+name = "objc2-core-graphics"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"
+dependencies = [
+ "bitflags 2.11.0",
+ "dispatch2",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-io-surface",
+]
+
+[[package]]
+name = "objc2-core-image"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-location"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-core-text"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"
+dependencies = [
+ "bitflags 2.11.0",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+]
+
+[[package]]
+name = "objc2-encode"
+version = "4.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33"
+
+[[package]]
+name = "objc2-foundation"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"
+dependencies = [
+ "bitflags 2.11.0",
+ "block2",
+ "libc",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-io-surface"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"
+dependencies = [
+ "bitflags 2.11.0",
+ "objc2",
+ "objc2-core-foundation",
+]
+
+[[package]]
+name = "objc2-quartz-core"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"
+dependencies = [
+ "bitflags 2.11.0",
+ "objc2",
+ "objc2-core-foundation",
+ "objc2-foundation",
+]
+
+[[package]]
+name = "objc2-ui-kit"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"
+dependencies = [
+ "bitflags 2.11.0",
+ "block2",
+ "objc2",
+ "objc2-cloud-kit",
+ "objc2-core-data",
+ "objc2-core-foundation",
+ "objc2-core-graphics",
+ "objc2-core-image",
+ "objc2-core-location",
+ "objc2-core-text",
+ "objc2-foundation",
+ "objc2-quartz-core",
+ "objc2-user-notifications",
+]
+
+[[package]]
+name = "objc2-user-notifications"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"
+dependencies = [
+ "objc2",
+ "objc2-foundation",
+]
+
[[package]]
name = "object"
version = "0.37.3"
@@ -6712,6 +6962,22 @@ dependencies = [
"num-traits",
]
+[[package]]
+name = "os_info"
+version = "3.15.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9cf20a545b305cf1da722b236b5155c9bb35f1d5ceb28c048bd96ca842f41b5b"
+dependencies = [
+ "android_system_properties",
+ "log",
+ "nix 0.31.3",
+ "objc2",
+ "objc2-foundation",
+ "objc2-ui-kit",
+ "serde",
+ "windows-sys 0.61.2",
+]
+
[[package]]
name = "outref"
version = "0.5.2"
@@ -7333,29 +7599,36 @@ dependencies = [
[[package]]
name = "posthog-rs"
-version = "0.3.7"
+version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "610d236077c94c96194b0d2b40989bda4bf8faf60e15a0da6ef8ffd4c78f6c1c"
+checksum = "0dd5b47b6122821d9e26bd0ebbe76a3631b42341978e2da3a42ab26750a1ba7e"
dependencies = [
"chrono",
"derive_builder",
+ "regex",
"reqwest 0.11.27",
"semver",
"serde",
"serde_json",
+ "sha1",
+ "tokio",
+ "tracing",
"uuid",
]
[[package]]
name = "posthog-rs"
-version = "0.4.2"
+version = "0.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0dd5b47b6122821d9e26bd0ebbe76a3631b42341978e2da3a42ab26750a1ba7e"
+checksum = "24e1beb349e47c45a4ffdee65e8c096ff0022c0a4d6c566cacdf50f553427fb3"
dependencies = [
+ "backtrace",
"chrono",
"derive_builder",
+ "flate2",
+ "os_info",
"regex",
- "reqwest 0.11.27",
+ "reqwest 0.13.4",
"semver",
"serde",
"serde_json",
@@ -8065,6 +8338,7 @@ version = "0.11.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f1906b49b0c3bc04b5fe5d86a77925ae6524a19b816ae38ce1e426255f1d8a31"
dependencies = [
+ "aws-lc-rs",
"bytes",
"getrandom 0.3.4",
"lru-slab",
@@ -8504,6 +8778,45 @@ dependencies = [
"webpki-roots 1.0.6",
]
+[[package]]
+name = "reqwest"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
+dependencies = [
+ "base64 0.22.1",
+ "bytes",
+ "futures-channel",
+ "futures-core",
+ "futures-util",
+ "http 1.4.0",
+ "http-body 1.0.1",
+ "http-body-util",
+ "hyper 1.9.0",
+ "hyper-rustls 0.27.7",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "quinn",
+ "rustls 0.23.37",
+ "rustls-pki-types",
+ "rustls-platform-verifier",
+ "serde",
+ "serde_json",
+ "sync_wrapper 1.0.2",
+ "tokio",
+ "tokio-rustls 0.26.4",
+ "tower 0.5.3",
+ "tower-http 0.6.8",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
[[package]]
name = "rfc6979"
version = "0.3.1"
@@ -8798,6 +9111,33 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rustls-platform-verifier"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "26d1e2536ce4f35f4846aa13bff16bd0ff40157cdb14cc056c7b14ba41233ba0"
+dependencies = [
+ "core-foundation 0.10.1",
+ "core-foundation-sys",
+ "jni",
+ "log",
+ "once_cell",
+ "rustls 0.23.37",
+ "rustls-native-certs 0.8.3",
+ "rustls-platform-verifier-android",
+ "rustls-webpki 0.103.9",
+ "security-framework 3.7.0",
+ "security-framework-sys",
+ "webpki-root-certs",
+ "windows-sys 0.61.2",
+]
+
+[[package]]
+name = "rustls-platform-verifier-android"
+version = "0.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f87165f0995f63a9fbeea62b64d10b4d9d8e78ec6d7d51fb2125fda7bb36788f"
+
[[package]]
name = "rustls-webpki"
version = "0.101.7"
@@ -9338,6 +9678,16 @@ version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e320a6c5ad31d271ad523dcf3ad13e2767ad8b1cb8f047f75a8aeaf8da139da2"
+[[package]]
+name = "simd_cesu8"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33"
+dependencies = [
+ "rustc_version",
+ "simdutf8",
+]
+
[[package]]
name = "simdutf8"
version = "0.1.5"
@@ -10866,15 +11216,20 @@ version = "0.6.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8"
dependencies = [
+ "async-compression",
"base64 0.22.1",
"bitflags 2.11.0",
"bytes",
+ "futures-core",
"futures-util",
"http 1.4.0",
"http-body 1.0.1",
+ "http-body-util",
"iri-string",
"mime",
"pin-project-lite",
+ "tokio",
+ "tokio-util",
"tower 0.5.3",
"tower-layer",
"tower-service",
@@ -11458,6 +11813,15 @@ dependencies = [
"wasm-bindgen",
]
+[[package]]
+name = "webpki-root-certs"
+version = "1.0.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f31141ce3fc3e300ae89b78c0dd67f9708061d1d2eda54b8209346fd6be9a92c"
+dependencies = [
+ "rustls-pki-types",
+]
+
[[package]]
name = "webpki-roots"
version = "0.25.4"
diff --git a/rust/Cargo.toml b/rust/Cargo.toml
index 2c34cb73fa81..70e074c4267d 100644
--- a/rust/Cargo.toml
+++ b/rust/Cargo.toml
@@ -19,6 +19,7 @@ members = [
"common/lifecycle",
"common/limiters",
"common/metrics",
+ "common/posthog",
"common/profiler",
"common/continuous_profiling",
"common/redis",
@@ -175,7 +176,7 @@ aws-smithy-runtime-api = { version = "1.11.5", features = ["client"] }
aws-smithy-http-client = { version = "1.1.11", features = ["rustls-aws-lc"] }
mockall = "0.13.0"
moka = { version = "0.12.15", features = ["sync", "future"] }
-posthog-rs = { version = "0.3.5", features = ["async-client"] }
+posthog-rs = { version = "0.12.0", features = ["async-client"] }
redis = { version = "0.32.7", features = [
"tokio-comp",
"cluster",
diff --git a/rust/common/posthog/Cargo.toml b/rust/common/posthog/Cargo.toml
new file mode 100644
index 000000000000..604e5fb121fd
--- /dev/null
+++ b/rust/common/posthog/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+name = "common-posthog"
+version = "0.1.0"
+edition = "2021"
+
+[lints]
+workspace = true
+
+[dependencies]
+posthog-rs = { workspace = true }
+serde_json = { workspace = true }
+tokio = { workspace = true }
+tracing = { workspace = true }
diff --git a/rust/common/posthog/src/lib.rs b/rust/common/posthog/src/lib.rs
new file mode 100644
index 000000000000..e52c30795559
--- /dev/null
+++ b/rust/common/posthog/src/lib.rs
@@ -0,0 +1,225 @@
+//! Internal PostHog telemetry for PostHog's own Rust services: global client
+//! initialization and manual `$exception` capture with a process-wide rate
+//! cap.
+
+use std::future::Future;
+use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::task::{Context, Waker};
+use std::time::Instant;
+
+use serde_json::Value;
+
+/// Hard cap on captured exceptions per process per minute. Bounds both outage
+/// storms (every request failing at once) and self-amplification: cymbal
+/// ingests the internal project's `$exception` events, i.e. its own captures.
+const MAX_CAPTURES_PER_MINUTE: u32 = 10;
+
+static SERVICE: OnceLock<ServiceContext> = OnceLock::new();
+static CAPTURE_WINDOW: RateWindow = RateWindow::new();
+static CLOCK_START: OnceLock<Instant> = OnceLock::new();
+
+struct ServiceContext {
+ service: &'static str,
+ pod: Option<String>,
+ region: Option<String>,
+}
+
+/// Initialize the global PostHog client used for internal service telemetry
+/// (product analytics events and exception capture).
+///
+/// `endpoint` accepts both a bare host (`https://us.i.posthog.com`) and the
+/// legacy full capture URLs still present in deployment config (`…/i/v0/e/`,
+/// `…/capture`); any capture path suffix is stripped before the host is
+/// handed to the SDK, which appends endpoint paths itself.
+///
+/// Without an API key the global client is disabled and every capture is a
+/// no-op.
+pub async fn init(
+ service: &'static str,
+ api_key: Option<&str>,
+ endpoint: &str,
+) -> Result<(), posthog_rs::Error> {
+ // A second init call keeps the first service identity.
+ drop(
+ SERVICE.set(ServiceContext {
+ service,
+ pod: std::env::var("POD_NAME")
+ .or_else(|_| std::env::var("HOSTNAME"))
+ .ok(),
+ region: std::env::var("POSTHOG_REGION").ok(),
+ }),
+ );
+
+ let Some(api_key) = api_key else {
+ posthog_rs::disable_global();
+ tracing::warn!("PostHog client disabled (no API key)");
+ return Ok(());
+ };
+
+ // Exclude this crate's own frames from in-app classification so captured
+ // stacks lead with the real service call site, not the shared wrapper.
+ let error_tracking = posthog_rs::ErrorTrackingOptionsBuilder::default()
+ .in_app_exclude_paths(vec!["common_posthog::".to_string()])
+ .build()
+ .expect("all error tracking options have defaults");
+ let options = posthog_rs::ClientOptionsBuilder::default()
+ .api_key(api_key.to_string())
+ .host(normalize_host(endpoint))
+ .error_tracking(error_tracking)
+ .build()
+ .expect("all client options have defaults");
+ posthog_rs::init_global(options).await?;
+ tracing::info!("PostHog client initialized");
+ Ok(())
+}
+
+/// Capture a handled error as a personless `$exception` event, fire and
+/// forget. Callers keep their `Arc` clone, so capturing never steals an error
+/// that is still needed for a response or log line.
+///
+/// Events are stamped with the service identity from [`init`] plus
+/// `properties`. At most [`MAX_CAPTURES_PER_MINUTE`] captures per process are
+/// sent; beyond that they are silently dropped.
+pub fn capture_exception<E>(
+ error: Arc<E>,
+ properties: impl IntoIterator<Item = (&'static str, Value)>,
+) where
+ E: std::error::Error + Send + Sync + 'static,
+{
+ if posthog_rs::global_is_disabled() {
+ return;
+ }
+
+ if !CAPTURE_WINDOW.allows(clock_window_minutes(), MAX_CAPTURES_PER_MINUTE) {
+ return;
+ }
+
+ // Strings and pre-built JSON values always serialize.
+ let prop_err = "string and JSON property values always serialize";
+ let mut options = posthog_rs::CaptureExceptionOptions::new();
+ if let Some(ctx) = SERVICE.get() {
+ options = options.property("service", ctx.service).expect(prop_err);
+ if let Some(pod) = &ctx.pod {
+ options = options.property("pod", pod.as_str()).expect(prop_err);
+ }
+ if let Some(region) = &ctx.region {
+ options = options.property("region", region.as_str()).expect(prop_err);
+ }
+ }
+ for (key, value) in properties {
+ options = options.property(key, value).expect(prop_err);
+ }
+
+ let send = async move {
+ if let Err(e) = posthog_rs::capture_exception_with(&*error, options).await {
+ tracing::error!(error = ?e, "Failed to capture exception to PostHog");
+ }
+ };
+
+ // The SDK builds the event (including the capture-site backtrace) eagerly,
+ // before its first await point. Polling once on the caller's stack makes
+ // that backtrace show real frames instead of a tokio worker; only the
+ // pending network send moves to a task.
+ let mut send = Box::pin(send);
+ let mut cx = Context::from_waker(Waker::noop());
+ if send.as_mut().poll(&mut cx).is_pending() {
+ tokio::spawn(send);
+ }
+}
+
+/// Strip a legacy capture path suffix from a configured PostHog endpoint,
+/// leaving the bare host the SDK expects.
+fn normalize_host(endpoint: &str) -> String {
+ let trimmed = endpoint.trim().trim_end_matches('/');
+ let trimmed = trimmed
+ .strip_suffix("/i/v0/e")
+ .or_else(|| trimmed.strip_suffix("/capture"))
+ .unwrap_or(trimmed);
+ trimmed.trim_end_matches('/').to_string()
+}
+
+fn clock_window_minutes() -> u64 {
+ CLOCK_START.get_or_init(Instant::now).elapsed().as_secs() / 60
+}
+
+/// Windowed counter for the capture cap. The reset is not atomic with the
+/// increment, so captures racing a window change can be over-allowed or
+/// over-suppressed by a few; the cap is a safety bound, not an exact quota.
+struct RateWindow {
+ window: AtomicU64,
+ count: AtomicU32,
+}
+
+impl RateWindow {
+ const fn new() -> Self {
+ Self {
+ window: AtomicU64::new(0),
+ count: AtomicU32::new(0),
+ }
+ }
+
+ fn allows(&self, window: u64, max: u32) -> bool {
+ if self.window.swap(window, Ordering::Relaxed) != window {
+ self.count.store(0, Ordering::Relaxed);
+ }
+ self.count.fetch_add(1, Ordering::Relaxed) < max
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn normalize_host_strips_capture_suffixes() {
+ let cases = [
+ ("https://us.i.posthog.com", "https://us.i.posthog.com"),
+ ("https://us.i.posthog.com/", "https://us.i.posthog.com"),
+ (
+ "https://us.i.posthog.com/i/v0/e/",
+ "https://us.i.posthog.com",
+ ),
+ (
+ "https://us.i.posthog.com/i/v0/e",
+ "https://us.i.posthog.com",
+ ),
+ (
+ "https://us.i.posthog.com/capture",
+ "https://us.i.posthog.com",
+ ),
+ (
+ "https://us.i.posthog.com/capture/",
+ "https://us.i.posthog.com",
+ ),
+ (" http://localhost:8010/i/v0/e/ ", "http://localhost:8010"),
+ (
+ "http://capture.posthog.svc:3000",
+ "http://capture.posthog.svc:3000",
+ ),
+ ];
+ for (input, expected) in cases {
+ assert_eq!(normalize_host(input), expected, "input: {input:?}");
+ }
+ }
+
+ #[test]
+ fn rate_window_caps_within_a_window() {
+ let limiter = RateWindow::new();
+ for _ in 0..3 {
+ assert!(limiter.allows(7, 3));
+ }
+ assert!(!limiter.allows(7, 3));
+ assert!(!limiter.allows(7, 3));
+ }
+
+ #[test]
+ fn rate_window_resets_on_new_window() {
+ let limiter = RateWindow::new();
+ for _ in 0..3 {
+ assert!(limiter.allows(1, 3));
+ }
+ assert!(!limiter.allows(1, 3));
+ assert!(limiter.allows(2, 3));
+ }
+}
diff --git a/rust/cymbal-resolution/Cargo.toml b/rust/cymbal-resolution/Cargo.toml
index 59c463f4f25b..f09e385368b4 100644
--- a/rust/cymbal-resolution/Cargo.toml
+++ b/rust/cymbal-resolution/Cargo.toml
@@ -10,13 +10,13 @@ cymbal-proto = { path = "../cymbal-proto" }
personhog-common = { path = "../personhog-common" }
common-alloc = { path = "../common/alloc" }
common-metrics = { path = "../common/metrics" }
+common-posthog = { path = "../common/posthog" }
async-stream = { workspace = true }
axum = { workspace = true }
envconfig = { workspace = true }
futures = { workspace = true }
metrics = { workspace = true }
-posthog-rs = { workspace = true }
serde_json = { workspace = true }
subtle = "2.6"
tokio = { workspace = true }
diff --git a/rust/cymbal-resolution/src/main.rs b/rust/cymbal-resolution/src/main.rs
index 6ab1b1773f96..a0fd35187bac 100644
--- a/rust/cymbal-resolution/src/main.rs
+++ b/rust/cymbal-resolution/src/main.rs
@@ -99,23 +99,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
}
async fn init_posthog_client(config: &CymbalConfig) {
- match &config.posthog_api_key {
- Some(key) => {
- let ph_config = posthog_rs::ClientOptionsBuilder::default()
- .api_key(key.clone())
- .api_endpoint(config.posthog_endpoint.clone())
- .build()
- .expect("Invalid PostHog client configuration");
- posthog_rs::init_global(ph_config)
- .await
- .expect("Failed to initialize PostHog client");
- tracing::info!("PostHog client initialized");
- }
- None => {
- posthog_rs::disable_global();
- tracing::warn!("PostHog client disabled");
- }
- }
+ common_posthog::init(
+ "cymbal-resolution",
+ config.posthog_api_key.as_deref(),
+ &config.posthog_endpoint,
+ )
+ .await
+ .expect("Failed to initialize PostHog client");
}
fn init_tracing() {
diff --git a/rust/cymbal/Cargo.toml b/rust/cymbal/Cargo.toml
index 910c0b0239c4..d899b091957d 100644
--- a/rust/cymbal/Cargo.toml
+++ b/rust/cymbal/Cargo.toml
@@ -20,6 +20,7 @@ common-kafka = { path = "../common/kafka" }
common-types = { path = "../common/types" }
common-dns = { path = "../common/dns" }
common-redis = { path = "../common/redis" }
+common-posthog = { path = "../common/posthog" }
cymbal-proto = { path = "../cymbal-proto" }
posthog-symbol-data = { path = "../common/symbol_data" }
hogvm = { path = "../common/hogvm" }
diff --git a/rust/cymbal/src/main.rs b/rust/cymbal/src/main.rs
index c3f4922af1c0..4179e2159821 100644
--- a/rust/cymbal/src/main.rs
+++ b/rust/cymbal/src/main.rs
@@ -2,7 +2,7 @@ use std::sync::Arc;
use cymbal::{app_context::AppContext, config::Config, server::start_server};
use tracing::level_filters::LevelFilter;
-use tracing::{error, info, warn};
+use tracing::{error, info};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
common_alloc::used!();
@@ -37,21 +37,13 @@ async fn main() {
}
};
- match &config.posthog_api_key {
- Some(key) => {
- let ph_config = posthog_rs::ClientOptionsBuilder::default()
- .api_key(key.clone())
- .api_endpoint(config.posthog_endpoint.clone())
- .build()
- .unwrap();
- posthog_rs::init_global(ph_config).await.unwrap();
- info!("Posthog client initialized");
- }
- None => {
- posthog_rs::disable_global();
- warn!("Posthog client disabled");
- }
- }
+ common_posthog::init(
+ "cymbal",
+ config.posthog_api_key.as_deref(),
+ &config.posthog_endpoint,
+ )
+ .await
+ .unwrap();
let context = Arc::new(AppContext::from_config(&config).await.unwrap());
diff --git a/rust/embedding-worker/Cargo.toml b/rust/embedding-worker/Cargo.toml
index bfaa8250a248..b8b601ad5460 100644
--- a/rust/embedding-worker/Cargo.toml
+++ b/rust/embedding-worker/Cargo.toml
@@ -17,10 +17,10 @@ common-alloc = { path = "../common/alloc" }
common-continuous-profiling = { path = "../common/continuous_profiling" }
common-kafka = { path = "../common/kafka" }
common-types = { path = "../common/types" }
+common-posthog = { path = "../common/posthog" }
anyhow = { workspace = true } # We use anyhow for now because we're in hack it ship it mode, real error types later
sqlx = { workspace = true }
uuid = { workspace = true }
-posthog-rs = { workspace = true }
futures.workspace = true
reqwest.workspace = true
tiktoken-rs.workspace = true
diff --git a/rust/embedding-worker/src/main.rs b/rust/embedding-worker/src/main.rs
index ae435b20dafa..735092d56d3d 100644
--- a/rust/embedding-worker/src/main.rs
+++ b/rust/embedding-worker/src/main.rs
@@ -20,7 +20,7 @@ use embedding_worker::{
use metrics::counter;
use tokio::task::JoinHandle;
use tracing::level_filters::LevelFilter;
-use tracing::{error, info, warn};
+use tracing::{error, info};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter, Layer};
use uuid::Uuid;
@@ -91,21 +91,13 @@ async fn main() {
}
};
- match &config.posthog_api_key {
- Some(key) => {
- let ph_config = posthog_rs::ClientOptionsBuilder::default()
- .api_key(key.clone())
- .api_endpoint(config.posthog_endpoint.clone())
- .build()
- .unwrap();
- posthog_rs::init_global(ph_config).await.unwrap();
- info!("Posthog client initialized");
- }
- None => {
- posthog_rs::disable_global();
- warn!("Posthog client disabled");
- }
- }
+ common_posthog::init(
+ "embedding-worker",
+ config.posthog_api_key.as_deref(),
+ &config.posthog_endpoint,
+ )
+ .await
+ .unwrap();
let context = Arc::new(AppContext::new(config.clone()).await.unwrap());