a2a_protocol_server/otel/telemetry/langfuse.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Langfuse as the trace destination.
5//!
6//! Langfuse needs nothing vendor-specific from an agent: it ingests plain
7//! OTLP/HTTP and maps the semantic conventions this crate's spans carry. What
8//! it does need is configuration that is easy to get subtly wrong, and this
9//! preset is that configuration, read from the three variables Langfuse's own
10//! Python and JavaScript SDKs use — so an agent written in Rust is configured
11//! exactly like the Python agents next to it.
12//!
13//! Every fact below was read from Langfuse, not assumed: the endpoint path
14//! and transports from `langfuse.com/integrations/native/opentelemetry`, the
15//! metrics and logs behaviour from the server source
16//! (`web/src/pages/api/public/otel/v1/metrics/index.ts` accepts metrics and
17//! discards them; there is no logs route), at `langfuse/langfuse@1a21a42`.
18
19use base64::Engine as _;
20
21use super::TelemetryError;
22
23/// Where a self-hosted Langfuse listens when started from its own
24/// `docker-compose.yml`; [`Langfuse::from_env`]'s default.
25///
26/// Langfuse's own SDKs default to its cloud service instead. This preset
27/// does not, so that nothing is sent off the machine unless
28/// `LANGFUSE_BASE_URL` says where.
29pub const LANGFUSE_SELF_HOSTED: &str = "http://localhost:3000";
30
31/// Where traces go, and the project keys that authorise them.
32///
33/// Applying it with
34/// [`TelemetryBuilder::with_langfuse`](super::TelemetryBuilder::with_langfuse):
35///
36/// * sends **traces** to `{base_url}/api/public/otel/v1/traces` over
37/// OTLP/HTTP with protobuf bodies — Langfuse does not accept OTLP/gRPC —
38/// with `Authorization: Basic base64(public_key:secret_key)` and
39/// `x-langfuse-ingestion-version: 4`, which Langfuse's documentation asks
40/// for so that directly ingested spans are not delayed;
41/// * turns **metrics and logs** off by default, because Langfuse discards
42/// OTLP metrics and has no OTLP logs route. `OTEL_METRICS_EXPORTER=otlp`
43/// or `OTEL_LOGS_EXPORTER=otlp` turns them back on, towards the general
44/// `OTEL_EXPORTER_OTLP_*` endpoint — a collector, not Langfuse.
45///
46/// The preset's endpoint is set in code, so for traces it wins over
47/// `OTEL_EXPORTER_OTLP_ENDPOINT`. Its two headers are added to those in
48/// `OTEL_EXPORTER_OTLP_HEADERS`, and a header of the same name in the
49/// variable replaces the preset's; to send traces somewhere else, do not
50/// apply it.
51#[derive(Clone)]
52pub struct Langfuse {
53 base_url: String,
54 public_key: String,
55 secret_key: String,
56}
57
58impl std::fmt::Debug for Langfuse {
59 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60 f.debug_struct("Langfuse")
61 .field("base_url", &self.base_url)
62 .field("public_key", &self.public_key)
63 .field("secret_key", &"<redacted>")
64 .finish()
65 }
66}
67
68impl Langfuse {
69 /// A project on the Langfuse at `base_url` — a self-hosted instance such
70 /// as [`LANGFUSE_SELF_HOSTED`], or Langfuse Cloud
71 /// (`https://cloud.langfuse.com`, `https://us.cloud.langfuse.com`).
72 pub fn new(
73 base_url: impl Into<String>,
74 public_key: impl Into<String>,
75 secret_key: impl Into<String>,
76 ) -> Self {
77 Self {
78 base_url: base_url.into(),
79 public_key: public_key.into(),
80 secret_key: secret_key.into(),
81 }
82 }
83
84 /// Reads `LANGFUSE_PUBLIC_KEY`, `LANGFUSE_SECRET_KEY` and
85 /// `LANGFUSE_BASE_URL`, the variables Langfuse's SDKs read. The base URL
86 /// defaults to [`LANGFUSE_SELF_HOSTED`] — not to Langfuse Cloud, as
87 /// theirs does.
88 ///
89 /// # Errors
90 ///
91 /// [`TelemetryError::Config`] naming the key that is missing. The error
92 /// never contains a key's value.
93 pub fn from_env() -> Result<Self, TelemetryError> {
94 Self::from_lookup(&super::config::process_env)
95 }
96
97 pub(super) fn from_lookup(env: &super::config::Env) -> Result<Self, TelemetryError> {
98 let required = |name: &str| {
99 env(name).ok_or_else(|| {
100 TelemetryError::config(name, "", "required for Langfuse, and not set")
101 })
102 };
103 Ok(Self::new(
104 env("LANGFUSE_BASE_URL").unwrap_or_else(|| LANGFUSE_SELF_HOSTED.to_owned()),
105 required("LANGFUSE_PUBLIC_KEY")?,
106 required("LANGFUSE_SECRET_KEY")?,
107 ))
108 }
109
110 /// The OTLP/HTTP traces endpoint.
111 pub(super) fn traces_endpoint(&self) -> String {
112 format!(
113 "{}/api/public/otel/v1/traces",
114 self.base_url.trim_end_matches('/')
115 )
116 }
117
118 /// The headers every export carries.
119 pub(super) fn headers(&self) -> Vec<(String, String)> {
120 let credentials = base64::engine::general_purpose::STANDARD
121 .encode(format!("{}:{}", self.public_key, self.secret_key));
122 vec![
123 ("authorization".to_owned(), format!("Basic {credentials}")),
124 ("x-langfuse-ingestion-version".to_owned(), "4".to_owned()),
125 ]
126 }
127}
128
129#[cfg(test)]
130mod tests {
131 use super::*;
132 use std::collections::HashMap;
133
134 fn lookup(pairs: &'static [(&'static str, &'static str)]) -> Box<super::super::config::Env> {
135 let map: HashMap<&str, &str> = pairs.iter().copied().collect();
136 Box::new(move |k| map.get(k).map(|v| (*v).to_owned()))
137 }
138
139 #[test]
140 fn endpoint_is_the_otel_traces_route_whatever_the_trailing_slash() {
141 for base in ["http://localhost:3000", "http://localhost:3000/"] {
142 assert_eq!(
143 Langfuse::new(base, "pk", "sk").traces_endpoint(),
144 "http://localhost:3000/api/public/otel/v1/traces"
145 );
146 }
147 }
148
149 #[test]
150 fn headers_are_basic_auth_of_the_key_pair_and_ingestion_version_4() {
151 let headers = Langfuse::new(LANGFUSE_SELF_HOSTED, "pk-lf-1", "sk-lf-2").headers();
152 // base64("pk-lf-1:sk-lf-2"), computed independently with
153 // `printf 'pk-lf-1:sk-lf-2' | base64`.
154 assert_eq!(
155 headers,
156 vec![
157 (
158 "authorization".to_owned(),
159 "Basic cGstbGYtMTpzay1sZi0y".to_owned()
160 ),
161 ("x-langfuse-ingestion-version".to_owned(), "4".to_owned()),
162 ]
163 );
164 }
165
166 #[test]
167 fn from_env_defaults_the_base_url_and_names_a_missing_key_without_values() {
168 let lf = Langfuse::from_lookup(&*lookup(&[
169 ("LANGFUSE_PUBLIC_KEY", "pk"),
170 ("LANGFUSE_SECRET_KEY", "sk"),
171 ]))
172 .unwrap();
173 assert_eq!(lf.base_url, LANGFUSE_SELF_HOSTED);
174
175 let err = Langfuse::from_lookup(&*lookup(&[("LANGFUSE_PUBLIC_KEY", "pk-visible")]))
176 .unwrap_err()
177 .to_string();
178 assert!(err.contains("LANGFUSE_SECRET_KEY"), "{err}");
179 assert!(!err.contains("pk-visible"), "{err}");
180 }
181
182 #[test]
183 fn debug_never_prints_the_secret_key() {
184 let shown = format!(
185 "{:?}",
186 Langfuse::new(LANGFUSE_SELF_HOSTED, "pk", "sk-very-secret")
187 );
188 assert!(!shown.contains("sk-very-secret"), "{shown}");
189 // It still says what it is: the instance and the public key.
190 assert!(shown.contains(LANGFUSE_SELF_HOSTED), "{shown}");
191 assert!(shown.contains("\"pk\""), "{shown}");
192 assert!(shown.contains("<redacted>"), "{shown}");
193 }
194}