Skip to main content

Interrupt

Struct Interrupt 

Source
pub struct Interrupt(/* private fields */);
Expand description

A handle that stops the state’s running call from any thread: Interrupt::interrupt makes the call stop with Error::Limit(LimitKind::Interrupted) within a fraction of a millisecond of work, wherever it is (a loop, a long gsub or sort, a coroutine), and scripts cannot catch it. It stays set until Interrupt::reset, and while it is set every entry into the state (a call, or making a value) stops at once.

Implementations§

Source§

impl Interrupt

Source

pub fn interrupt(&self)

Asks the running call (and every call after it, until reset) to stop.

Examples found in repository?
examples/frontstop.rs (line 49)
23fn main() {
24    let mut args = std::env::args().skip(1);
25    let cases: Vec<String> = match args.next() {
26        Some(c) if c != "all" => vec![c],
27        _ => ["do", "dots", "flat", "locals", "keys", "strs"].iter().map(|s| (*s).to_owned()).collect(),
28    };
29    let points: u32 = args.next().and_then(|a| a.parse().ok()).unwrap_or(24);
30    // A third argument: interrupt only there (milliseconds into the load).
31    let only: Option<u64> = args.next().and_then(|a| a.parse().ok());
32    for case in cases {
33        let src = source(&case);
34        let full = {
35            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
36            let t = Instant::now();
37            let r = lua.load(&src, "=t").map(|_| ());
38            let e = t.elapsed();
39            assert!(r.is_ok(), "{case}: {r:?}");
40            e
41        };
42        let mut worst = (Duration::ZERO, Duration::ZERO);
43        for k in 1..=points {
44            let at = only.map_or(full * k / (points + 1), Duration::from_millis);
45            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
46            let h = lua.interrupt_handle();
47            let t = std::thread::spawn(move || {
48                std::thread::sleep(at);
49                h.interrupt();
50                Instant::now()
51            });
52            let started = Instant::now();
53            let r = lua.load(&src, "=t").map(|_| ());
54            let end = Instant::now();
55            let fired = t.join().unwrap();
56            if r.is_err() {
57                let late = end.saturating_duration_since(fired);
58                if std::env::var("FRONTSTOP_VERBOSE").is_ok() {
59                    println!("  at {at:?}: {late:?} late, {:?} into the load", fired.saturating_duration_since(started));
60                }
61                if late > worst.0 {
62                    worst = (late, at);
63                }
64            }
65            lua.interrupt_handle().reset();
66            let _ = lua.load("return 1", "=ok");
67        }
68        println!("{case:8} {:.1} MB, load {full:?}: worst {:?} late (interrupted at {:?})", src.len() as f64 / 1e6, worst.0, worst.1);
69    }
70}
More examples
Hide additional examples
examples/interngap.rs (line 75)
32fn main() {
33    let a: Vec<String> = std::env::args().collect();
34    let n: usize = a.get(1).and_then(|s| s.parse().ok()).unwrap_or(2_000_000);
35    let k: usize = a.get(2).and_then(|s| s.parse().ok()).unwrap_or(600_000);
36    let mut lua = Lua::new(Limits::default().memory(4 << 30).fuel(1 << 40).hash_seed(7), Libs::ALL);
37    // The table grows first (its array part's growth is not the interner's).
38    lua.exec(&format!("L = {{}} for i = 1, {n} do L[i] = true end"), "=setup").unwrap();
39    let (clock, st) = gap_clock();
40    lua.set_time_limit(Some((clock, Duration::from_secs(600))));
41    let body = std::env::var("BODY").unwrap_or_else(|_| "L[i] = 's' .. i".into());
42    let f = lua.load(&format!("local L = L for i = 1, {n} do {body} end return #L"), "=vm").unwrap();
43    st.lock().unwrap().0 = Instant::now();
44    let t = Instant::now();
45    lua.call(f.value(), &[]).unwrap();
46    let all = t.elapsed();
47    let g = *st.lock().unwrap();
48    println!("vm: {n} strings in {all:?}, longest between deadline reads {:?}", g.1);
49    println!("reads {}, mean gap {:?}", g.2, all / g.2.max(1) as u32);
50    let stat = std::fs::read_to_string("/proc/self/stat").unwrap_or_default();
51    println!("minflt {}", stat.split_whitespace().nth(9).unwrap_or("?"));
52    println!(
53        "{:?}",
54        lua.internal_sizes().into_iter().filter(|(k, _)| k.starts_with("intern")).collect::<Vec<_>>()
55    );
56    if k == 0 {
57        return;
58    }
59    // A host load: the interrupt is looked at by the compile's steps; a thread notes how late
60    // a load stops after it, at points along the load.
61    let src = format!("return {{{}}}", (0..k).map(|i| format!("\"c{i}\",")).collect::<String>());
62    let full = {
63        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
64        let t = Instant::now();
65        l.load(&src, "=t").unwrap();
66        t.elapsed()
67    };
68    let mut worst = Duration::ZERO;
69    for p in 1..=12u32 {
70        let at = full * p / 13;
71        let mut l = Lua::new(Limits::unmetered().memory(4 << 30), Libs::NONE);
72        let h = l.interrupt_handle();
73        let th = std::thread::spawn(move || {
74            std::thread::sleep(at);
75            h.interrupt();
76            Instant::now()
77        });
78        let r = l.load(&src, "=t").map(|_| ());
79        let end = Instant::now();
80        let fired = th.join().unwrap();
81        if r.is_err() {
82            worst = worst.max(end.saturating_duration_since(fired));
83        }
84    }
85    println!("load: {k} constants in {full:?}, worst stop after the interrupt {worst:?}");
86}
Source

pub fn reset(&self)

Lets calls run again. A host that reuses one state for many calls resets the handle before each call it wants to run.

Examples found in repository?
examples/frontstop.rs (line 65)
23fn main() {
24    let mut args = std::env::args().skip(1);
25    let cases: Vec<String> = match args.next() {
26        Some(c) if c != "all" => vec![c],
27        _ => ["do", "dots", "flat", "locals", "keys", "strs"].iter().map(|s| (*s).to_owned()).collect(),
28    };
29    let points: u32 = args.next().and_then(|a| a.parse().ok()).unwrap_or(24);
30    // A third argument: interrupt only there (milliseconds into the load).
31    let only: Option<u64> = args.next().and_then(|a| a.parse().ok());
32    for case in cases {
33        let src = source(&case);
34        let full = {
35            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
36            let t = Instant::now();
37            let r = lua.load(&src, "=t").map(|_| ());
38            let e = t.elapsed();
39            assert!(r.is_ok(), "{case}: {r:?}");
40            e
41        };
42        let mut worst = (Duration::ZERO, Duration::ZERO);
43        for k in 1..=points {
44            let at = only.map_or(full * k / (points + 1), Duration::from_millis);
45            let mut lua = Lua::new(Limits::unmetered().memory(8 << 30), Libs::NONE);
46            let h = lua.interrupt_handle();
47            let t = std::thread::spawn(move || {
48                std::thread::sleep(at);
49                h.interrupt();
50                Instant::now()
51            });
52            let started = Instant::now();
53            let r = lua.load(&src, "=t").map(|_| ());
54            let end = Instant::now();
55            let fired = t.join().unwrap();
56            if r.is_err() {
57                let late = end.saturating_duration_since(fired);
58                if std::env::var("FRONTSTOP_VERBOSE").is_ok() {
59                    println!("  at {at:?}: {late:?} late, {:?} into the load", fired.saturating_duration_since(started));
60                }
61                if late > worst.0 {
62                    worst = (late, at);
63                }
64            }
65            lua.interrupt_handle().reset();
66            let _ = lua.load("return 1", "=ok");
67        }
68        println!("{case:8} {:.1} MB, load {full:?}: worst {:?} late (interrupted at {:?})", src.len() as f64 / 1e6, worst.0, worst.1);
69    }
70}
Source

pub fn is_set(&self) -> bool

Whether it is set.

Trait Implementations§

Source§

impl Clone for Interrupt

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Interrupt

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.