use crate::{PanicReport, control::Shared};
use std::{sync::Weak, thread};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ThreadComponent {
Carrier,
LifecycleOwner,
NativeWorker,
Readiness,
Coordinator,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum FailurePhase {
Running,
PanicCleanup,
Join,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ThreadFailure {
component: ThreadComponent,
name: String,
phase: FailurePhase,
pub(crate) shutdown_phase: crate::ShutdownPhase,
panic: PanicReport,
cleanup_complete: bool,
}
impl ThreadFailure {
pub(crate) fn new(
component: ThreadComponent,
name: &str,
phase: FailurePhase,
panic: PanicReport,
) -> Self {
let mut end = name.len().min(128);
while !name.is_char_boundary(end) {
end -= 1;
}
Self {
component,
name: name[..end].to_owned(),
phase,
shutdown_phase: crate::ShutdownPhase::NotRequested,
cleanup_complete: phase == FailurePhase::Join && !panic.cleanup_panicked(),
panic,
}
}
pub fn component(&self) -> ThreadComponent {
self.component
}
pub fn name(&self) -> &str {
&self.name
}
pub fn phase(&self) -> FailurePhase {
self.phase
}
pub fn shutdown_phase(&self) -> crate::ShutdownPhase {
self.shutdown_phase
}
pub fn panic(&self) -> &PanicReport {
&self.panic
}
pub fn cleanup_complete(&self) -> bool {
self.cleanup_complete
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ThreadFailures {
entries: Vec<ThreadFailure>,
additional: u64,
}
impl ThreadFailures {
pub(crate) fn joined(&mut self, component: ThreadComponent, name: &str) {
for entry in &mut self.entries {
if entry.component == component && entry.name == name {
entry.cleanup_complete = !entry.panic.cleanup_panicked();
}
}
}
pub(crate) fn push(&mut self, failure: ThreadFailure) {
if self.entries.len() < 8 {
self.entries.push(failure);
} else {
self.additional = self.additional.saturating_add(1);
}
}
pub fn entries(&self) -> &[ThreadFailure] {
&self.entries
}
pub fn additional(&self) -> u64 {
self.additional
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty() && self.additional == 0
}
}
#[cfg(test)]
pub(crate) fn join(
worker: thread::JoinHandle<()>,
shared: &Weak<Shared>,
component: ThreadComponent,
) {
let name = worker.thread().name().unwrap_or("unnamed").to_owned();
report_join(worker.join(), shared, component, &name);
}
pub(crate) fn report_join(
result: thread::Result<()>,
shared: &Weak<Shared>,
component: ThreadComponent,
name: &str,
) {
if let Err(payload) = result {
let (captured, quarantined) = vthread_stack::panic_payload::capture_for_join(payload);
let panic = PanicReport::from_captured(captured);
if let Some(shared) = shared.upgrade() {
let mut failure = ThreadFailure::new(component, name, FailurePhase::Join, panic);
failure.cleanup_complete &= !quarantined;
shared.record_failure(failure);
}
} else if let Some(shared) = shared.upgrade() {
crate::signal::lock(&shared.failures).joined(component, name);
}
}
#[cfg(test)]
#[path = "thread_failure_test.rs"]
mod thread_failure_test;