Rust

exporter

Module

Exporters: where finished spans go.

Span::finish hands the span to every registered Exporter whose Exporter::sample accepts it. None discards spans, Stdout writes JSON lines, Pretty writes colourful multi-line output for a terminal, and Sentry reports errors to Sentry.

PHP: the classes of Utopia\Span\Exporter.

Contents

use utopia_span::exporter::HttpTransport;
Rust
pub struct HttpTransport {
    // private fields
}

Sends envelopes over HTTP/1.1 (TLS with the WebPKI roots) in the background: on the current runtime, or on a thread of its own outside one. Failures are written to standard error. The whole exchange times out after one second, the connection after half a second.

PHP: the default utopia-php/client cURL client, with CURLOPT_TIMEOUT_MS => 1000 and CURLOPT_CONNECTTIMEOUT_MS => 500; failures go to error_log().

use utopia_span::exporter::None;
Rust
pub struct None;

Discards every span: Exporter::sample is always false.

PHP: Utopia\Span\Exporter\None.

Rust
use utopia_span::exporter::{Exporter, None};
use utopia_span::Span;

let span = Span::new("test");
assert!(!None.sample(&span));
None.export(&span); // does nothing
PHP
use Utopia\Span\Exporter\None;
use Utopia\Span\Span;

$span = new Span('test');
var_dump((new None())->sample($span)); // bool(false)
(new None())->export($span);           // does nothing
use utopia_span::Pretty;
Rust
pub struct Pretty {
    // private fields
}

Writes each span as a coloured block for local development: a header (action, duration, short trace id), the attributes other than span.* aligned in a column with level first, the error with at most max_trace_frames stack frames, and a separator line width wide. Spans with an error go to standard error, the others to standard output.

PHP: Utopia\Span\Exporter\Pretty.

Rust
use utopia_span::{Pretty, Span};

let span = Span::new("db.query");
span.set("span.duration", 0.0123).set("rows", 3);
let text = String::from_utf8(Pretty::new().width(10).render(&span)).unwrap();
assert!(text.contains("12.3ms"));
assert!(text.contains("rows"));
PHP
use Utopia\Span\Exporter\Pretty;
use Utopia\Span\Span;

$span = new Span('db.query');
$span->set('span.duration', 0.0123)->set('rows', 3);
(new Pretty(width: 10))->export($span); // db.query · 12.3ms · … then "rows 3"
Also implements Default, Debug.
use utopia_span::exporter::Request;
Rust
pub struct Request {
    pub method: &'static str,
    pub url: String,
    pub headers: Vec<(&'static str, String)>,
    pub body: Vec<u8>,
}

An HTTP request to Sentry's envelope endpoint.

use utopia_span::Sentry;
Rust
pub struct Sentry {
    // private fields
}

Reports spans at warning level or above that carry an error as Sentry issues.

Each event carries the error and its chain of causes (at most 10, root cause first), the trace context, http.url, http.method and http.query as the request, http.response.status_code as the response, and every other attribute (except span.* and level) as a context, tag or extra, as the classifier decides. A boolean span.handled attribute sets whether the error was handled; otherwise fatal spans are unhandled.

PHP: Utopia\Span\Exporter\Sentry. It sends with a PSR-18 client and waits for the reply; here the default HttpTransport sends in the background on the current runtime.

Rust
use std::sync::{Arc, Mutex};
use utopia_span::exporter::Request;
use utopia_span::{Exporter, Failure, Level, Sentry, Span};

let sent = Arc::new(Mutex::new(Vec::<Request>::new()));
let log = sent.clone();
let sentry = Sentry::new("https://publickey@sentry.example.com:9000/123")?
    .transport(move |request: Request| log.lock().unwrap().push(request));

let span = Span::new("test");
span.finish_with(Some(Level::Error), Some(Failure::new("RuntimeException", "Test error")));
assert!(sentry.sample(&span));
sentry.export(&span);

let request = &sent.lock().unwrap()[0];
assert_eq!(request.url, "https://sentry.example.com:9000/api/123/envelope/");
assert!(String::from_utf8_lossy(&request.body).contains(r#""value":"Test error""#));
PHP
use Utopia\Span\Exporter\Sentry;
use Utopia\Span\Span;

$sentry = new Sentry(dsn: 'https://publickey@sentry.example.com:9000/123');
$span = new Span('test');
$span->finish(error: new \RuntimeException('Test error'));
var_dump($sentry->sample($span)); // bool(true)
// $sentry->export($span) POSTs to https://sentry.example.com:9000/api/123/envelope/
Also implements Debug.
use utopia_span::Stdout;
Rust
pub struct Stdout {
    // private fields
}

Writes each span as one line of JSON (NDJSON): level and action first, then every attribute, then the error (error.type, error.message, error.code, error.file, error.line, error.trace with at most max_trace_frames frames, error.trace_truncated). Spans with an error go to standard error, the others to standard output.

Invalid UTF-8 is replaced with U+FFFD and a value that cannot be encoded becomes null, so one bad attribute cannot drop the whole record; when the record still cannot be encoded, a line naming the failure (level, action, error.type, export.error) is written instead.

PHP: Utopia\Span\Exporter\Stdout.

Rust
use std::io::Write;
use std::sync::{Arc, Mutex};
use utopia_span::{Exporter, Span, Stdout};

#[derive(Clone, Default)]
struct Buffer(Arc<Mutex<Vec<u8>>>);
impl Write for Buffer {
    fn write(&mut self, b: &[u8]) -> std::io::Result<usize> { self.0.lock().unwrap().write(b) }
    fn flush(&mut self) -> std::io::Result<()> { Ok(()) }
}

let out = Buffer::default();
let exporter = Stdout::new().writers(Box::new(out.clone()), Box::new(std::io::sink()));
let span = Span::new("job");
span.set("span.trace_id", "t").set("span.id", "s").set("span.started_at", 1.5).set("level", "info");
exporter.export(&span);

let line = String::from_utf8(out.0.lock().unwrap().clone()).unwrap();
assert_eq!(line, "{\"level\":\"info\",\"action\":\"job\",\"span.trace_id\":\"t\",\"span.id\":\"s\",\"span.started_at\":1.5}\n");
PHP
use Utopia\Span\Exporter\Stdout;
use Utopia\Span\Span;

$span = new Span('job');
$span->set('span.trace_id', 't')->set('span.id', 's')->set('span.started_at', 1.5)->set('level', 'info');
(new Stdout())->export($span);
// {"level":"info","action":"job","span.trace_id":"t","span.id":"s","span.started_at":1.5}
Also implements Default, Debug.
use utopia_span::exporter::SentryField;
Rust
pub enum SentryField {
    Tag,
    Context,
    Extra,
}

Where a span attribute goes in a Sentry event.

PHP: Utopia\Span\Exporter\SentryField.

use utopia_span::exporter::SentryLevel;
Rust
pub enum SentryLevel {
    Debug,
    Info,
    Warning,
    Error,
    Fatal,
}

The levels of Sentry's event API.

PHP: Utopia\Span\Exporter\Sentry\Level.

use utopia_span::Exporter;
Rust
pub trait Exporter: Send + Sync

Receives finished spans.

Implement it to send spans to an observability backend, then register it with Span::set_exporters.

PHP: Utopia\Span\Exporter\Exporter.

use utopia_span::exporter::Transport;
Rust
pub trait Transport: Send + Sync

Sends envelopes to Sentry.

A transport reports its own failures: tracing never fails the application.

PHP: the PSR-18 ClientInterface the exporter sends with.

Implemented byHttpTransport
Rust
pub type Sampler = Box<dyn Fn(&Span) -> bool + Send + Sync>;

Decides whether an exporter exports a span.

PHP: the Closure(Span): bool $sampler of an exporter's constructor.