Skip to main content

mysten_common/
logging.rs

1// Copyright (c) Mysten Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use crate::in_test_configuration;
5use once_cell::sync::Lazy;
6
7#[macro_export]
8macro_rules! fatal {
9    ($msg:literal $(, $arg:expr)*) => {{
10        if $crate::in_antithesis() {
11            let full_msg = format!($msg $(, $arg)*);
12            let json = $crate::logging::json!({ "message": full_msg });
13            $crate::logging::assert_unreachable_antithesis!($msg, &json);
14        }
15        tracing::error!(fatal = true, $msg $(, $arg)*);
16        panic!($msg $(, $arg)*);
17    }};
18}
19
20pub use antithesis_sdk::assert_reachable as assert_reachable_antithesis;
21pub use antithesis_sdk::assert_sometimes as assert_sometimes_antithesis;
22pub use antithesis_sdk::assert_unreachable as assert_unreachable_antithesis;
23
24pub use serde_json::json;
25
26#[inline(always)]
27pub fn crash_on_debug() -> bool {
28    static CRASH_ON_DEBUG: Lazy<bool> = Lazy::new(|| {
29        in_test_configuration() || std::env::var("SUI_ENABLE_DEBUG_ASSERTIONS").is_ok()
30    });
31
32    *CRASH_ON_DEBUG
33}
34
35#[cfg(msim)]
36pub mod intercept_debug_fatal {
37    use std::sync::{Arc, Mutex};
38
39    #[derive(Clone)]
40    pub struct DebugFatalCallback {
41        pub pattern: String,
42        pub callback: Arc<dyn Fn() + Send + Sync>,
43    }
44
45    static INTERCEPT_DEBUG_FATAL: Mutex<Option<DebugFatalCallback>> = Mutex::new(None);
46
47    pub fn register_callback(message: &str, f: impl Fn() + Send + Sync + 'static) {
48        *INTERCEPT_DEBUG_FATAL.lock().unwrap() = Some(DebugFatalCallback {
49            pattern: message.to_string(),
50            callback: Arc::new(f),
51        });
52    }
53
54    pub fn get_callback() -> Option<DebugFatalCallback> {
55        INTERCEPT_DEBUG_FATAL.lock().unwrap().clone()
56    }
57}
58
59#[macro_export]
60macro_rules! register_debug_fatal_handler {
61    ($message:literal, $f:expr) => {
62        #[cfg(msim)]
63        $crate::logging::intercept_debug_fatal::register_callback($message, $f);
64
65        #[cfg(not(msim))]
66        {
67            // silence unused variable warnings from the body of the callback
68            let _ = $f;
69        }
70    };
71}
72
73/// Like `debug_fatal!`, but records `$location` (a `&str`) as the
74/// `system_invariant_violations` metric label instead of the macro's own
75/// `file!():line!()`. Use this when forwarding a caller-supplied location
76/// (e.g. from `#[track_caller]` + `Location::caller()`) so the metric points
77/// at the user's call site rather than the wrapper.
78#[macro_export]
79macro_rules! debug_fatal_at {
80    ($location:expr, $msg:literal $(, $arg:expr)*) => {{
81        loop {
82            #[cfg(msim)]
83            {
84                if let Some(cb) = $crate::logging::intercept_debug_fatal::get_callback() {
85                    tracing::error!($msg $(, $arg)*);
86                    let msg = format!($msg $(, $arg)*);
87                    if msg.contains(&cb.pattern) {
88                        (cb.callback)();
89                    }
90                    break;
91                }
92            }
93
94            // In antithesis, rather than crashing, we will use the assert_unreachable_antithesis
95            // macro to catch the signal that something has gone wrong.
96            if !$crate::in_antithesis() && $crate::logging::crash_on_debug() {
97                $crate::fatal!($msg $(, $arg)*);
98            } else {
99                let stacktrace = std::backtrace::Backtrace::capture();
100                tracing::error!(debug_fatal = true, stacktrace = ?stacktrace, $msg $(, $arg)*);
101                let location: &str = $location;
102                if let Some(metrics) = mysten_metrics::get_metrics() {
103                    metrics.system_invariant_violations.with_label_values(&[location]).inc();
104                }
105                if $crate::in_antithesis() {
106                    // antithesis requires a literal for first argument. pass the formatted argument
107                    // as a string.
108                    let full_msg = format!($msg $(, $arg)*);
109                    let json = $crate::logging::json!({ "message": full_msg });
110                    $crate::logging::assert_unreachable_antithesis!($msg, &json);
111                }
112            }
113            break;
114        }
115    }};
116}
117
118#[macro_export]
119macro_rules! debug_fatal {
120    //($msg:literal $(, $arg:expr)* $(,)?)
121    ($msg:literal $(, $arg:expr)*) => {{
122        $crate::debug_fatal_at!(concat!(file!(), ':', line!()), $msg $(, $arg)*);
123    }};
124}
125
126#[macro_export]
127macro_rules! debug_fatal_no_invariant {
128    ($msg:literal $(, $arg:expr)*) => {{
129        loop {
130            #[cfg(msim)]
131            {
132                if let Some(cb) = $crate::logging::intercept_debug_fatal::get_callback() {
133                    tracing::error!($msg $(, $arg)*);
134                    let msg = format!($msg $(, $arg)*);
135                    if msg.contains(&cb.pattern) {
136                        (cb.callback)();
137                    }
138                    break;
139                }
140            }
141
142            if !$crate::in_antithesis() && $crate::logging::crash_on_debug() {
143                $crate::fatal!($msg $(, $arg)*);
144            } else {
145                tracing::error!($msg $(, $arg)*);
146                if $crate::in_antithesis() {
147                    let full_msg = format!($msg $(, $arg)*);
148                    let json = $crate::logging::json!({ "message": full_msg });
149                    $crate::logging::assert_unreachable_antithesis!($msg, &json);
150                }
151            }
152            break;
153        }
154    }};
155}
156
157#[macro_export]
158macro_rules! assert_reachable {
159    () => {
160        $crate::logging::assert_reachable!("");
161    };
162    ($message:literal) => {{
163        // calling in to antithesis sdk breaks determinisim in simtests (on linux only)
164        if !cfg!(msim) {
165            $crate::logging::assert_reachable_antithesis!($message);
166        } else {
167            $crate::assert_reachable_simtest!($message);
168        }
169    }};
170}
171
172#[macro_export]
173macro_rules! assert_sometimes {
174    ($expr:expr, $message:literal) => {{
175        // calling in to antithesis sdk breaks determinisim in simtests (on linux only)
176        if !cfg!(msim) {
177            $crate::logging::assert_sometimes_antithesis!($expr, $message);
178        } else {
179            $crate::assert_sometimes_simtest!($expr, $message);
180        }
181    }};
182}
183
184mod tests {
185    #[test]
186    #[should_panic]
187    fn test_fatal() {
188        fatal!("This is a fatal error");
189    }
190
191    #[test]
192    #[should_panic]
193    fn test_debug_fatal() {
194        if cfg!(debug_assertions) {
195            debug_fatal!("This is a debug fatal error");
196        } else {
197            // pass in release mode as well
198            fatal!("This is a fatal error");
199        }
200    }
201
202    #[cfg(not(debug_assertions))]
203    #[test]
204    fn test_debug_fatal_release_mode() {
205        debug_fatal!("This is a debug fatal error");
206    }
207
208    #[test]
209    fn test_assert_sometimes_side_effects() {
210        let mut x = 0;
211
212        let mut inc = || {
213            x += 1;
214            true
215        };
216
217        assert_sometimes!(inc(), "");
218        assert_eq!(x, 1);
219    }
220}