#![cfg(feature = "debug")]
use once_cell::sync::Lazy;
use std::{
collections::HashMap,
sync::{
LockResult, Mutex,
atomic::{AtomicUsize, Ordering},
},
thread::{self, ThreadId},
};
use tracing::info;
pub type LockId = usize;
#[derive(Debug, Clone)]
pub enum LockState {
Held,
Waiting,
}
#[derive(Debug, Clone, Default)]
pub struct ThreadState {
pub name: String,
pub locks: HashMap<LockId, LockState>,
pub data: String,
pub status: String,
}
pub fn set_thread_status(status: String) {
let thread_id = thread::current().id();
if let Some(state) = GLOBAL_STATE.lock().unwrap().get_mut(&thread_id) {
state.status = status;
}
}
#[derive(Debug, Clone)]
pub struct LockInfo {
pub name: String,
}
static GLOBAL_STATE: Lazy<Mutex<HashMap<ThreadId, ThreadState>>> =
Lazy::new(|| Mutex::new(HashMap::new()));
static LOCK_INFO: Lazy<Mutex<HashMap<LockId, LockInfo>>> = Lazy::new(|| Mutex::new(HashMap::new()));
static NEXT_LOCK_ID: AtomicUsize = AtomicUsize::new(0);
pub fn new_lock_id(name: &str) -> LockId {
let id = NEXT_LOCK_ID.fetch_add(1, Ordering::SeqCst);
LOCK_INFO.lock().unwrap().insert(
id,
LockInfo {
name: name.to_string(),
},
);
id
}
#[derive(Debug)]
pub struct DebugMutex<T> {
id: LockId,
name: String,
mutex: Mutex<T>,
}
impl<T> DebugMutex<T> {
pub fn new(value: T, name: &str) -> Self {
Self {
id: new_lock_id(name),
name: name.to_string(),
mutex: Mutex::new(value),
}
}
pub fn lock(
&self,
) -> Result<DebugMutexGuard<'_, T>, std::sync::PoisonError<std::sync::MutexGuard<'_, T>>> {
let thread_id = thread::current().id();
GLOBAL_STATE
.lock()
.unwrap()
.entry(thread_id)
.or_default()
.locks
.insert(self.id, LockState::Waiting);
let guard = self.mutex.lock();
GLOBAL_STATE
.lock()
.unwrap()
.entry(thread_id)
.or_default()
.locks
.insert(self.id, LockState::Held);
guard.map(|g| DebugMutexGuard {
mutex: self,
guard: g,
})
}
}
pub struct DebugMutexGuard<'a, T: 'a> {
mutex: &'a DebugMutex<T>,
guard: std::sync::MutexGuard<'a, T>,
}
impl<'a, T> std::ops::Deref for DebugMutexGuard<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.guard.deref()
}
}
impl<'a, T> std::ops::DerefMut for DebugMutexGuard<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.guard.deref_mut()
}
}
impl<'a, T> Drop for DebugMutexGuard<'a, T> {
fn drop(&mut self) {
let thread_id = thread::current().id();
if let Some(state) = GLOBAL_STATE.lock().unwrap().get_mut(&thread_id) {
state.locks.remove(&self.mutex.id);
}
}
}
pub struct ThreadTracker {
thread_id: ThreadId,
}
impl ThreadTracker {
pub fn new(name: String) -> Self {
let thread_id = thread::current().id();
let mut state = GLOBAL_STATE.lock().unwrap();
state.entry(thread_id).or_insert_with(|| ThreadState {
name,
..Default::default()
});
Self { thread_id }
}
}
impl Drop for ThreadTracker {
fn drop(&mut self) {
GLOBAL_STATE.lock().unwrap().remove(&self.thread_id);
}
}
pub fn dump_deadlock_info() {
info!("--- Deadlock Info Dump ---");
let state = GLOBAL_STATE.lock().unwrap();
let lock_info = LOCK_INFO.lock().unwrap();
for (thread_id, thread_state) in state.iter() {
info!("Thread ID: {:?}, Name: {}", thread_id, thread_state.name);
if !thread_state.locks.is_empty() {
for (lock_id, lock_state) in thread_state.locks.iter() {
let state_str = match lock_state {
LockState::Held => "Held",
LockState::Waiting => "Waiting",
};
let lock_name = lock_info
.get(lock_id)
.map(|info| info.name.as_str())
.unwrap_or("Unknown");
info!(
" - Lock ID: {}, Name: {}, State: {}",
lock_id, lock_name, state_str
);
}
} else {
info!(" - No locks held or waiting.");
}
if !thread_state.data.is_empty() {
info!(" - Data: {}", thread_state.data);
}
if !thread_state.status.is_empty() {
info!(" - Status: {}", thread_state.status);
}
}
info!("--- End of Dump ---");
}