teksilo_analytics_otlp/lib.rs
1// SPDX-License-Identifier: MPL-2.0
2// SPDX-FileCopyrightText: 2026 FernTech
3
4//! `teksilo-analytics-otlp` — OpenTelemetry-compatible analytics
5//! adapter for Teksilo.
6//!
7//! Speaks **OTLP/HTTP logs** over **JSON**. Works with any
8//! OTel-compatible collector — `otelcol-contrib`, Honeycomb,
9//! self-hosted Tempo+Loki via the OTel collector's HTTP receiver.
10//!
11//! # Mapping
12//!
13//! ```text
14//! Teksilo Event OTLP LogRecord
15//! ──────────────────────── ────────────────────────────────────
16//! event.name body.stringValue
17//! event.category attributes["teksilo.category"]
18//! event.timestamp timeUnixNano (string, OTLP/JSON)
19//! event.install_id resource.service.instance.id (when set)
20//! event.session_id attributes["teksilo.session_id"]
21//! event.props.<key> attributes["teksilo.<key>"]
22//! event.schema_version attributes["teksilo.schema_version"]
23//! ```
24//!
25//! Anonymous-mode batches (no `install_id`) omit
26//! `service.instance.id`; the OTel collector treats them as
27//! aggregate logs.
28//!
29//! # Quick start
30//!
31//! ```ignore
32//! use teksilo_analytics_otlp::OtlpAdapter;
33//! use std::rc::Rc;
34//!
35//! let adapter = Rc::new(
36//! OtlpAdapter::builder()
37//! .endpoint("http://127.0.0.1:4318/v1/logs")
38//! .service_name("my.app")
39//! .service_version(env!("CARGO_PKG_VERSION"))
40//! .header("x-honeycomb-team", std::env::var("HONEYCOMB_API_KEY").unwrap())
41//! .build(),
42//! ) as Rc<dyn teksilo_telemetry::UsageReporter>;
43//! ```
44//!
45//! # Fetch + erase
46//!
47//! Backend-dependent — the OTLP spec has no fetch or delete RPC.
48//! The adapter returns
49//! `TelemetryError::FetchUnsupportedByBackend` /
50//! `ErasureUnsupportedByBackend` by default. Operators with a
51//! self-hosted Tempo+Loki + an HTTP-side delete API can subclass
52//! the adapter (or wait for a future user-provided
53//! `EraseEndpoint`/`QueryEndpoint` injection point — tracked under
54//! future work).
55//!
56//! # Queue durability
57//!
58//! Unlike `teksilo-analytics-plausible` and `teksilo-analytics-native`,
59//! this adapter has **no built-in persistent queue**. Pending
60//! events live in an in-memory `VecDeque` and are lost on hard
61//! exit.
62//!
63//! This is an intentional design decision, not an oversight:
64//!
65//! 1. **The OTel deployment model owns durability.** OTLP is
66//! designed to talk to a *collector* — typically `otelcol` or
67//! `otelcol-contrib` running as a sidecar, system service, or
68//! on `localhost:4318`. The collector itself buffers, retries,
69//! and persists (via the `file_storage` extension or its built-
70//! in queue). Layering a second durability tier inside the
71//! desktop adapter duplicates work the collector already does.
72//! 2. **Remote-collector scenarios are atypical for desktop apps.**
73//! When an app talks straight to a remote OTLP endpoint (e.g.
74//! Honeycomb, Grafana Cloud), short network blips are absorbed
75//! by the in-memory queue's retry/backoff loop. Multi-hour
76//! offline buffering is not the OTLP HTTP-logs use case.
77//!
78//! Operators who *need* client-side durability against hard
79//! exits can fall back to a local collector with a `file_storage`
80//! exporter — the same persistence guarantee the redb-backed
81//! adapters provide, but at the right layer of the stack.
82//!
83//! If a future use case demands client-side durability (offline
84//! laptops with no local collector), exposing
85//! `OtlpAdapterBuilder::queue(Arc<dyn EventQueue>)` matching the
86//! Plausible/Teksilo shape is straightforward — the worker already
87//! owns the only `VecDeque` site to swap.
88
89mod config;
90mod transport;
91mod wire;
92mod worker;
93
94pub use config::OtlpConfig;
95
96use std::sync::Arc;
97use std::sync::atomic::Ordering;
98use std::sync::mpsc;
99use std::thread::JoinHandle;
100use std::time::Duration;
101
102use teksilo_core::telemetry::{
103 ConsentScope, Event, RemoteDataExport, TelemetryError, UsageReporter,
104};
105
106use crate::worker::{WorkerCommand, WorkerStats, spawn_worker};
107
108pub struct OtlpAdapter {
109 config: OtlpConfig,
110 worker_tx: mpsc::Sender<WorkerCommand>,
111 worker_handle: Option<JoinHandle<()>>,
112 stats: Arc<WorkerStats>,
113}
114
115impl OtlpAdapter {
116 pub fn builder() -> OtlpAdapterBuilder {
117 OtlpAdapterBuilder::default()
118 }
119
120 pub fn endpoint(&self) -> &str {
121 &self.config.endpoint
122 }
123
124 pub fn events_accepted(&self) -> usize {
125 self.stats.accepted.load(Ordering::Relaxed)
126 }
127
128 pub fn events_dropped(&self) -> usize {
129 self.stats.dropped.load(Ordering::Relaxed)
130 }
131
132 pub fn events_queued(&self) -> usize {
133 self.stats.queued.load(Ordering::Relaxed)
134 }
135
136 fn send(&self, cmd: WorkerCommand) {
137 let _ = self.worker_tx.send(cmd);
138 }
139}
140
141impl std::fmt::Debug for OtlpAdapter {
142 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143 f.debug_struct("OtlpAdapter")
144 .field("endpoint", &self.config.endpoint)
145 .field("service_name", &self.config.service_name)
146 .field("accepted", &self.events_accepted())
147 .field("dropped", &self.events_dropped())
148 .field("queued", &self.events_queued())
149 .finish()
150 }
151}
152
153impl UsageReporter for OtlpAdapter {
154 fn record(&self, event: &Event<'_>) {
155 self.send(WorkerCommand::Record(event.to_owned()));
156 }
157
158 fn flush(&self) -> Result<(), TelemetryError> {
159 let (tx, rx) = mpsc::sync_channel(1);
160 self.send(WorkerCommand::Flush(tx));
161 match rx.recv_timeout(self.config.request_timeout * 3) {
162 Ok(Ok(())) => Ok(()),
163 Ok(Err(e)) => Err(TelemetryError::Other(e)),
164 Err(_) => Err(TelemetryError::Other("flush timed out".into())),
165 }
166 }
167
168 fn discard_pending(&self) -> Result<(), TelemetryError> {
169 self.send(WorkerCommand::Discard);
170 Ok(())
171 }
172
173 fn supported_scopes(&self) -> ConsentScope {
174 // OTel collectors are general-purpose — they accept whatever
175 // we send. Returning `all()` lets the privacy widget show
176 // every per-scope toggle. Operators can constrain at the
177 // collector side via processors / attributes filters.
178 ConsentScope::all()
179 }
180
181 fn install_id(&self) -> Option<&str> {
182 // The adapter is stateless w.r.t. install_id — it picks the
183 // value off whatever event flows through. App-side
184 // pseudonymous-mode sets install_id on the event before
185 // record(); anonymous-mode events have None.
186 None
187 }
188
189 fn endpoint(&self) -> &str {
190 &self.config.endpoint
191 }
192
193 fn adapter_name(&self) -> &'static str {
194 "otlp"
195 }
196
197 fn fetch_remote_data(&self) -> Result<RemoteDataExport, TelemetryError> {
198 // OTLP has no fetch path. Self-hosted Tempo+Loki can be
199 // queried via LogQL but the URL + auth shape is operator-
200 // specific. Future work: accept
201 // a `QueryEndpoint` config that operators wire to their
202 // backend's read API.
203 Err(TelemetryError::FetchUnsupportedByBackend)
204 }
205
206 fn erase_remote_data(&self) -> Result<(), TelemetryError> {
207 Err(TelemetryError::ErasureUnsupportedByBackend)
208 }
209}
210
211impl Drop for OtlpAdapter {
212 fn drop(&mut self) {
213 let _ = self.worker_tx.send(WorkerCommand::Shutdown);
214 if let Some(handle) = self.worker_handle.take() {
215 let _ = handle.join();
216 }
217 }
218}
219
220#[derive(Default)]
221pub struct OtlpAdapterBuilder {
222 config: OtlpConfig,
223}
224
225impl std::fmt::Debug for OtlpAdapterBuilder {
226 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
227 f.debug_struct("OtlpAdapterBuilder")
228 .field("endpoint", &self.config.endpoint)
229 .field("service_name", &self.config.service_name)
230 .finish()
231 }
232}
233
234impl OtlpAdapterBuilder {
235 pub fn endpoint(mut self, url: impl Into<String>) -> Self {
236 self.config.endpoint = url.into();
237 self
238 }
239
240 /// Apply an operator-set runtime override iff non-empty —
241 /// matches the same shape as the Plausible/Teksilo adapters.
242 pub fn endpoint_override(mut self, url: impl Into<String>) -> Self {
243 let url = url.into();
244 if !url.is_empty() {
245 self.config.endpoint = url;
246 }
247 self
248 }
249
250 pub fn service_name(mut self, name: impl Into<String>) -> Self {
251 self.config.service_name = name.into();
252 self
253 }
254
255 pub fn service_version(mut self, version: impl Into<String>) -> Self {
256 self.config.service_version = version.into();
257 self
258 }
259
260 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
261 self.config.headers.push((name.into(), value.into()));
262 self
263 }
264
265 pub fn user_agent(mut self, ua: impl Into<String>) -> Self {
266 self.config.user_agent = ua.into();
267 self
268 }
269
270 pub fn max_batch_size(mut self, n: usize) -> Self {
271 self.config.max_batch_size = n.max(1);
272 self
273 }
274
275 pub fn flush_interval(mut self, d: Duration) -> Self {
276 self.config.flush_interval = d;
277 self
278 }
279
280 pub fn request_timeout(mut self, d: Duration) -> Self {
281 self.config.request_timeout = d;
282 self
283 }
284
285 pub fn max_queue_size(mut self, n: usize) -> Self {
286 self.config.max_queue_size = n.max(1);
287 self
288 }
289
290 pub fn build(self) -> OtlpAdapter {
291 assert!(
292 !self.config.endpoint.is_empty(),
293 "OtlpAdapter::builder().endpoint(...) is required",
294 );
295 assert!(
296 !self.config.service_name.is_empty(),
297 "OtlpAdapter::builder().service_name(...) is required",
298 );
299 let stats = Arc::new(WorkerStats::default());
300 let (tx, handle) = spawn_worker(self.config.clone(), stats.clone());
301 OtlpAdapter {
302 config: self.config,
303 worker_tx: tx,
304 worker_handle: Some(handle),
305 stats,
306 }
307 }
308}