1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub enum SentryField {
17 Tag,
20 Context,
22 Extra,
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum SentryLevel {
31 Debug,
33 Info,
35 Warning,
37 Error,
39 Fatal,
41}
42
43impl SentryLevel {
44 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 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#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct Request {
88 pub method: &'static str,
90 pub url: String,
92 pub headers: Vec<(&'static str, String)>,
94 pub body: Vec<u8>,
96}
97
98pub trait Transport: Send + Sync {
105 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
117const EXPORT_LEVELS: [Level; 3] = [Level::Warn, Level::Error, Level::Fatal];
119
120const MAX_CHAIN_DEPTH: usize = 10;
122
123const HANDLED_HTTP_KEYS: [&str; 4] = ["http.url", "http.method", "http.query", "http.response.status_code"];
125
126pub 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 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 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 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 pub fn environment(mut self, environment: impl Into<String>) -> Self {
280 self.environment = Some(environment.into());
281 self
282 }
283
284 pub fn release(mut self, release: impl Into<String>) -> Self {
288 self.release = Some(release.into());
289 self
290 }
291
292 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 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 pub fn transport(mut self, transport: impl Transport + 'static) -> Self {
313 self.transport = Arc::new(transport);
314 self
315 }
316
317 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 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 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
460fn 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
482fn 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
531fn 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 #[derive(Debug, Default)]
615 pub struct HttpTransport {
616 client: std::sync::OnceLock<Option<HyperClient>>,
617 }
618
619 impl HttpTransport {
620 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}