1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102
//! Sentry options implementation. use crate::{ before_send, logger, transport, BeforeSend, BeforeSendData, CPath, CToR, Error, Level, Message, RToC, Transport, TransportState, BEFORE_SEND, LOGGER, }; #[cfg(doc)] use crate::{shutdown, user_consent_give, user_consent_revoke, Event}; use once_cell::sync::Lazy; #[cfg(feature = "test")] use std::env; #[cfg(doc)] use std::process::abort; use std::{ fmt::{Debug, Formatter, Result as FmtResult}, mem, path::PathBuf, sync::{Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard}, }; /// Global lock for the following purposes: /// - Prevent [`Options::init`] from being called twice. /// - Fix some null-dereferncing bugs in `sentry-native` that can happen when /// shutdown is called while other functions are still accessing options. /// Hopefully this will be fixed upstream in the future, see /// <https://github.com/getsentry/sentry-native/issues/280>. static GLOBAL_LOCK: Lazy<RwLock<bool>> = Lazy::new(|| RwLock::new(false)); /// Convenience function to get a read lock on `GLOBAL_LOCK`. pub fn global_read() -> RwLockReadGuard<'static, bool> { GLOBAL_LOCK.read().expect("global lock poisoned") } /// Convenience function to get a write lock on `GLOBAL_LOCK`. pub fn global_write() -> RwLockWriteGuard<'static, bool> { GLOBAL_LOCK.write().expect("global lock poisoned") } /// The Sentry client options. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// # fn main() -> anyhow::Result<()> { /// let _shutdown = Options::new().init()?; /// # Ok(()) } /// ``` pub struct Options { /// Raw Sentry options. raw: Option<Ownership>, /// Storing a fake DSN to make documentation tests and examples work. #[cfg(feature = "test")] dsn: Option<String>, /// Storing [`Options::set_before_send`] data to save it globally on /// [`Options::init`] and properly deallocate it on [`shutdown`]. before_send: Option<BeforeSendData>, } /// Represents the ownership status of [`Options`]. #[derive(Clone, Copy, Debug)] pub enum Ownership { /// [`Options`] is owned. Owned(*mut sys::Options), /// [`Options`] is borrowed. Borrowed(*const sys::Options), } unsafe impl Send for Options {} unsafe impl Sync for Options {} impl Default for Options { fn default() -> Self { Self::new() } } impl Debug for Options { fn fmt(&self, fmt: &mut Formatter<'_>) -> FmtResult { let mut debug = fmt.debug_struct("Options"); debug.field("raw", &self.raw); #[cfg(feature = "test")] debug.field("dsn", &self.dsn); debug .field( "before_send", if self.before_send.is_some() { &"Some" } else { &"None" }, ) .finish() } } impl Drop for Options { fn drop(&mut self) { if let Some(Ownership::Owned(options)) = self.raw.take() { unsafe { sys::options_free(options) } } } } impl PartialEq for Options { fn eq(&self, _: &Self) -> bool { false } } impl Eq for Options {} impl Options { /// Creates new Sentry client options. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// ``` #[must_use] pub fn new() -> Self { Self::from_sys(Ownership::Owned(unsafe { sys::options_new() })) } /// Creates new [`Options`] from a [`sys::Options`] wrapped in /// [`Ownership`]. pub(crate) fn from_sys(options: Ownership) -> Self { #[cfg_attr(not(feature = "test"), allow(unused_mut))] let mut options = Self { raw: Some(options), #[cfg(feature = "test")] dsn: None, before_send: None, }; #[cfg(feature = "test")] { if let Some(Ownership::Owned(_)) = options.raw { // will be set up properly for us inside those functions options.set_database_path(".sentry-native"); options.set_handler_path(""); options.set_dsn( &env::var("SENTRY_DSN") .expect("tests require a valid `SENTRY_DSN` environment variable"), ) } } options } /// Yields a pointer to [`sys::Options`], ownership is retained. fn as_ref(&self) -> *const sys::Options { match self.raw.expect("use after free") { Ownership::Owned(options) => options, Ownership::Borrowed(options) => options, } } /// Yields a mutable pointer to [`sys::Options`], ownership is retained. fn as_mut(&mut self) -> *mut sys::Options { if let Ownership::Owned(options) = self.raw.expect("use after free") { options } else { unreachable!("can't mutably borrow `Options`") } } /// Sets a custom transport. This only affects events sent through /// [`Event::capture`], not the crash handler. /// /// The `startup` parameter is a function that serves as a one-time /// initialization event for your [`Transport`], it takes a /// [`&Options`](Options) and has to return a [`Transport`]. /// /// # Notes /// Unwinding panics of functions in `transport` will be cought and /// [`abort`] will be called if any occured. /// /// # Examples /// ``` /// # use sentry_contrib_native::{Options, RawEnvelope}; /// let mut options = Options::new(); /// options.set_transport(|_| { /// |envelope: RawEnvelope| println!("Event to be sent: {:?}", envelope.event()) /// }); /// ``` /// See [`Transport`] for a more detailed documentation. pub fn set_transport< S: (FnOnce(&Self) -> T) + 'static + Send + Sync, T: Into<Box<T>> + Transport, >( &mut self, startup: S, ) { let startup = TransportState::Startup(Box::new(|options: &Self| startup(options).into())); let startup = Box::into_raw(Box::new(Some(startup))); unsafe { let transport = sys::transport_new(Some(transport::send)); sys::transport_set_state(transport, startup.cast()); sys::transport_set_startup_func(transport, Some(transport::startup)); sys::transport_set_shutdown_func(transport, Some(transport::shutdown)); sys::options_set_transport(self.as_mut(), transport) } } /// Sets a callback that is triggered before sending an event through /// [`Event::capture`]. /// /// # Notes /// Unwinding panics of functions in `before_send` will be cought and /// [`abort`] will be called if any occured. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_before_send(|mut value| { /// // do something with the value and then return it /// value /// }); /// ``` pub fn set_before_send<B: Into<Box<B>> + BeforeSend>(&mut self, before_send: B) { let fun = Box::into_raw(Box::<Box<dyn BeforeSend>>::new(before_send.into())); self.before_send = Some(unsafe { Box::from_raw(fun) }); unsafe { sys::options_set_before_send(self.as_mut(), Some(before_send::before_send), fun.cast()) } } /// Sets the DSN. /// /// # Panics /// Panics if `dsn` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_dsn("yourdsn.com"); /// ``` pub fn set_dsn<S: Into<String>>(&mut self, dsn: S) { #[cfg(feature = "test")] let dsn = { self.dsn = Some(dsn.into()); env::var("SENTRY_DSN") .expect("tests require a valid `SENTRY_DSN` environment variable") .into_cstring() }; #[cfg(not(feature = "test"))] let dsn = dsn.into().into_cstring(); unsafe { sys::options_set_dsn(self.as_mut(), dsn.as_ptr()) } } /// Gets the DSN. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_dsn("yourdsn.com"); /// /// assert_eq!(Some("yourdsn.com"), options.dsn()); /// ``` #[must_use] pub fn dsn(&self) -> Option<&str> { #[cfg(feature = "test")] if let Some(Ownership::Owned(_)) = self.raw { return self.dsn.as_deref(); } unsafe { sys::options_get_dsn(self.as_ref()).as_str() } } /// Sets the sample rate, which should be a [`f64`] between `0.0` and `1.0`. /// Sentry will randomly discard any event that is captured using [`Event`] /// when a sample rate < 1.0 is set. /// /// # Errors /// Fails with [`Error::SampleRateRange`] if `sample_rate` is smaller than /// `0.0` or bigger than `1.0`. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_sample_rate(0.5); /// ``` pub fn set_sample_rate(&mut self, sample_rate: f64) -> Result<(), Error> { if sample_rate >= 0. && sample_rate <= 1. { unsafe { sys::options_set_sample_rate(self.as_mut(), sample_rate) }; Ok(()) } else { Err(Error::SampleRateRange) } } /// Gets the sample rate. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// # fn main() -> anyhow::Result<()> { /// let mut options = Options::new(); /// options.set_sample_rate(0.5)?; /// /// assert_eq!(0.5, options.sample_rate()); /// # Ok(()) } /// ``` #[must_use] pub fn sample_rate(&self) -> f64 { unsafe { sys::options_get_sample_rate(self.as_ref()) } } /// Sets the release. /// /// # Panics /// Panics if `release` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_release("1.0"); /// ``` pub fn set_release<S: Into<String>>(&mut self, release: S) { let release = release.into().into_cstring(); unsafe { sys::options_set_release(self.as_mut(), release.as_ptr()) } } /// Gets the release. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_release("1.0"); /// /// assert_eq!(Some("1.0"), options.release()); /// ``` #[must_use] pub fn release(&self) -> Option<&str> { unsafe { sys::options_get_release(self.as_ref()).as_str() } } /// Sets the environment. /// /// # Panics /// Panics if `environment` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_environment("production"); /// ``` pub fn set_environment<S: Into<String>>(&mut self, environment: S) { let environment = environment.into().into_cstring(); unsafe { sys::options_set_environment(self.as_mut(), environment.as_ptr()) } } /// Gets the environment. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_environment("production"); /// /// assert_eq!(Some("production"), options.environment()); /// ``` #[must_use] pub fn environment(&self) -> Option<&str> { unsafe { sys::options_get_environment(self.as_ref()).as_str() } } /// Sets the distribution. /// /// # Panics /// Panics if `distribution` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_distribution("release-pgo"); /// ``` pub fn set_distribution<S: Into<String>>(&mut self, distribution: S) { let distribution = distribution.into().into_cstring(); unsafe { sys::options_set_dist(self.as_mut(), distribution.as_ptr()) } } /// Gets the distribution. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_distribution("release-pgo"); /// /// assert_eq!(Some("release-pgo"), options.distribution()); /// ``` #[must_use] pub fn distribution(&self) -> Option<&str> { unsafe { sys::options_get_dist(self.as_ref()).as_str() } } /// Configures the http proxy. /// /// # Panics /// Panics if `proxy` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_http_proxy("1.1.1.1"); /// ``` pub fn set_http_proxy<S: Into<String>>(&mut self, proxy: S) { let proxy = proxy.into().into_cstring(); unsafe { sys::options_set_http_proxy(self.as_mut(), proxy.as_ptr()) } } /// Returns the configured http proxy. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_http_proxy("1.1.1.1"); /// /// assert_eq!(Some("1.1.1.1"), options.http_proxy()); /// ``` #[must_use] pub fn http_proxy(&self) -> Option<&str> { unsafe { sys::options_get_http_proxy(self.as_ref()).as_str() } } /// Configures the path to a file containing SSL certificates for /// verification. /// /// # Panics /// Panics if `path` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_ca_certs("certs.pem"); /// ``` pub fn set_ca_certs<S: Into<String>>(&mut self, path: S) { let path = path.into().into_cstring(); unsafe { sys::options_set_ca_certs(self.as_mut(), path.as_ptr()) } } /// Returns the configured path for CA certificates. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_ca_certs("certs.pem"); /// /// assert_eq!(Some("certs.pem"), options.ca_certs()); /// ``` #[must_use] pub fn ca_certs(&self) -> Option<&str> { unsafe { sys::options_get_ca_certs(self.as_ref()).as_str() } } /// Enables or disables debug printing mode. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_debug(true); /// ``` pub fn set_debug(&mut self, debug: bool) { let debug = debug.into(); unsafe { sys::options_set_debug(self.as_mut(), debug) } } /// Returns the current value of the debug flag. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_debug(true); /// /// assert!(options.debug()); /// ``` #[must_use] pub fn debug(&self) -> bool { match unsafe { sys::options_get_debug(self.as_ref()) } { 0 => false, 1 => true, error => unreachable!("{} couldn't be converted to a bool", error), } } /// Sets a callback that is used for logging purposes when /// [`Options::debug`] is `true`. /// /// # Notes /// Unwinding panics in `logger` will be cought and [`abort`] /// will be called if any occured. /// /// # Examples /// ``` /// # use sentry_contrib_native::{Level, Options}; /// # use std::iter::FromIterator; /// let mut options = Options::new(); /// options.set_debug(true); /// options.set_logger(|level, message| { /// println!("[{}]: {}", level, message); /// }); /// ``` pub fn set_logger<L: Into<Box<L>> + Fn(Level, Message) + 'static + Send + Sync>( &mut self, logger: L, ) { *LOGGER.write().expect("failed to set `LOGGER`") = Some(logger.into()); unsafe { sys::options_set_logger(self.as_mut(), Some(logger::logger)) } } /// Enables or disabled user consent requirements for uploads. /// /// This disables uploads until the user has given the consent to the SDK. /// Consent itself is given with [`user_consent_give`] and revoked with /// [`user_consent_revoke`]. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_require_user_consent(true); /// ``` pub fn set_require_user_consent(&mut self, val: bool) { let val = val.into(); unsafe { sys::options_set_require_user_consent(self.as_mut(), val) } } /// Returns `true` if user consent is required. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_require_user_consent(true); /// /// assert!(options.require_user_consent()); /// ``` #[must_use] pub fn require_user_consent(&self) -> bool { match unsafe { sys::options_get_require_user_consent(self.as_ref()) } { 0 => false, 1 => true, error => unreachable!("{} couldn't be converted to a bool", error), } } /// Enables or disables on-device symbolication of stack traces. /// /// This feature can have a performance impact, and is enabled by default on /// Android. It is usually only needed when it is not possible to provide /// debug information files for system libraries which are needed for /// serverside symbolication. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_symbolize_stacktraces(true); /// ``` pub fn set_symbolize_stacktraces(&mut self, val: bool) { let val = val.into(); unsafe { sys::options_set_symbolize_stacktraces(self.as_mut(), val) } } /// Returns `true` if on-device symbolication of stack traces is enabled. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_symbolize_stacktraces(true); /// /// assert!(options.symbolize_stacktraces()); /// ``` #[must_use] pub fn symbolize_stacktraces(&self) -> bool { match unsafe { sys::options_get_symbolize_stacktraces(self.as_ref()) } { 0 => false, 1 => true, error => unreachable!("{} couldn't be converted to a bool", error), } } /// Adds a new attachment to be sent along. /// /// # Panics /// Panics if `name` or `path` contain any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.add_attachment("test attachment", "server.log"); /// ``` pub fn add_attachment<S: Into<String>, P: Into<PathBuf>>(&mut self, name: S, path: P) { let name = name.into().into_cstring(); let path = path.into().into_os_vec(); #[cfg(windows)] unsafe { sys::options_add_attachmentw(self.as_mut(), name.as_ptr(), path.as_ptr()) }; #[cfg(not(windows))] unsafe { sys::options_add_attachment(self.as_mut(), name.as_ptr(), path.as_ptr()) } } /// Sets the path to the crashpad handler if the crashpad backend is used. /// /// The path defaults to the `crashpad_handler`/`crashpad_handler.exe` /// executable, depending on platform, which is expected to be present in /// the same directory as the app executable. /// /// It is recommended that library users set an explicit handler path, /// depending on the directory/executable structure of their app. /// /// # Panics /// Panics if `path` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_handler_path("crashpad_handler"); /// ``` #[cfg_attr( all(feature = "test", any(windows, target_os = "macos")), allow(clippy::needless_pass_by_value) )] pub fn set_handler_path<P: Into<PathBuf>>( &mut self, #[cfg(not(all(feature = "test", any(windows, target_os = "macos"))))] path: P, #[cfg(all(feature = "test", any(windows, target_os = "macos")))] _path: P, ) { #[cfg(all(feature = "test", any(windows, target_os = "macos")))] let path = PathBuf::from(env!("CRASHPAD_HANDLER")).into_os_vec(); #[cfg(not(all(feature = "test", any(windows, target_os = "macos"))))] let path = path.into().into_os_vec(); #[cfg(windows)] unsafe { sys::options_set_handler_pathw(self.as_mut(), path.as_ptr()) }; #[cfg(not(windows))] unsafe { sys::options_set_handler_path(self.as_mut(), path.as_ptr()) } } /// Sets the path to the Sentry database directory. /// /// Sentry will use this path to persist user consent, sessions, and other /// artifacts in case of a crash. This will also be used by the crashpad /// backend if it is configured. /// /// The path defaults to `.sentry-native` in the current working directory, /// will be created if it does not exist, and will be resolved to an /// absolute path inside of [`Options::init`]. /// /// It is recommended that library users set an explicit absolute path, /// depending on their apps runtime directory. /// /// # Panics /// Panics if `path` contains any null bytes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_database_path(".sentry-native"); /// ``` pub fn set_database_path<P: Into<PathBuf>>(&mut self, path: P) { #[cfg(feature = "test")] let path = PathBuf::from(env!("OUT_DIR")) .join(path.into()) .into_os_vec(); #[cfg(not(feature = "test"))] let path = path.into().into_os_vec(); #[cfg(windows)] unsafe { sys::options_set_database_pathw(self.as_mut(), path.as_ptr()) }; #[cfg(not(windows))] unsafe { sys::options_set_database_path(self.as_mut(), path.as_ptr()) }; } /// Enables forwarding to the system crash reporter. Disabled by default. /// /// This setting only has an effect when using Crashpad on macOS. If /// enabled, Crashpad forwards crashes to the macOS system crash reporter. /// Depending on the crash, this may impact the crash time. Even if enabled, /// Crashpad may choose not to forward certain crashes. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// let mut options = Options::new(); /// options.set_system_crash_reporter(true); /// ``` pub fn set_system_crash_reporter(&mut self, enabled: bool) { let enabled = enabled.into(); unsafe { sys::options_set_system_crash_reporter_enabled(self.as_mut(), enabled) } } /// Initializes the Sentry SDK with the specified options. Make sure to /// capture the resulting [`Shutdown`], this makes sure to automatically /// call [`shutdown`] when it drops. /// /// # Errors /// Fails with [`Error::Init`] if Sentry couldn't initialize - should only /// occur in these situations: /// - Fails to create database directory. /// - Fails to lock database directory. /// /// # Panics /// Panics if `init` was already called once before. /// /// # Examples /// ``` /// # use sentry_contrib_native::Options; /// # fn main() -> anyhow::Result<()> { /// let _shutdown = Options::new().init()?; /// # Ok(()) } /// ``` pub fn init(mut self) -> Result<Shutdown, Error> { let mut lock = global_write(); // make sure we aren't initializing Sentry twice if *lock { panic!("already initialized Sentry once") } // disolve `Options`, `sys::init` is going to take ownership now let options = if let Ownership::Owned(options) = self.raw.take().expect("use after free") { options } else { unreachable!("can't mutably borrow `Options`") }; match unsafe { sys::init(options) } { 0 => { *lock = true; // store `before_send` data so we can deallocate it later if let Some(before_send) = self.before_send.take() { BEFORE_SEND .set(Mutex::new(Some(before_send))) .map_err(|_| ()) .expect("`BEFORE_SEND` was set once before"); } drop(lock); Ok(Shutdown) } _ => Err(Error::Init), } } } /// Automatically shuts down the Sentry client on drop. /// /// # Examples /// ``` /// # use anyhow::Result; /// # use sentry_contrib_native::{Options, Shutdown}; /// fn main() -> Result<()> { /// let options = Options::new(); /// let _shutdown: Shutdown = options.init()?; /// /// // ... /// // your application code /// // ... /// /// Ok(()) /// // Sentry client will automatically shutdown because `Shutdown` is leaving context /// } /// ``` #[derive(Clone, Debug, Hash, Eq, Ord, PartialEq, PartialOrd)] pub struct Shutdown; impl Drop for Shutdown { fn drop(&mut self) { crate::shutdown(); } } impl Shutdown { /// Disable automatic shutdown. Call [`shutdown`] manually to force /// transports to flush out before the program exits. /// /// # Examples /// ``` /// # use anyhow::Result; /// # use sentry_contrib_native::{Options, shutdown}; /// fn main() -> Result<()> { /// sentry_init()?; /// /// // ... /// // your application code /// // ... /// /// // call shutdown manually to make sure transports flush out /// shutdown(); /// Ok(()) /// } /// /// fn sentry_init() -> Result<()> { /// let options = Options::new(); /// // call forget because we are leaving the context and we don't want to shut down the Sentry client yet /// options.init()?.forget(); /// Ok(()) /// } /// ``` pub fn forget(self) { mem::forget(self) } /// Manually shutdown. /// /// # Examples /// ``` /// # use anyhow::Result; /// # use sentry_contrib_native::Options; /// fn main() -> Result<()> { /// let options = Options::new(); /// let shutdown = options.init()?; /// /// // ... /// // your application code /// // ... /// /// // call shutdown manually to make sure transports flush out /// shutdown.shutdown(); /// Ok(()) /// } /// ``` pub fn shutdown(self) { drop(self) } } #[test] fn options() -> anyhow::Result<()> { use crate::{RawEnvelope, Value}; struct CustomTransport; impl CustomTransport { const fn new(_: &Options) -> Self { Self } } impl Transport for CustomTransport { fn send(&self, _: RawEnvelope) {} } struct Filter; impl BeforeSend for Filter { fn before_send(&self, value: Value) -> Value { value } } let mut options = Options::new(); options.set_transport(|_| |_| {}); options.set_transport(CustomTransport::new); options.set_before_send(|value| value); options.set_before_send(Filter); options.set_dsn("yourdsn.com"); assert_eq!(Some("yourdsn.com"), options.dsn()); let sample_rate = 0.5; options.set_sample_rate(sample_rate)?; #[allow(clippy::float_cmp)] { assert_eq!(sample_rate, options.sample_rate()); } options.set_release("1.0"); assert_eq!(Some("1.0"), options.release()); options.set_environment("production"); assert_eq!(Some("production"), options.environment()); options.set_distribution("release-pgo"); assert_eq!(Some("release-pgo"), options.distribution()); options.set_http_proxy("1.1.1.1"); assert_eq!(Some("1.1.1.1"), options.http_proxy()); options.set_ca_certs("certs.pem"); assert_eq!(Some("certs.pem"), options.ca_certs()); options.set_debug(true); assert!(options.debug()); options.set_logger(|_, _| ()); options.set_require_user_consent(true); assert!(options.require_user_consent()); options.set_symbolize_stacktraces(true); assert!(options.symbolize_stacktraces()); options.add_attachment("test attachment", "server.log"); options.set_handler_path("crashpad_handler"); options.set_database_path(".sentry-native"); options.set_system_crash_reporter(true); Ok(()) } #[cfg(test)] #[rusty_fork::test_fork(timeout_ms = 60000)] #[should_panic] fn options_fail() -> anyhow::Result<()> { Options::new().init()?; Options::new().init()?; Ok(()) } #[cfg(test)] #[rusty_fork::test_fork(timeout_ms = 60000)] fn threaded_stress() -> anyhow::Result<()> { use crate::test; use std::{ convert::TryFrom, sync::{Arc, Mutex, MutexGuard}, thread, }; fn spawns(tests: Vec<fn(MutexGuard<Options>, usize)>) -> Options { let options = Arc::new(Mutex::new(Options::new())); let mut spawns = Vec::with_capacity(tests.len()); for test in tests { let options = Arc::clone(&options); let handle = thread::spawn(move || { let mut handles = Vec::with_capacity(100); for index in 0..100 { let options = Arc::clone(&options); handles.push(thread::spawn(move || { let options = options.lock().unwrap(); test(options, index) })) } handles }); spawns.push(handle) } for spawn in spawns { for handle in spawn.join().unwrap() { handle.join().unwrap() } } Arc::try_unwrap(options).unwrap().into_inner().unwrap() } test::set_hook(); let options = spawns(vec![ |mut options, _| options.set_before_send(|value| value), |mut options, index| options.set_dsn(index.to_string()), |options, _| println!("{:?}", options.dsn()), |mut options, index| { let sample_rate = f64::from(u32::try_from(index).unwrap()) / 100.; options.set_sample_rate(sample_rate).unwrap() }, |options, _| println!("{:?}", options.sample_rate()), |mut options, index| options.set_release(index.to_string()), |options, _| println!("{:?}", options.release()), |mut options, index| options.set_environment(index.to_string()), |options, _| println!("{:?}", options.environment()), |mut options, index| options.set_distribution(index.to_string()), |options, _| println!("{:?}", options.distribution()), |mut options, index| options.set_http_proxy(index.to_string()), |options, _| println!("{:?}", options.http_proxy()), |mut options, index| options.set_ca_certs(index.to_string()), |options, _| println!("{:?}", options.ca_certs()), |mut options, index| { options.set_debug(match index % 2 { 0 => false, 1 => true, _ => unreachable!(), }) }, |options, _| println!("{:?}", options.debug()), |mut options, index| { options.set_require_user_consent(match index % 2 { 0 => false, 1 => true, _ => unreachable!(), }) }, |options, _| println!("{:?}", options.require_user_consent()), |mut options, index| { options.set_symbolize_stacktraces(match index % 2 { 0 => false, 1 => true, _ => unreachable!(), }) }, |options, _| println!("{:?}", options.symbolize_stacktraces()), |mut options, index| options.add_attachment(index.to_string(), index.to_string()), |mut options, index| options.set_handler_path(index.to_string()), |mut options, index| options.set_database_path(index.to_string()), |mut options, index| { options.set_system_crash_reporter(match index % 2 { 0 => false, 1 => true, _ => unreachable!(), }) }, ]); options.init()?.shutdown(); test::verify_panics(); Ok(()) } #[cfg(test)] #[rusty_fork::test_fork(timeout_ms = 60000)] fn sync() -> anyhow::Result<()> { use crate::test; use anyhow::{anyhow, Result}; use std::{sync::Arc, thread}; test::set_hook(); let mut options = Options::new(); options.set_debug(true); let options = Arc::new(options); let mut handles = vec![]; for _ in 0..100 { let options = Arc::clone(&options); let handle = thread::spawn(move || { println!("{}", options.debug()); }); handles.push(handle); } for handle in handles { handle.join().unwrap(); } thread::spawn(move || -> Result<Shutdown> { Arc::try_unwrap(options) .map_err(|_| anyhow!("failed to unwrap arc"))? .init() .map_err(Into::into) }) .join() .unwrap()? .shutdown(); test::verify_panics(); Ok(()) }