use std::cell::RefCell;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Mutex;
use std::sync::atomic::{AtomicU64, Ordering};
const KEPT_FAILURES: usize = 20;
static FAILED_FEATURES: AtomicU64 = AtomicU64::new(0);
static BASELINE: AtomicU64 = AtomicU64::new(0);
static ALLOWED: AtomicU64 = AtomicU64::new(u64::MAX);
static FIRST: Mutex<Vec<Failure>> = Mutex::new(Vec::new());
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Failure {
pub feature_id: u64,
pub layer: &'static str,
pub op: &'static str,
pub message: String,
}
impl std::fmt::Display for Failure {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"feature {} in layer {:?}, {}: {}",
self.feature_id, self.layer, self.op, self.message
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Exceeded {
pub count: u64,
pub allowed: u64,
}
struct Context {
feature_id: u64,
layer: &'static str,
failed: bool,
}
thread_local! {
static CONTEXT: RefCell<Option<Context>> = const { RefCell::new(None) };
}
#[must_use = "the feature is counted when the scope is dropped"]
pub struct FeatureScope(());
pub fn enter(feature_id: u64, layer: &'static str) -> FeatureScope {
CONTEXT.with(|c| {
*c.borrow_mut() = Some(Context {
feature_id,
layer,
failed: false,
});
});
FeatureScope(())
}
impl Drop for FeatureScope {
fn drop(&mut self) {
let failed = CONTEXT
.with(|c| c.borrow_mut().take())
.is_some_and(|ctx| ctx.failed);
if failed {
FAILED_FEATURES.fetch_add(1, Ordering::Relaxed);
}
}
}
pub fn catch<T>(op: &'static str, work: impl FnOnce() -> T) -> Option<T> {
match catch_unwind(AssertUnwindSafe(work)) {
Ok(value) => Some(value),
Err(payload) => {
record(op, message_of(payload.as_ref()));
None
}
}
}
#[must_use]
pub fn message_of(payload: &(dyn std::any::Any + Send)) -> String {
payload
.downcast_ref::<String>()
.map(String::as_str)
.or_else(|| payload.downcast_ref::<&str>().copied())
.unwrap_or("unknown panic")
.to_owned()
}
fn record(op: &'static str, message: String) {
let (feature_id, layer, in_scope) = CONTEXT.with(|c| {
let mut slot = c.borrow_mut();
match slot.as_mut() {
Some(ctx) => {
ctx.failed = true;
(ctx.feature_id, ctx.layer, true)
}
None => (0, "", false),
}
});
if !in_scope {
FAILED_FEATURES.fetch_add(1, Ordering::Relaxed);
}
let failure = Failure {
feature_id,
layer,
op,
message,
};
let mut first = FIRST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if first.len() < KEPT_FAILURES {
tracing::warn!("geometry panic caught, piece skipped: {failure}");
first.push(failure);
} else {
tracing::debug!("geometry panic caught, piece skipped: {failure}");
}
}
#[must_use]
pub fn failed_features() -> u64 {
FAILED_FEATURES.load(Ordering::Relaxed)
}
pub fn begin_build(allowed: u64) {
BASELINE.store(FAILED_FEATURES.load(Ordering::Relaxed), Ordering::Relaxed);
ALLOWED.store(allowed, Ordering::Relaxed);
FIRST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
}
#[must_use]
pub fn build_failures() -> u64 {
FAILED_FEATURES
.load(Ordering::Relaxed)
.saturating_sub(BASELINE.load(Ordering::Relaxed))
}
#[must_use]
pub fn allowed() -> u64 {
ALLOWED.load(Ordering::Relaxed)
}
#[must_use]
pub fn exceeded() -> Option<Exceeded> {
let count = build_failures();
let allowed = allowed();
(count > allowed).then_some(Exceeded { count, allowed })
}
#[must_use]
pub fn first_failures() -> Vec<Failure> {
FIRST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clone()
}
#[cfg(test)]
pub(crate) fn test_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: Mutex<()> = Mutex::new(());
LOCK.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(test)]
mod tests {
use super::*;
use super::test_lock as serial;
#[test]
fn a_panic_gives_none_and_a_value_gives_some() {
let _lock = serial();
assert_eq!(catch("fine", || 7), Some(7));
assert_eq!(catch("boom", || -> u8 { panic!("bad ring") }), None);
}
#[test]
fn a_feature_counts_once_however_many_pieces_fail() {
let _lock = serial();
begin_build(10);
let scope = enter(42, "earth");
for _ in 0..5 {
assert_eq!(catch("clip", || -> u8 { panic!("bad ring") }), None);
}
assert_eq!(build_failures(), 0, "counted when the scope ends");
drop(scope);
assert_eq!(build_failures(), 1);
let first = first_failures();
assert_eq!(first.len(), 5);
assert_eq!(first[0].feature_id, 42);
assert_eq!(first[0].layer, "earth");
assert_eq!(first[0].op, "clip");
assert_eq!(first[0].message, "bad ring");
}
#[test]
fn a_scope_without_a_failure_counts_nothing() {
let _lock = serial();
begin_build(10);
drop(enter(1, "water"));
assert_eq!(build_failures(), 0);
}
#[test]
fn a_failure_outside_a_scope_is_counted_at_once_with_no_feature() {
let _lock = serial();
begin_build(10);
assert_eq!(catch("clip", || -> u8 { panic!("x") }), None);
assert_eq!(build_failures(), 1);
assert_eq!(first_failures()[0].feature_id, 0);
}
#[test]
fn the_limit_is_passed_only_above_the_allowed_count() {
let _lock = serial();
begin_build(2);
for id in 0..2 {
let scope = enter(id, "earth");
let _ = catch("clip", || -> u8 { panic!("x") });
drop(scope);
}
assert_eq!(exceeded(), None, "two of two allowed");
let scope = enter(9, "earth");
let _ = catch("clip", || -> u8 { panic!("x") });
drop(scope);
assert_eq!(
exceeded(),
Some(Exceeded {
count: 3,
allowed: 2
})
);
}
#[test]
fn begin_build_forgets_the_earlier_build() {
let _lock = serial();
begin_build(0);
let _ = catch("clip", || -> u8 { panic!("x") });
assert_eq!(build_failures(), 1);
begin_build(0);
assert_eq!(build_failures(), 0);
assert!(first_failures().is_empty());
}
#[test]
fn only_the_first_failures_are_kept() {
let _lock = serial();
begin_build(u64::MAX);
for _ in 0..(KEPT_FAILURES + 5) {
let _ = catch("clip", || -> u8 { panic!("x") });
}
assert_eq!(first_failures().len(), KEPT_FAILURES);
assert_eq!(build_failures(), (KEPT_FAILURES + 5) as u64);
}
}