atagen

macltok

public
Star0
Watch0
d8e76b56867c28deec549cb435c865e4f830e4bf
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git

Blame: src/wasm.rs

7b376d620a3datagen2026-09-26 12:53 UTC1
use std::cell::RefCell;
7b376d620a3datagen2026-09-26 12:53 UTC2
7b376d620a3datagen2026-09-26 12:53 UTC3
type Handler = Box<dyn Fn(&str)>;
7b376d620a3datagen2026-09-26 12:53 UTC4
7b376d620a3datagen2026-09-26 12:53 UTC5
thread_local! {
7b376d620a3datagen2026-09-26 12:53 UTC6
    static HANDLER: RefCell<Option<Handler>> = const { RefCell::new(None) };
7b376d620a3datagen2026-09-26 12:53 UTC7
}
7b376d620a3datagen2026-09-26 12:53 UTC8
7b376d620a3datagen2026-09-26 12:53 UTC9
/// a panic on wasm32 traps the task that raised it and nothing unwinds, so the engine
7b376d620a3datagen2026-09-26 12:53 UTC10
/// catches nothing. the rest of it keeps running in an undefined state and goes silent,
7b376d620a3datagen2026-09-26 12:53 UTC11
/// no `Failed` and no `Stopped`. `handler` runs from the panic hook with the message,
7b376d620a3datagen2026-09-26 12:53 UTC12
/// after whatever hook was there before, and is the host's one chance to react, say by
7b376d620a3datagen2026-09-26 12:53 UTC13
/// terminating the worker and starting a fresh one. a second call replaces the handler
7b376d620a3datagen2026-09-26 12:53 UTC14
pub fn on_panic(handler: impl Fn(&str) + 'static) {
7b376d620a3datagen2026-09-26 12:53 UTC15
    let installed = HANDLER.with(|slot| slot.replace(Some(Box::new(handler))).is_some());
7b376d620a3datagen2026-09-26 12:53 UTC16
    if installed {
7b376d620a3datagen2026-09-26 12:53 UTC17
        return;
7b376d620a3datagen2026-09-26 12:53 UTC18
    }
7b376d620a3datagen2026-09-26 12:53 UTC19
    let previous = std::panic::take_hook();
7b376d620a3datagen2026-09-26 12:53 UTC20
    std::panic::set_hook(Box::new(move |info| {
7b376d620a3datagen2026-09-26 12:53 UTC21
        previous(info);
7b376d620a3datagen2026-09-26 12:53 UTC22
        let message = info.to_string();
7b376d620a3datagen2026-09-26 12:53 UTC23
        HANDLER.with(|slot| {
7b376d620a3datagen2026-09-26 12:53 UTC24
            if let Some(handler) = &*slot.borrow() {
7b376d620a3datagen2026-09-26 12:53 UTC25
                handler(&message);
7b376d620a3datagen2026-09-26 12:53 UTC26
            }
7b376d620a3datagen2026-09-26 12:53 UTC27
        });
7b376d620a3datagen2026-09-26 12:53 UTC28
    }));
7b376d620a3datagen2026-09-26 12:53 UTC29
}