Skip to main content

utopia_span/exporter/
sentry.rs

1//! Errors as Sentry issues.
2
3use std::sync::Arc;
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use php_std::json::{self, Flags};
7use php_std::{Array, ArrayKey, Value as Php};
8
9use super::{Exporter, Sampler};
10use crate::{Error, Failure, Level, Span, Value};
11
12/// Where a span attribute goes in a Sentry event.
13///
14/// PHP: `Utopia\Span\Exporter\SentryField`.
15#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum SentryField {
17    /// Indexed and searchable: for low-cardinality values (environment,
18    /// version, tenant). Values are cut to 200 characters.
19    Tag,
20    /// Not indexed; recommended for debugging data. The default.
21    Context,
22    /// Not indexed; deprecated by Sentry in favour of [`SentryField::Context`].
23    Extra,
24}
25
26/// The levels of Sentry's event API.
27///
28/// PHP: `Utopia\Span\Exporter\Sentry\Level`.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum SentryLevel {
31    /// `debug`.
32    Debug,
33    /// `info`.
34    Info,
35    /// `warning`.
36    Warning,
37    /// `error`.
38    Error,
39    /// `fatal`.
40    Fatal,
41}
42
43impl SentryLevel {
44    /// The Sentry level of a span level (`warn` is `warning`).
45    ///
46    /// PHP: `Sentry\Level::fromSpan($level)`.
47    ///
48    /// ```
49    /// use utopia_span::Level;
50    /// use utopia_span::exporter::SentryLevel;
51    ///
52    /// assert_eq!(SentryLevel::from_span(Level::Warn).as_str(), "warning");
53    /// ```
54    ///
55    /// ```php
56    /// use Utopia\Span\Exporter\Sentry\Level as SentryLevel;
57    /// use Utopia\Span\Level;
58    ///
59    /// echo SentryLevel::fromSpan(Level::Warn)->value, "\n"; // warning
60    /// ```
61    pub const fn from_span(level: Level) -> Self {
62        match level {
63            Level::Debug => SentryLevel::Debug,
64            Level::Info => SentryLevel::Info,
65            Level::Warn => SentryLevel::Warning,
66            Level::Error => SentryLevel::Error,
67            Level::Fatal => SentryLevel::Fatal,
68        }
69    }
70
71    /// The level's name in Sentry's API.
72    ///
73    /// PHP: `$level->value`.
74    pub const fn as_str(self) -> &'static str {
75        match self {
76            SentryLevel::Debug => "debug",
77            SentryLevel::Info => "info",
78            SentryLevel::Warning => "warning",
79            SentryLevel::Error => "error",
80            SentryLevel::Fatal => "fatal",
81        }
82    }
83}
84
85/// An HTTP request to Sentry's envelope endpoint.
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct Request {
88    /// The method: `POST`.
89    pub method: &'static str,
90    /// The envelope endpoint, `{scheme}://{host}{:port}/api/{project}/envelope/`.
91    pub url: String,
92    /// `Content-Type` and `X-Sentry-Auth`.
93    pub headers: Vec<(&'static str, String)>,
94    /// The envelope: header, item header and event, one JSON document per line.
95    pub body: Vec<u8>,
96}
97
98/// Sends envelopes to Sentry.
99///
100/// A transport reports its own failures: tracing never fails the
101/// application.
102///
103/// PHP: the PSR-18 `ClientInterface` the exporter sends with.
104pub trait Transport: Send + Sync {
105    /// Sends one request.
106    fn send(&self, request: Request);
107}
108
109impl<F: Fn(Request) + Send + Sync> Transport for F {
110    fn send(&self, request: Request) {
111        self(request)
112    }
113}
114
115type Classifier = Box<dyn Fn(&str) -> SentryField + Send + Sync>;
116
117/// Span levels Sentry receives.
118const EXPORT_LEVELS: [Level; 3] = [Level::Warn, Level::Error, Level::Fatal];
119
120/// Chained causes sent per event, at most.
121const MAX_CHAIN_DEPTH: usize = 10;
122
123/// Attributes mapped onto the event's `request` and `response`.
124const HANDLED_HTTP_KEYS: [&str; 4] = ["http.url", "http.method", "http.query", "http.response.status_code"];
125
126/// Reports spans at warning level or above that carry an error as Sentry
127/// issues.
128///
129/// Each event carries the error and its chain of causes (at most 10, root
130/// cause first), the trace context, `http.url`, `http.method` and
131/// `http.query` as the request, `http.response.status_code` as the response,
132/// and every other attribute (except `span.*` and `level`) as a context, tag
133/// or extra, as the classifier decides. A boolean `span.handled` attribute
134/// sets whether the error was handled; otherwise fatal spans are unhandled.
135///
136/// PHP: `Utopia\Span\Exporter\Sentry`. It sends with a PSR-18 client and
137/// waits for the reply; here the default [`HttpTransport`] sends in the
138/// background on the current runtime.
139///
140/// ```
141/// use std::sync::{Arc, Mutex};
142/// use utopia_span::exporter::Request;
143/// use utopia_span::{Exporter, Failure, Level, Sentry, Span};
144///
145/// let sent = Arc::new(Mutex::new(Vec::<Request>::new()));
146/// let log = sent.clone();
147/// let sentry = Sentry::new("https://publickey@sentry.example.com:9000/123")?
148///     .transport(move |request: Request| log.lock().unwrap().push(request));
149///
150/// let span = Span::new("test");
151/// span.finish_with(Some(Level::Error), Some(Failure::new("RuntimeException", "Test error")));
152/// assert!(sentry.sample(&span));
153/// sentry.export(&span);
154///
155/// let request = &sent.lock().unwrap()[0];
156/// assert_eq!(request.url, "https://sentry.example.com:9000/api/123/envelope/");
157/// assert!(String::from_utf8_lossy(&request.body).contains(r#""value":"Test error""#));
158/// # Ok::<(), utopia_span::Error>(())
159/// ```
160///
161/// ```php
162/// use Utopia\Span\Exporter\Sentry;
163/// use Utopia\Span\Span;
164///
165/// $sentry = new Sentry(dsn: 'https://publickey@sentry.example.com:9000/123');
166/// $span = new Span('test');
167/// $span->finish(error: new \RuntimeException('Test error'));
168/// var_dump($sentry->sample($span)); // bool(true)
169/// // $sentry->export($span) POSTs to https://sentry.example.com:9000/api/123/envelope/
170/// ```
171pub struct Sentry {
172    dsn: String,
173    endpoint: String,
174    public_key: String,
175    environment: Option<String>,
176    release: Option<String>,
177    server_name: Option<String>,
178    sampler: Option<Sampler>,
179    classifier: Classifier,
180    transport: Arc<dyn Transport>,
181}
182
183impl std::fmt::Debug for Sentry {
184    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
185        f.debug_struct("Sentry").field("endpoint", &self.endpoint).finish()
186    }
187}
188
189fn text(bytes: Option<std::borrow::Cow<'_, [u8]>>) -> String {
190    bytes.map(|b| String::from_utf8_lossy(&b).into_owned()).unwrap_or_default()
191}
192
193fn key(k: &str) -> ArrayKey {
194    ArrayKey::from(k)
195}
196
197fn object(entries: Vec<(&str, Php)>) -> Php {
198    let mut array = Array::default();
199    for (k, v) in entries {
200        array.set(key(k), v);
201    }
202    Php::Array(array)
203}
204
205impl Sentry {
206    /// An exporter to the project of `dsn` (`https://<key>@<host>/<project>`).
207    ///
208    /// Fails with [`Error::InvalidArgument`] when the DSN is empty,
209    /// malformed, or lacks the key, host or project.
210    ///
211    /// PHP: `new Sentry(dsn: $dsn)`.
212    ///
213    /// ```
214    /// use utopia_span::Sentry;
215    ///
216    /// assert!(Sentry::new("https://key@sentry.io/123").is_ok());
217    /// assert_eq!(Sentry::new("").unwrap_err().to_string(), "Sentry DSN is required");
218    /// assert_eq!(
219    ///     Sentry::new("https://sentry.io/123").unwrap_err().to_string(),
220    ///     "Invalid Sentry DSN: must include public key, host, and project ID",
221    /// );
222    /// ```
223    ///
224    /// ```php
225    /// use Utopia\Span\Exporter\Sentry;
226    ///
227    /// try {
228    ///     new Sentry(dsn: 'https://sentry.io/123');
229    /// } catch (\InvalidArgumentException $e) {
230    ///     echo $e->getMessage(), "\n"; // Invalid Sentry DSN: must include public key, host, and project ID
231    /// }
232    /// ```
233    pub fn new(dsn: &str) -> Result<Self, Error> {
234        if dsn.is_empty() {
235            return Err(Error::InvalidArgument("Sentry DSN is required"));
236        }
237        let url = php_std::url::parse_url(dsn.as_bytes()).ok_or(Error::InvalidArgument("Invalid Sentry DSN"))?;
238        let public_key = text(url.user());
239        let host = text(url.host());
240        let path = text(url.path());
241        let project = path.trim_start_matches('/');
242        if public_key.is_empty() || host.is_empty() || project.is_empty() {
243            return Err(Error::InvalidArgument("Invalid Sentry DSN: must include public key, host, and project ID"));
244        }
245        let scheme =
246            url.scheme().map_or_else(|| "https".to_owned(), |s| String::from_utf8_lossy(&s).to_ascii_lowercase());
247        // The request URI as an HTTP client normalises it: lowercase scheme
248        // and host, no default port, the path percent-encoded.
249        let port = match (scheme.as_str(), url.port()) {
250            (_, None) | ("http", Some(80)) | ("https", Some(443)) => String::new(),
251            (_, Some(p)) => format!(":{p}"),
252        };
253        let host = host.to_ascii_lowercase();
254        Ok(Self {
255            dsn: dsn.to_owned(),
256            endpoint: format!("{scheme}://{host}{port}{}", encode_path(&format!("/api/{project}/envelope/"))),
257            public_key,
258            environment: None,
259            release: None,
260            server_name: None,
261            sampler: None,
262            classifier: Box::new(|_| SentryField::Context),
263            transport: default_transport(),
264        })
265    }
266
267    /// Exports only the spans `sampler` accepts, among those at warning level
268    /// or above: it narrows what is sent, never widens it.
269    ///
270    /// PHP: the `$sampler` argument.
271    pub fn sampler(mut self, sampler: impl Fn(&Span) -> bool + Send + Sync + 'static) -> Self {
272        self.sampler = Some(Box::new(sampler));
273        self
274    }
275
276    /// The environment events are tagged with (`production`).
277    ///
278    /// PHP: the `$environment` argument.
279    pub fn environment(mut self, environment: impl Into<String>) -> Self {
280        self.environment = Some(environment.into());
281        self
282    }
283
284    /// The release events are tagged with (a version or commit).
285    ///
286    /// PHP: the `$release` argument.
287    pub fn release(mut self, release: impl Into<String>) -> Self {
288        self.release = Some(release.into());
289        self
290    }
291
292    /// The server name events are tagged with.
293    ///
294    /// PHP: the `$serverName` argument.
295    pub fn server_name(mut self, server_name: impl Into<String>) -> Self {
296        self.server_name = Some(server_name.into());
297        self
298    }
299
300    /// Decides where each attribute goes; the default puts every attribute in
301    /// the event's context.
302    ///
303    /// PHP: the `$classifier` argument.
304    pub fn classifier(mut self, classifier: impl Fn(&str) -> SentryField + Send + Sync + 'static) -> Self {
305        self.classifier = Box::new(classifier);
306        self
307    }
308
309    /// Sends envelopes with `transport` instead of the default HTTP client.
310    ///
311    /// PHP: the `$client` argument.
312    pub fn transport(mut self, transport: impl Transport + 'static) -> Self {
313        self.transport = Arc::new(transport);
314        self
315    }
316
317    /// The request this exporter sends for `span`, or `None` when the span
318    /// has no error or its event cannot be encoded.
319    pub fn request(&self, span: &Span) -> Option<Request> {
320        let body = self.envelope(span)?;
321        Some(Request {
322            method: "POST",
323            url: self.endpoint.clone(),
324            headers: vec![
325                ("Content-Type", "application/x-sentry-envelope".to_owned()),
326                ("X-Sentry-Auth", format!("Sentry sentry_version=7, sentry_key={}", self.public_key)),
327            ],
328            body,
329        })
330    }
331
332    fn envelope(&self, span: &Span) -> Option<Vec<u8>> {
333        let error = span.error()?;
334        let attributes = span.attributes();
335        let get = |k: &str| attributes.iter().find(|(key, _)| &**key == k).map(|(_, v)| v.clone()).unwrap_or_default();
336        let now = || {
337            let d = SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default();
338            d.as_secs() as f64 + f64::from(d.subsec_micros()) / 1e6
339        };
340        let or_now = |v: Value| if v.is_null() { now() } else { v.to_number() };
341
342        let trace_id = get("span.trace_id").to_php_string();
343        let span_id = get("span.id").to_php_string();
344        let started = or_now(get("span.started_at"));
345        let finished = or_now(get("span.finished_at"));
346
347        let mut trace = vec![("trace_id", Php::Str(trace_id.clone().into())), ("span_id", Php::Str(span_id.into()))];
348        if let Value::Str(parent) = get("span.parent_id") {
349            trace.push(("parent_span_id", Php::Str(parent)));
350        }
351
352        let event_id: Vec<u8> = trace_id.iter().copied().filter(|&b| b != b'-').collect();
353        let sent_at = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
354        let header = object(vec![
355            ("event_id", Php::Str(event_id.into())),
356            ("sent_at", Php::Str(php_std::datetime::date(b"c", sent_at, &php_std::datetime::TzInfo::utc()).into())),
357            ("dsn", Php::from(self.dsn.as_str())),
358        ]);
359        let item = object(vec![("type", Php::from("event")), ("content_type", Php::from("application/json"))]);
360
361        let mut contexts = vec![
362            ("trace", object(trace)),
363            (
364                "runtime",
365                object(vec![
366                    ("name", Php::from("rust")),
367                    ("version", Php::from(option_env!("CARGO_PKG_RUST_VERSION").unwrap_or("unknown"))),
368                    ("sapi", Php::from("native")),
369                ]),
370            ),
371        ];
372        if let Value::Int(status) = get("http.response.status_code") {
373            contexts.push(("response", object(vec![("status_code", Php::Int(status))])));
374        }
375
376        let mut tags = Array::default();
377        let mut custom = Array::default();
378        let mut extra = Array::default();
379        for (k, value) in &attributes {
380            if k.starts_with("span.") || &**k == "level" || HANDLED_HTTP_KEYS.contains(&&**k) {
381                continue;
382            }
383            match (self.classifier)(k) {
384                SentryField::Tag => {
385                    let text = value.to_php_string();
386                    // `mb_substr($value, 0, 200, 'UTF-8')`: 200 characters.
387                    let cut = php_std::mb::mb_substr(&text, 0, Some(200)).unwrap_or_else(|_| text.to_vec());
388                    tags.set(key(k), Php::Str(cut.into()));
389                }
390                SentryField::Context => {
391                    custom.set(key(k), value.to_php());
392                }
393                SentryField::Extra => {
394                    extra.set(key(k), value.to_php());
395                }
396            }
397        }
398        if !custom.is_empty() {
399            contexts.push(("custom", Php::Array(custom)));
400        }
401
402        let level = Level::parse(&get("level").to_php_string()).unwrap_or(Level::Error);
403        let handled = get("span.handled").as_bool();
404        let mut payload = vec![
405            ("level", Php::from(SentryLevel::from_span(level).as_str())),
406            ("platform", Php::from("native")),
407            (
408                "sdk",
409                object(vec![("name", Php::from("utopia-span")), ("version", Php::from(env!("CARGO_PKG_VERSION")))]),
410            ),
411            ("start_timestamp", Php::Float(started)),
412            ("timestamp", Php::Float(finished)),
413            ("transaction", Php::from(span.action())),
414            ("message", Php::Str(error.message_bytes().into())),
415            ("contexts", object(contexts)),
416            ("exception", object(vec![("values", exception_values(&error, level, handled))])),
417        ];
418        if !tags.is_empty() {
419            payload.push(("tags", Php::Array(tags)));
420        }
421        if !extra.is_empty() {
422            payload.push(("extra", Php::Array(extra)));
423        }
424        let mut request = Vec::new();
425        for (attribute, field) in [("http.url", "url"), ("http.method", "method"), ("http.query", "query_string")] {
426            if let Value::Str(s) = get(attribute) {
427                request.push((field, Php::Str(s)));
428            }
429        }
430        if !request.is_empty() {
431            payload.push(("request", object(request)));
432        }
433        for (field, value) in
434            [("environment", &self.environment), ("release", &self.release), ("server_name", &self.server_name)]
435        {
436            if let Some(value) = value {
437                payload.push((field, Php::from(value.as_str())));
438            }
439        }
440
441        let encode = |v: &Php, flags: Flags| json::encode(v, flags, json::DEFAULT_DEPTH);
442        let encoded = (
443            encode(&header, Flags::INVALID_UTF8_SUBSTITUTE),
444            encode(&item, Flags::NONE),
445            encode(&object(payload), Flags::INVALID_UTF8_SUBSTITUTE),
446        );
447        let (Ok(header), Ok(item), Ok(payload)) = encoded else {
448            // `json_last_error_msg()` is the last encoding's: the payload's.
449            let message = match &encoded.2 {
450                Err(e) => e.message(),
451                Ok(_) => "No error",
452            };
453            eprintln!("Sentry exporter: failed to encode event - {message}");
454            return None;
455        };
456        Some(format!("{header}\n{item}\n{payload}").into_bytes())
457    }
458}
459
460/// Percent-encodes what a URI path may not hold, as PSR-7 URIs do: bytes
461/// outside the unreserved, sub-delimiter, `:`, `@`, `/` and `%` characters,
462/// and a `%` not followed by two hex digits.
463fn encode_path(path: &str) -> String {
464    let bytes = path.as_bytes();
465    let mut out = String::with_capacity(path.len());
466    for (i, &b) in bytes.iter().enumerate() {
467        let keep = b.is_ascii_alphanumeric()
468            || b"_-.~!$&'()*+,;=:@/".contains(&b)
469            || (b == b'%'
470                && bytes.len() > i + 2
471                && bytes[i + 1].is_ascii_hexdigit()
472                && bytes[i + 2].is_ascii_hexdigit());
473        if keep {
474            out.push(b as char);
475        } else {
476            out.push_str(&format!("%{b:02X}"));
477        }
478    }
479    out
480}
481
482/// The values of the event's `exception`: the error and its causes, root
483/// cause first.
484fn exception_values(error: &Failure, level: Level, handled: Option<bool>) -> Php {
485    let mut chain = Vec::new();
486    let mut current = Some(error);
487    while let Some(e) = current {
488        if chain.len() >= MAX_CHAIN_DEPTH {
489            break;
490        }
491        chain.push(e);
492        current = e.cause();
493    }
494    let handled = handled.unwrap_or(level != Level::Fatal);
495    let chained = chain.len() > 1;
496    let mut values: Vec<Php> = chain
497        .iter()
498        .enumerate()
499        .map(|(id, exception)| {
500            let mut mechanism = vec![("type", Php::from("generic")), ("handled", Php::Bool(handled))];
501            if chained {
502                mechanism.push(("exception_id", Php::Int(id as i64)));
503                if id > 0 {
504                    mechanism.push(("parent_id", Php::Int(id as i64 - 1)));
505                    mechanism.push(("source", Php::from("__previous__")));
506                }
507            }
508            let mut value = vec![
509                ("type", Php::from(exception.class())),
510                ("value", Php::Str(exception.message_bytes().into())),
511                ("stacktrace", object(vec![("frames", frames(exception))])),
512                ("mechanism", object(mechanism)),
513            ];
514            if let Some(end) = exception.class().rfind('\\') {
515                value.push(("module", Php::from(&exception.class()[..end])));
516            }
517            object(value)
518        })
519        .collect();
520    values.reverse();
521    Php::Array(values.into_iter().collect())
522}
523
524fn function(frame: &crate::Frame) -> String {
525    match &frame.class {
526        Some(class) => format!("{class}{}{}", frame.call.as_deref().unwrap_or("::"), frame.function),
527        None => frame.function.clone(),
528    }
529}
530
531/// The stack frames of one error, outermost call first, ending with where it
532/// was raised.
533fn frames(error: &Failure) -> Php {
534    let in_app = |file: &str| Php::Bool(!file.contains("/vendor/"));
535    let mut frames: Array = error
536        .frames()
537        .iter()
538        .rev()
539        .filter_map(|frame| {
540            let file = frame.file.as_deref()?;
541            Some(object(vec![
542                ("filename", Php::from(file)),
543                ("lineno", Php::Int(frame.line.map_or(0, i64::from))),
544                ("in_app", in_app(file)),
545                ("function", Php::from(function(frame).as_str())),
546            ]))
547        })
548        .collect();
549    let mut site = vec![
550        ("filename", Php::from(error.file())),
551        ("lineno", Php::Int(i64::from(error.line()))),
552        ("in_app", in_app(error.file())),
553    ];
554    if let Some(first) = error.frames().first() {
555        site.push(("function", Php::from(function(first).as_str())));
556    }
557    let _ = frames.push(object(site));
558    Php::Array(frames)
559}
560
561impl Exporter for Sentry {
562    fn sample(&self, span: &Span) -> bool {
563        let level = Level::parse(&span.get("level").to_php_string());
564        if !level.is_some_and(|l| EXPORT_LEVELS.contains(&l)) {
565            return false;
566        }
567        self.sampler.as_ref().is_none_or(|sampler| sampler(span))
568    }
569
570    fn export(&self, span: &Span) {
571        if let Some(request) = self.request(span) {
572            self.transport.send(request);
573        }
574    }
575}
576
577#[cfg(feature = "http")]
578fn default_transport() -> Arc<dyn Transport> {
579    Arc::new(HttpTransport::new())
580}
581
582#[cfg(not(feature = "http"))]
583fn default_transport() -> Arc<dyn Transport> {
584    Arc::new(|_request: Request| {})
585}
586
587#[cfg(feature = "http")]
588pub use http::HttpTransport;
589
590#[cfg(feature = "http")]
591mod http {
592    use std::time::Duration;
593
594    use bytes::Bytes;
595    use http_body_util::{BodyExt, Full};
596    use hyper_rustls::HttpsConnector;
597    use hyper_util::client::legacy::Client;
598    use hyper_util::client::legacy::connect::HttpConnector as Connector;
599    use hyper_util::rt::TokioExecutor;
600
601    use super::{Request, Transport};
602
603    type HyperClient = Client<HttpsConnector<Connector>, Full<Bytes>>;
604
605    /// Sends envelopes over HTTP/1.1 (TLS with the WebPKI roots) in the
606    /// background: on the current runtime, or on a thread of its own
607    /// outside one. Failures are written to standard error. The whole
608    /// exchange times out after one second, the connection after half a
609    /// second.
610    ///
611    /// PHP: the default `utopia-php/client` cURL client, with
612    /// `CURLOPT_TIMEOUT_MS => 1000` and `CURLOPT_CONNECTTIMEOUT_MS => 500`;
613    /// failures go to `error_log()`.
614    #[derive(Debug, Default)]
615    pub struct HttpTransport {
616        client: std::sync::OnceLock<Option<HyperClient>>,
617    }
618
619    impl HttpTransport {
620        /// A transport.
621        pub fn new() -> Self {
622            Self::default()
623        }
624
625        fn client(&self) -> Option<HyperClient> {
626            self.client
627                .get_or_init(|| {
628                    let mut http = Connector::new();
629                    http.set_connect_timeout(Some(Duration::from_millis(500)));
630                    http.enforce_http(false);
631                    let https = hyper_rustls::HttpsConnectorBuilder::new()
632                        .with_provider_and_webpki_roots(rustls::crypto::ring::default_provider())
633                        .ok()?
634                        .https_or_http()
635                        .enable_http1()
636                        .wrap_connector(http);
637                    Some(Client::builder(TokioExecutor::new()).build(https))
638                })
639                .clone()
640        }
641    }
642
643    async fn exchange(client: HyperClient, request: Request) -> Result<(), String> {
644        let mut builder = hyper::Request::builder().method(request.method).uri(request.url.as_str());
645        for (name, value) in &request.headers {
646            builder = builder.header(*name, value.as_str());
647        }
648        let req = builder.body(Full::new(Bytes::from(request.body))).map_err(|e| e.to_string())?;
649        let res = client.request(req).await.map_err(|e| e.to_string())?;
650        let status = res.status().as_u16();
651        if status >= 400 {
652            let body = res.into_body().collect().await.map(|b| b.to_bytes()).unwrap_or_default();
653            return Err(format!("HTTP {status} - {}", String::from_utf8_lossy(&body)));
654        }
655        Ok(())
656    }
657
658    impl Transport for HttpTransport {
659        fn send(&self, request: Request) {
660            let Some(client) = self.client() else {
661                eprintln!("Sentry exporter: TLS setup failed");
662                return;
663            };
664            let job = async move {
665                let result = tokio::time::timeout(Duration::from_secs(1), exchange(client, request)).await;
666                match result {
667                    Ok(Ok(())) => {}
668                    Ok(Err(message)) => eprintln!("Sentry exporter: {message}"),
669                    Err(_) => eprintln!("Sentry exporter: Operation timed out after 1000 milliseconds"),
670                }
671            };
672            match tokio::runtime::Handle::try_current() {
673                Ok(runtime) => {
674                    runtime.spawn(job);
675                }
676                Err(_) => {
677                    std::thread::spawn(move || {
678                        if let Ok(runtime) = tokio::runtime::Builder::new_current_thread().enable_all().build() {
679                            runtime.block_on(job);
680                        }
681                    });
682                }
683            }
684        }
685    }
686}