use super::*;
crate::euv_devtools_only_items! {
#[must_use]
pub(crate) fn copy_utf8_truncated(text: &str, dest: &mut [u8]) -> usize {
let bytes: &[u8] = text.as_bytes();
let max_len: usize = bytes.len().min(dest.len());
let mut valid_len: usize = max_len;
while valid_len > 0 && !text.is_char_boundary(valid_len) {
valid_len -= 1;
}
dest[..valid_len].copy_from_slice(&bytes[..valid_len]);
valid_len
}
#[must_use]
fn runtime_context_lock() -> &'static Mutex<InlineRuntimeContextState> {
PANIC_RUNTIME_CONTEXT.get_or_init(|| Mutex::new(InlineRuntimeContextState::new_default()))
}
}
#[must_use]
fn panic_ring_lock() -> &'static Mutex<VecDeque<PanicForensicsRecord>> {
PANIC_FORENSICS_RING
.get_or_init(|| Mutex::new(VecDeque::with_capacity(PANIC_FORENSICS_RING_CAPACITY)))
}
#[must_use]
pub fn format_utc_timestamp_now() -> String {
#[cfg(target_arch = "wasm32")]
{
PANIC_WASM_TIMESTAMP.to_string()
}
#[cfg(not(target_arch = "wasm32"))]
{
let secs_total: u64 = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|delta: Duration| delta.as_secs())
.unwrap_or(0);
format_unix_secs_utc(secs_total)
}
}
#[cfg(not(target_arch = "wasm32"))]
#[must_use]
pub fn format_unix_secs_utc(secs_total: u64) -> String {
let days_since_epoch: i64 = (secs_total / 86_400) as i64;
let secs_of_day: u64 = secs_total % 86_400;
let hour: u64 = secs_of_day / 3_600;
let minute: u64 = (secs_of_day % 3_600) / 60;
let second: u64 = secs_of_day % 60;
let shifted: i64 = days_since_epoch + 719_468;
let era: i64 = if shifted >= 0 {
shifted
} else {
shifted - 146_096
} / 146_097;
let day_of_era: u64 = (shifted - era * 146_097) as u64;
let year_of_era: u64 =
(day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
let year_base: i64 = (year_of_era as i64) + era * 400;
let day_of_year: u64 = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
let month_prime: u64 = (5 * day_of_year + 2) / 153;
let day: u64 = day_of_year - (153 * month_prime + 2) / 5 + 1;
let month: u64 = if month_prime < 10 {
month_prime + 3
} else {
month_prime - 9
};
let year: i64 = if month <= 2 { year_base + 1 } else { year_base };
format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
}
#[must_use]
fn capture_forced_backtrace(message: &str) -> (String, Vec<String>) {
#[cfg(not(target_arch = "wasm32"))]
{
let _: &str = message;
let raw_backtrace: String = Backtrace::force_capture().to_string();
let frames: Vec<String> = raw_backtrace
.lines()
.map(str::trim)
.filter(|line: &&str| !line.is_empty())
.map(str::to_string)
.collect();
(raw_backtrace, frames)
}
#[cfg(target_arch = "wasm32")]
{
let js_error: JsValue = js_sys::Error::new(message).into();
let raw_backtrace: String = Reflect::get(&js_error, &JsValue::from_str(PANIC_JS_STACK_KEY))
.ok()
.and_then(|val: JsValue| val.as_string())
.unwrap_or_default();
let frames: Vec<String> = raw_backtrace
.lines()
.map(str::trim)
.filter(|line: &&str| !line.is_empty())
.map(str::to_string)
.collect();
(raw_backtrace, frames)
}
}
#[must_use]
fn extract_hook_message(info: &PanicHookInfo<'_>) -> String {
if let Some(static_msg) = info.payload().downcast_ref::<&str>() {
return (*static_msg).to_string();
}
if let Some(owned_msg) = info.payload().downcast_ref::<String>() {
return owned_msg.clone();
}
PANIC_FALLBACK_PAYLOAD.to_string()
}
pub fn record_runtime_breadcrumb(kind: &str, detail: &str) {
crate::euv_devtools_or_prod! {
devtools => {
if let Ok(mut guard) = runtime_context_lock().try_lock() {
guard.push_breadcrumb(kind, detail);
}
},
prod => {
let _: (&str, &str) = (kind, detail);
},
}
}
pub fn update_runtime_context(
active_route: Option<&str>,
viewport_scale: Option<(f32, f32, f32)>,
theme: Option<&str>,
active_overlays_csv: Option<&str>,
frame_seq: Option<u64>,
is_idle: Option<bool>,
) {
crate::euv_devtools_or_prod! {
devtools => {
if let Ok(mut guard) = runtime_context_lock().try_lock() {
if let Some(route_val) = active_route {
guard.route_len = copy_utf8_truncated(route_val, &mut guard.route_buf);
guard.push_breadcrumb(PANIC_BREADCRUMB_KIND_ROUTE, route_val);
}
if let Some((width_val, height_val, scale_val)) = viewport_scale {
guard.viewport_width = width_val;
guard.viewport_height = height_val;
guard.scale_factor = scale_val;
}
if let Some(theme_val) = theme {
guard.theme_len = copy_utf8_truncated(theme_val, &mut guard.theme_buf);
}
if let Some(overlays_val) = active_overlays_csv {
guard.overlays_len = copy_utf8_truncated(overlays_val, &mut guard.overlays_buf);
if !overlays_val.is_empty() {
guard.push_breadcrumb(PANIC_BREADCRUMB_KIND_OVERLAY, overlays_val);
}
}
if let Some(seq_val) = frame_seq {
guard.frame_seq = seq_val;
}
if let Some(idle_val) = is_idle {
let prev_idle: bool = guard.is_idle;
guard.is_idle = idle_val;
if prev_idle != idle_val {
let detail: &str = if idle_val {
PANIC_IDLE_ENTERED_DETAIL
} else {
PANIC_IDLE_RESUMED_DETAIL
};
guard.push_breadcrumb(PANIC_BREADCRUMB_KIND_IDLE, detail);
}
}
}
},
prod => {
let _: Option<&str> = active_route;
let _: Option<(f32, f32, f32)> = viewport_scale;
let _: Option<&str> = theme;
let _: Option<&str> = active_overlays_csv;
let _: Option<u64> = frame_seq;
let _: Option<bool> = is_idle;
},
}
}
pub(crate) fn record_window_event_breadcrumb(event: &WindowEvent) {
crate::euv_devtools_or_prod! {
devtools => {
let detail: &str = match event {
WindowEvent::Resized(..) => PANIC_EVENT_RESIZE,
WindowEvent::SafeAreaChanged(..) => PANIC_EVENT_SAFE_AREA,
WindowEvent::ThemeChanged(..) => PANIC_EVENT_THEME_CHANGE,
WindowEvent::Focused(..) => PANIC_EVENT_FOCUSED,
WindowEvent::CloseRequested(_) => PANIC_EVENT_CLOSE_REQUEST,
WindowEvent::Lifecycle(_) => PANIC_EVENT_LIFECYCLE,
WindowEvent::DeepLink(_) => PANIC_EVENT_DEEP_LINK,
WindowEvent::System(_) => PANIC_EVENT_SYSTEM_EVT,
WindowEvent::PointerMove(..) => PANIC_EVENT_POINTER_MOVE,
WindowEvent::PointerDown(..) => PANIC_EVENT_POINTER_DOWN,
WindowEvent::PointerUp(..) => PANIC_EVENT_POINTER_UP,
WindowEvent::PointerCancel(..) => PANIC_EVENT_POINTER_CANCEL,
WindowEvent::Scroll(..) => PANIC_EVENT_SCROLL,
WindowEvent::KeyDown(..) => PANIC_EVENT_KEY_DOWN,
WindowEvent::KeyUp(..) => PANIC_EVENT_KEY_UP,
WindowEvent::TextInput(..) => PANIC_EVENT_TEXT_INPUT,
WindowEvent::Ime(..) => PANIC_EVENT_IME_EVENT,
WindowEvent::RedrawRequested(_) => PANIC_EVENT_REDRAW_REQUEST,
};
record_runtime_breadcrumb(PANIC_BREADCRUMB_KIND_EVENT, detail);
},
prod => {
let _: &WindowEvent = event;
},
}
}
#[must_use]
pub fn snapshot_runtime_context() -> PanicRuntimeContext {
crate::euv_devtools_or_prod! {
devtools => {
match runtime_context_lock().lock() {
Ok(guard) => guard.to_owned_context(),
Err(poisoned) => poisoned.into_inner().to_owned_context(),
}
},
prod => PanicRuntimeContext::default(),
}
}
#[must_use]
pub fn snapshot_runtime_breadcrumbs() -> Vec<RuntimeEventBreadcrumb> {
crate::euv_devtools_or_prod! {
devtools => {
match runtime_context_lock().lock() {
Ok(guard) => guard.snapshot_breadcrumbs(),
Err(poisoned) => poisoned.into_inner().snapshot_breadcrumbs(),
}
},
prod => Vec::new(),
}
}
pub fn reset_runtime_breadcrumbs() {
crate::euv_devtools_only! {
match runtime_context_lock().lock() {
Ok(mut guard) => {
*guard = InlineRuntimeContextState::new_default();
}
Err(poisoned) => {
let mut inner: MutexGuard<'_, InlineRuntimeContextState> = poisoned.into_inner();
*inner = InlineRuntimeContextState::new_default();
}
}
}
}
pub fn set_terminal_panic_restore_enabled(enabled: bool) {
PANIC_TERMINAL_RESTORE_ACTIVE.store(enabled, Ordering::Release);
}
#[must_use]
pub fn is_terminal_panic_restore_enabled() -> bool {
PANIC_TERMINAL_RESTORE_ACTIVE.load(Ordering::Acquire)
}
fn store_and_emit_panic_record(record: PanicForensicsRecord) {
let serialized_line: Option<String> = to_string(&record).ok();
#[cfg(not(target_arch = "wasm32"))]
{
if PANIC_TERMINAL_RESTORE_ACTIVE.swap(false, Ordering::AcqRel) {
let mut out_stream: io::Stdout = stdout();
let _: io::Result<()> = out_stream.write_all(PANIC_TERMINAL_RESTORE_SEQ.as_bytes());
let _: io::Result<()> = out_stream.flush();
}
if let Some(json_line) = serialized_line.as_deref() {
let mut err_stream: io::Stderr = stderr();
let _: io::Result<()> =
writeln!(err_stream, "{PANIC_FORENSICS_STDERR_PREFIX} {json_line}");
}
if let Ok(report_path) = env::var(ENV_EUV_PANIC_REPORT_PATH) {
let trimmed: &str = report_path.trim();
if !trimmed.is_empty()
&& let Ok(pretty_json) = to_string_pretty(&record)
{
let _: io::Result<()> = fs::write(trimmed, pretty_json);
}
}
}
#[cfg(target_arch = "wasm32")]
{
if let Some(json_line) = serialized_line.as_deref() {
if let Some(browser_window) = window() {
let _: Result<bool, JsValue> = Reflect::set(
browser_window.as_ref(),
&JsValue::from_str(PANIC_WASM_WINDOW_PROP),
&JsValue::from_str(json_line),
);
}
let line_msg: String = format!("{PANIC_FORENSICS_STDERR_PREFIX} {json_line}");
web_sys::console::error_1(&JsValue::from_str(&line_msg));
}
}
match panic_ring_lock().lock() {
Ok(mut ring) => {
while ring.len() >= PANIC_FORENSICS_RING_CAPACITY {
let _: Option<PanicForensicsRecord> = ring.pop_front();
}
ring.push_back(record);
}
Err(poisoned) => {
let mut ring: MutexGuard<'_, VecDeque<PanicForensicsRecord>> = poisoned.into_inner();
while ring.len() >= PANIC_FORENSICS_RING_CAPACITY {
let _: Option<PanicForensicsRecord> = ring.pop_front();
}
ring.push_back(record);
}
}
}
#[must_use]
fn capture_panic_forensics_from_hook(info: &PanicHookInfo<'_>) -> PanicForensicsRecord {
let timestamp_utc: String = format_utc_timestamp_now();
let message: String = extract_hook_message(info);
let (location_file, location_line, location_col): (String, u32, u32) = match info.location() {
Some(loc) => (loc.file().to_string(), loc.line(), loc.column()),
None => (PANIC_UNKNOWN_FILE.to_string(), 0, 0),
};
#[cfg(not(target_arch = "wasm32"))]
let thread_name: String = current().name().unwrap_or(PANIC_UNNAMED_THREAD).to_string();
#[cfg(target_arch = "wasm32")]
let thread_name: String = PANIC_WASM_THREAD_NAME.to_string();
let (raw_backtrace, backtrace_frames): (String, Vec<String>) =
capture_forced_backtrace(&message);
let runtime_context: PanicRuntimeContext = snapshot_runtime_context();
PanicForensicsRecord {
timestamp_utc,
message,
location_file,
location_line,
location_col,
thread_name,
backtrace_frames,
raw_backtrace,
runtime_context,
}
}
pub fn install_panic_forensics_hook() {
if PANIC_FORENSICS_INSTALLED
.compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
.is_err()
{
return;
}
crate::euv_devtools_only! {
let _: &Mutex<InlineRuntimeContextState> = runtime_context_lock();
}
let _: &Mutex<VecDeque<PanicForensicsRecord>> = panic_ring_lock();
let previous_hook: Box<dyn Fn(&PanicHookInfo<'_>) + Sync + Send + 'static> = take_hook();
set_hook(Box::new(move |info: &PanicHookInfo<'_>| {
let record: PanicForensicsRecord = capture_panic_forensics_from_hook(info);
store_and_emit_panic_record(record);
previous_hook(info);
}));
}
#[must_use]
pub fn is_panic_forensics_installed() -> bool {
PANIC_FORENSICS_INSTALLED.load(Ordering::Acquire)
}
#[must_use]
pub fn latest_panic_forensics() -> Option<PanicForensicsRecord> {
match panic_ring_lock().lock() {
Ok(ring) => ring.back().cloned(),
Err(poisoned) => poisoned.into_inner().back().cloned(),
}
}
#[must_use]
pub fn all_panic_forensics() -> Vec<PanicForensicsRecord> {
match panic_ring_lock().lock() {
Ok(ring) => ring.iter().cloned().collect(),
Err(poisoned) => poisoned.into_inner().iter().cloned().collect(),
}
}
#[must_use]
pub fn drain_panic_forensics() -> Vec<PanicForensicsRecord> {
match panic_ring_lock().lock() {
Ok(mut ring) => ring.drain(..).collect(),
Err(poisoned) => poisoned.into_inner().drain(..).collect(),
}
}
#[must_use]
pub fn panic_forensics_count() -> usize {
match panic_ring_lock().lock() {
Ok(ring) => ring.len(),
Err(poisoned) => poisoned.into_inner().len(),
}
}