utopia_span/lib.rs
1//! Span tracing: record what one unit of work (a request, a job, a query) did
2//! as attributes on a span, and export the span when it finishes.
3//!
4//! [`Span::init`] starts a span and makes it the current span of the running
5//! task, so code anywhere below can add attributes with [`Span::add`] without
6//! holding it. [`Span::finish`] stamps the duration and level and hands the
7//! span to every registered [`Exporter`]: [`Stdout`] (JSON lines), [`Pretty`]
8//! (colourful terminal output) or [`Sentry`] (errors as Sentry issues). Spans
9//! carry W3C trace context, so a trace continues across services
10//! ([`Span::traceparent`], [`Span::init`] with a `traceparent` header).
11//!
12//! Where "current" lives is a [`Storage`]: [`Memory`] (one span per process),
13//! [`Task`] (one span per task) or [`Auto`] (the task's span inside a
14//! task scope, the process's otherwise), chosen once with
15//! [`Span::set_storage`].
16//!
17//! PHP: ports `utopia-php/span`.
18//!
19//! | PHP | Rust |
20//! |---|---|
21//! | `Span` (`new Span($action)`) | [`Span`] ([`Span::new`]) |
22//! | `Span::setStorage()`, `Span::setExporters()` | [`Span::set_storage`], [`Span::set_exporters`] |
23//! | `Span::init()`, `Span::current()`, `Span::add()`, `Span::traceparent()` | [`Span::init`], [`Span::current`], [`Span::add`], [`Span::current_traceparent`] |
24//! | `set()`, `get()`, `getAttributes()`, `getAction()`, `getTraceparent()` | [`Span::set`], [`Span::get`], [`Span::attributes`], [`Span::action`], [`Span::traceparent`] |
25//! | `setError()`, `getError()`, `finish()` | [`Span::set_error`], [`Span::error`], [`Span::finish`] / [`Span::finish_with`] |
26//! | `string\|int\|float\|bool\|null` attribute values | [`Value`] |
27//! | `\Throwable` | [`Failure`] |
28//! | `Level` | [`Level`] |
29//! | `Storage\Storage`, `Memory`, `Coroutine`, `Auto` | [`Storage`], [`Memory`], [`Task`], [`Auto`] |
30//! | `Exporter\Exporter`, `None`, `Stdout`, `Pretty` | [`Exporter`], [`exporter::None`], [`Stdout`], [`Pretty`] |
31//! | `Exporter\Sentry`, `SentryField`, `Sentry\Level` | [`Sentry`], [`exporter::SentryField`], [`exporter::SentryLevel`] |
32//!
33//! PHP: storage and exporters are static properties of `Span`; here they are
34//! process-wide too. A [`Span`] is a shared handle, as a PHP object is: every
35//! clone is the same span ([`Span::ptr_eq`]).
36//!
37//! ```
38//! use utopia_span::{Memory, Span};
39//! use std::sync::Arc;
40//!
41//! Span::set_storage(Some(Arc::new(Memory::new())));
42//!
43//! let span = Span::init("http.request", None);
44//! Span::add("http.method", "GET");
45//! Span::add("http.response.status_code", 200);
46//!
47//! assert_eq!(span.get("http.method"), "GET".into());
48//! assert_eq!(span.get("http.response.status_code"), 200.into());
49//! span.finish();
50//! assert!(Span::current().is_none());
51//! ```
52//!
53//! ```php
54//! use Utopia\Span\Span;
55//! use Utopia\Span\Storage\Memory;
56//!
57//! Span::setStorage(new Memory());
58//!
59//! $span = Span::init('http.request');
60//! Span::add('http.method', 'GET');
61//! Span::add('http.response.status_code', 200);
62//!
63//! echo $span->get('http.method'), "\n"; // GET
64//! echo $span->get('http.response.status_code'), "\n"; // 200
65//! $span->finish();
66//! var_dump(Span::current()); // NULL
67//! ```
68
69#![warn(missing_docs)]
70
71pub mod exporter;
72mod failure;
73mod storage;
74mod value;
75
76use std::sync::{Arc, Mutex, MutexGuard, RwLock};
77use std::time::{SystemTime, UNIX_EPOCH};
78
79pub use exporter::{Exporter, Pretty, Sentry, Stdout};
80pub use failure::{Failure, Frame};
81pub use storage::{Auto, Memory, Storage, Task};
82pub use value::Value;
83
84/// The getting started guide (`guide.md`), compiled and run with the doctests.
85#[cfg(doctest)]
86#[doc = include_str!("../guide.md")]
87pub struct GettingStarted;
88
89/// Why an exporter could not be created.
90#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
91pub enum Error {
92 /// An argument is invalid, such as a Sentry DSN without a project id.
93 ///
94 /// PHP: `\InvalidArgumentException`, with the same message.
95 #[error("{0}")]
96 InvalidArgument(&'static str),
97}
98
99impl Error {
100 /// The name of the PHP exception class this error matches.
101 ///
102 /// PHP: the class `utopia-php/span` throws.
103 ///
104 /// ```
105 /// use utopia_span::Error;
106 ///
107 /// assert_eq!(Error::InvalidArgument("Sentry DSN is required").php_class(), "InvalidArgumentException");
108 /// ```
109 pub fn php_class(&self) -> &'static str {
110 match self {
111 Error::InvalidArgument(_) => "InvalidArgumentException",
112 }
113 }
114}
115
116/// The severity of a span, from least to most severe.
117///
118/// PHP: `Utopia\Span\Level`. Names follow Grafana Loki's `detected_level`
119/// vocabulary (`warn`, not `warning`).
120#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
121pub enum Level {
122 /// `debug`.
123 Debug,
124 /// `info`: the level of a span finished without an error.
125 Info,
126 /// `warn`.
127 Warn,
128 /// `error`: the level of a span finished with an error.
129 Error,
130 /// `fatal`.
131 Fatal,
132}
133
134impl Level {
135 /// Every level, from least to most severe.
136 ///
137 /// PHP: `Level::cases()`.
138 pub const ALL: [Level; 5] = [Level::Debug, Level::Info, Level::Warn, Level::Error, Level::Fatal];
139
140 /// The level's name, as the `level` attribute holds it.
141 ///
142 /// PHP: `$level->value`.
143 ///
144 /// ```
145 /// use utopia_span::Level;
146 ///
147 /// assert_eq!(Level::Warn.as_str(), "warn");
148 /// ```
149 ///
150 /// ```php
151 /// use Utopia\Span\Level;
152 ///
153 /// echo Level::Warn->value, "\n"; // warn
154 /// ```
155 pub const fn as_str(self) -> &'static str {
156 match self {
157 Level::Debug => "debug",
158 Level::Info => "info",
159 Level::Warn => "warn",
160 Level::Error => "error",
161 Level::Fatal => "fatal",
162 }
163 }
164
165 /// The level named `name`, if any.
166 ///
167 /// PHP: `Level::tryFrom($name)` (`Level::from()` throws a `\ValueError`
168 /// where this returns `None`).
169 ///
170 /// ```
171 /// use utopia_span::Level;
172 ///
173 /// assert_eq!(Level::parse(b"error"), Some(Level::Error));
174 /// assert_eq!(Level::parse(b"warning"), None);
175 /// ```
176 ///
177 /// ```php
178 /// use Utopia\Span\Level;
179 ///
180 /// var_dump(Level::tryFrom('error') === Level::Error); // bool(true)
181 /// var_dump(Level::tryFrom('warning')); // NULL
182 /// ```
183 pub fn parse(name: &[u8]) -> Option<Level> {
184 Level::ALL.into_iter().find(|l| l.as_str().as_bytes() == name)
185 }
186}
187
188impl std::fmt::Display for Level {
189 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
190 f.write_str(self.as_str())
191 }
192}
193
194static STORAGE: RwLock<Option<Arc<dyn Storage>>> = RwLock::new(None);
195static EXPORTERS: RwLock<Vec<Arc<dyn Exporter>>> = RwLock::new(Vec::new());
196
197struct State {
198 /// Attributes in insertion order; setting a key again keeps its place.
199 attributes: Vec<(Box<str>, Value)>,
200 error: Option<Arc<Failure>>,
201}
202
203struct Inner {
204 action: Box<str>,
205 state: Mutex<State>,
206}
207
208/// One unit of work: an action, attributes, and the error it failed with, if
209/// any.
210///
211/// A new span has a random 128-bit trace id (`span.trace_id`), a random
212/// 64-bit span id (`span.id`), both in lowercase hex, and its start time in
213/// seconds since the epoch (`span.started_at`). A `Span` is a handle: clones
214/// share one span.
215///
216/// PHP: `Utopia\Span\Span`.
217///
218/// ```
219/// use utopia_span::{Span, Value};
220///
221/// let span = Span::new("db.query");
222/// span.set("db.table", "users").set("db.rows", 3);
223///
224/// assert_eq!(span.action(), "db.query");
225/// assert_eq!(span.get("db.rows"), Value::Int(3));
226/// assert_eq!(span.get("missing"), Value::Null);
227/// assert_eq!(span.get("span.trace_id").as_str().map(str::len), Some(32));
228/// ```
229///
230/// ```php
231/// use Utopia\Span\Span;
232///
233/// $span = new Span('db.query');
234/// $span->set('db.table', 'users')->set('db.rows', 3);
235///
236/// echo $span->getAction(), "\n"; // db.query
237/// echo $span->get('db.rows'), "\n"; // 3
238/// var_dump($span->get('missing')); // NULL
239/// echo strlen($span->get('span.trace_id')), "\n"; // 32
240/// ```
241#[derive(Clone)]
242pub struct Span(Arc<Inner>);
243
244impl std::fmt::Debug for Span {
245 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
246 let state = self.state();
247 f.debug_struct("Span").field("action", &self.0.action).field("attributes", &state.attributes).finish()
248 }
249}
250
251impl PartialEq for Span {
252 /// Whether both handles are the same span (PHP's `===`).
253 fn eq(&self, other: &Self) -> bool {
254 Arc::ptr_eq(&self.0, &other.0)
255 }
256}
257
258impl Default for Span {
259 /// A span of the action `unknown`.
260 fn default() -> Self {
261 Span::new("unknown")
262 }
263}
264
265fn hex(bytes: &[u8]) -> String {
266 const DIGITS: &[u8; 16] = b"0123456789abcdef";
267 let mut out = String::with_capacity(bytes.len() * 2);
268 for b in bytes {
269 out.push(DIGITS[usize::from(b >> 4)] as char);
270 out.push(DIGITS[usize::from(b & 15)] as char);
271 }
272 out
273}
274
275/// Seconds since the epoch, as PHP's `microtime(true)` (microseconds).
276fn microtime() -> f64 {
277 let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
278 now.as_secs() as f64 + f64::from(now.subsec_micros()) / 1e6
279}
280
281impl Span {
282 /// A new span of `action`, with new trace and span ids, started now. It
283 /// is not the current span: [`Span::init`] makes one current.
284 ///
285 /// PHP: `new Span($action)`.
286 pub fn new(action: impl Into<Box<str>>) -> Span {
287 let mut ids = [0u8; 24];
288 // The OS random source does not fail on supported platforms; zero ids
289 // would still be valid ones.
290 let _ = getrandom::fill(&mut ids);
291 let attributes = vec![
292 (Box::from("span.trace_id"), Value::from(hex(&ids[..16]))),
293 (Box::from("span.id"), Value::from(hex(&ids[16..]))),
294 (Box::from("span.started_at"), Value::Float(microtime())),
295 ];
296 Span(Arc::new(Inner { action: action.into(), state: Mutex::new(State { attributes, error: None }) }))
297 }
298
299 fn state(&self) -> MutexGuard<'_, State> {
300 self.0.state.lock().unwrap_or_else(|e| e.into_inner())
301 }
302
303 /// Whether `a` and `b` are the same span.
304 ///
305 /// PHP: `$a === $b`.
306 pub fn ptr_eq(a: &Span, b: &Span) -> bool {
307 Arc::ptr_eq(&a.0, &b.0)
308 }
309
310 /// Sets (or clears, with `None`) where the current span is kept. Call it
311 /// once at startup, before creating spans.
312 ///
313 /// PHP: `Span::setStorage($storage)`.
314 pub fn set_storage(storage: Option<Arc<dyn Storage>>) {
315 *STORAGE.write().unwrap_or_else(|e| e.into_inner()) = storage;
316 }
317
318 /// Replaces every exporter. Finished spans go to each exporter whose
319 /// [`Exporter::sample`] accepts them.
320 ///
321 /// PHP: `Span::setExporters(...$exporters)`.
322 pub fn set_exporters(exporters: Vec<Arc<dyn Exporter>>) {
323 *EXPORTERS.write().unwrap_or_else(|e| e.into_inner()) = exporters;
324 }
325
326 /// Starts a span of `action` and makes it the current span.
327 ///
328 /// A valid W3C `traceparent` header (`00-<32 hex>-<16 hex>-<2 hex>`)
329 /// continues its trace: the span takes its trace id, and its parent id
330 /// becomes `span.parent_id`. Anything else is ignored and the span starts
331 /// a new trace.
332 ///
333 /// PHP: `Span::init($action, $traceparent)`.
334 ///
335 /// ```
336 /// use utopia_span::{Span, Value};
337 ///
338 /// let span = Span::init("http.request", Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"));
339 /// assert_eq!(span.get("span.trace_id"), Value::from("0af7651916cd43dd8448eb211c80319c"));
340 /// assert_eq!(span.get("span.parent_id"), Value::from("b7ad6b7169203331"));
341 /// ```
342 ///
343 /// ```php
344 /// use Utopia\Span\Span;
345 ///
346 /// $span = Span::init('http.request', '00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01');
347 /// echo $span->get('span.trace_id'), "\n"; // 0af7651916cd43dd8448eb211c80319c
348 /// echo $span->get('span.parent_id'), "\n"; // b7ad6b7169203331
349 /// ```
350 pub fn init(action: impl Into<Box<str>>, traceparent: Option<&str>) -> Span {
351 let span = Span::new(action);
352 if let Some(traceparent) = traceparent {
353 let parts: Vec<&str> = traceparent.split('-').collect();
354 let xdigits = |s: &str, n: usize| s.len() == n && s.bytes().all(|b| b.is_ascii_hexdigit());
355 if parts.len() == 4
356 && parts[0] == "00"
357 && xdigits(parts[1], 32)
358 && xdigits(parts[2], 16)
359 && xdigits(parts[3], 2)
360 {
361 span.set("span.trace_id", parts[1]);
362 span.set("span.parent_id", parts[2]);
363 }
364 }
365 if let Some(storage) = STORAGE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
366 storage.set(Some(span.clone()));
367 }
368 span
369 }
370
371 /// The current span, if one is active.
372 ///
373 /// PHP: `Span::current()`.
374 pub fn current() -> Option<Span> {
375 STORAGE.read().unwrap_or_else(|e| e.into_inner()).as_ref()?.get()
376 }
377
378 /// Sets an attribute on the current span; does nothing when no span is
379 /// active.
380 ///
381 /// PHP: `Span::add($key, $value)`.
382 ///
383 /// ```
384 /// use std::sync::Arc;
385 /// use utopia_span::{Memory, Span, Value};
386 ///
387 /// Span::set_storage(Some(Arc::new(Memory::new())));
388 /// Span::add("ignored", 1); // no current span yet
389 ///
390 /// let span = Span::init("job", None);
391 /// Span::add("job.id", "a1");
392 /// assert_eq!(span.get("job.id"), Value::from("a1"));
393 /// ```
394 ///
395 /// ```php
396 /// use Utopia\Span\Span;
397 /// use Utopia\Span\Storage\Memory;
398 ///
399 /// Span::setStorage(new Memory());
400 /// Span::add('ignored', 1); // no current span yet
401 ///
402 /// $span = Span::init('job');
403 /// Span::add('job.id', 'a1');
404 /// echo $span->get('job.id'), "\n"; // a1
405 /// ```
406 pub fn add(key: &str, value: impl Into<Value>) {
407 if let Some(span) = Span::current() {
408 span.set(key, value);
409 }
410 }
411
412 /// The `traceparent` header of the current span, to propagate the trace
413 /// to the services this one calls.
414 ///
415 /// PHP: `Span::traceparent()`.
416 pub fn current_traceparent() -> Option<String> {
417 Span::current().map(|s| s.traceparent())
418 }
419
420 /// Sets an attribute. Setting a key again replaces its value in place;
421 /// the built-in `span.*` attributes can be replaced too.
422 ///
423 /// PHP: `$span->set($key, $value)`.
424 pub fn set(&self, key: &str, value: impl Into<Value>) -> &Self {
425 let value = value.into();
426 let mut state = self.state();
427 match state.attributes.iter_mut().find(|(k, _)| &**k == key) {
428 Some((_, v)) => *v = value,
429 None => state.attributes.push((Box::from(key), value)),
430 }
431 self
432 }
433
434 /// Records the error this span failed with. Exporters read it with
435 /// [`Span::error`].
436 ///
437 /// PHP: `$span->setError($throwable)`.
438 pub fn set_error(&self, error: impl Into<Arc<Failure>>) -> &Self {
439 self.state().error = Some(error.into());
440 self
441 }
442
443 /// The recorded error, if any.
444 ///
445 /// PHP: `$span->getError()`.
446 pub fn error(&self) -> Option<Arc<Failure>> {
447 self.state().error.clone()
448 }
449
450 /// What the span represents (`http.request`, `db.query`).
451 ///
452 /// PHP: `$span->getAction()`.
453 pub fn action(&self) -> &str {
454 &self.0.action
455 }
456
457 /// An attribute's value; [`Value::Null`] when it is not set.
458 ///
459 /// PHP: `$span->get($key)`.
460 pub fn get(&self, key: &str) -> Value {
461 self.state().attributes.iter().find(|(k, _)| &**k == key).map(|(_, v)| v.clone()).unwrap_or(Value::Null)
462 }
463
464 /// The span's W3C `traceparent` header: `00-{trace id}-{span id}-01`.
465 ///
466 /// PHP: `$span->getTraceparent()`.
467 ///
468 /// ```
469 /// use utopia_span::Span;
470 ///
471 /// let span = Span::new("call");
472 /// span.set("span.trace_id", "0af7651916cd43dd8448eb211c80319c").set("span.id", "b7ad6b7169203331");
473 /// assert_eq!(span.traceparent(), "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01");
474 /// ```
475 ///
476 /// ```php
477 /// use Utopia\Span\Span;
478 ///
479 /// $span = new Span('call');
480 /// $span->set('span.trace_id', '0af7651916cd43dd8448eb211c80319c')->set('span.id', 'b7ad6b7169203331');
481 /// echo $span->getTraceparent(), "\n"; // 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
482 /// ```
483 pub fn traceparent(&self) -> String {
484 let text = |v: Value| String::from_utf8_lossy(&v.to_php_string()).into_owned();
485 format!("00-{}-{}-01", text(self.get("span.trace_id")), text(self.get("span.id")))
486 }
487
488 /// Every attribute, in the order they were first set.
489 ///
490 /// PHP: `$span->getAttributes()`.
491 pub fn attributes(&self) -> Vec<(Box<str>, Value)> {
492 self.state().attributes.clone()
493 }
494
495 /// Calls `f` with every attribute, in order, without copying them.
496 pub fn with_attributes<R>(&self, f: impl FnOnce(&[(Box<str>, Value)]) -> R) -> R {
497 f(&self.state().attributes)
498 }
499
500 /// Finishes the span: [`Span::finish_with`] without a level or error.
501 ///
502 /// PHP: `$span->finish()`.
503 pub fn finish(&self) {
504 self.finish_with(None, None);
505 }
506
507 /// Finishes the span and exports it.
508 ///
509 /// Records `error` (if given), sets `span.finished_at` and
510 /// `span.duration` (seconds), and sets `level` to `level`, or else to
511 /// [`Level::Error`] when the span has an error and [`Level::Info`]
512 /// otherwise, replacing any `level` set before. Then every exporter whose
513 /// sampler accepts the span exports it, and the current span is cleared.
514 ///
515 /// PHP: `$span->finish($level, $error)`.
516 ///
517 /// ```
518 /// use utopia_span::{Failure, Level, Span, Value};
519 ///
520 /// let span = Span::new("job");
521 /// span.finish_with(Some(Level::Warn), Some(Failure::new("RuntimeException", "slow")));
522 /// assert_eq!(span.get("level"), Value::from("warn"));
523 /// assert!(span.get("span.duration").as_float().is_some());
524 /// ```
525 ///
526 /// ```php
527 /// use Utopia\Span\Level;
528 /// use Utopia\Span\Span;
529 ///
530 /// $span = new Span('job');
531 /// $span->finish(level: Level::Warn, error: new \RuntimeException('slow'));
532 /// echo $span->get('level'), "\n"; // warn
533 /// var_dump(is_float($span->get('span.duration'))); // bool(true)
534 /// ```
535 pub fn finish_with(&self, level: Option<Level>, error: Option<Failure>) {
536 if let Some(error) = error {
537 self.set_error(error);
538 }
539 let finished = microtime();
540 let started = self.get("span.started_at").to_number();
541 self.set("span.finished_at", finished);
542 self.set("span.duration", finished - started);
543 let level = level.unwrap_or(if self.error().is_some() { Level::Error } else { Level::Info });
544 self.set("level", level.as_str());
545
546 let exporters = EXPORTERS.read().unwrap_or_else(|e| e.into_inner()).clone();
547 for exporter in &exporters {
548 if exporter.sample(self) {
549 exporter.export(self);
550 }
551 }
552 if let Some(storage) = STORAGE.read().unwrap_or_else(|e| e.into_inner()).as_ref() {
553 storage.set(None);
554 }
555 }
556}
557
558#[cfg(test)]
559mod tests {
560 use super::*;
561
562 #[test]
563 fn invalid_traceparent_starts_a_new_trace() {
564 let span = Span::init("t", Some("00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331"));
565 assert_eq!(span.get("span.parent_id"), Value::Null);
566 assert_eq!(span.get("span.id").as_str().map(str::len), Some(16));
567 }
568
569 #[test]
570 fn set_keeps_the_position() {
571 let span = Span::new("t");
572 span.set("a", 1).set("b", 2).set("a", 3);
573 let keys: Vec<_> = span.attributes().into_iter().map(|(k, _)| k).collect();
574 assert_eq!(&*keys[3], "a");
575 assert_eq!(span.get("a"), Value::Int(3));
576 }
577}