Skip to main content

ledger_engine/
limits.rs

1//! Time limit for one request.
2//!
3//! Handlers run on blocking threads, and a blocking thread cannot be stopped
4//! from outside: a request that runs away would hold its slot (one of
5//! `MAX_INFLIGHT`) for as long as it likes. So a request stops itself. The
6//! server sets a deadline for the thread before calling the handler, and the
7//! loops whose length the client controls (owner directory pages, cold index
8//! partitions, the transactions of a page or a ledger) call `check`. Past the
9//! deadline the request ends with `tooBusy` and its slot goes to the next one.
10//! Threads that read for a request (`cold::Cold::ledgers`) take its deadline
11//! with them (`current`, `start_at`).
12
13use std::cell::Cell;
14use std::time::{Duration, Instant};
15
16use crate::api::{RpcError, rpc_err};
17
18thread_local! {
19    static DEADLINE: Cell<Option<Instant>> = const { Cell::new(None) };
20    static NO_OLD_STATE: Cell<bool> = const { Cell::new(false) };
21}
22
23/// The error text that carries an exceeded limit through modules whose errors
24/// are strings; `api::internal` turns it back into `tooBusy`.
25pub const EXCEEDED: &str = "request time limit exceeded";
26
27/// The deadline of the current thread's request; cleared when dropped, so a
28/// pooled thread does not carry it into the next task.
29#[derive(Debug)]
30pub struct Deadline(());
31
32impl Drop for Deadline {
33    fn drop(&mut self) {
34        DEADLINE.with(|d| d.set(None));
35        NO_OLD_STATE.with(|d| d.set(false));
36    }
37}
38
39/// Starts the limit for the request about to run on this thread.
40pub fn start(limit: Duration) -> Deadline {
41    DEADLINE.with(|d| d.set(Some(Instant::now() + limit)));
42    Deadline(())
43}
44
45/// `start` for a request from a public listener. Such a request also does not
46/// read state before the snapshot: a read there decompresses cold blocks, and
47/// the public budgets don't count that work yet.
48pub fn start_public(limit: Duration) -> Deadline {
49    let d = start(limit);
50    NO_OLD_STATE.with(|o| o.set(true));
51    d
52}
53
54/// Whether the current request may read state before the snapshot. Requests
55/// outside the server (tools, tests) may.
56pub fn old_state_allowed() -> bool {
57    !NO_OLD_STATE.with(Cell::get)
58}
59
60/// The deadline of the current thread's request, to hand to threads that
61/// read for it.
62pub fn current() -> Option<Instant> {
63    DEADLINE.with(Cell::get)
64}
65
66/// Runs this thread under a deadline taken from another (`current`); `None`
67/// sets none.
68pub fn start_at(at: Option<Instant>) -> Deadline {
69    DEADLINE.with(|d| d.set(at));
70    Deadline(())
71}
72
73/// `Err(EXCEEDED)` once the current request is past its deadline. Without a
74/// deadline (loading, tools, tests) there is no limit.
75pub fn check() -> Result<(), String> {
76    match DEADLINE.with(Cell::get) {
77        Some(at) if Instant::now() >= at => Err(EXCEEDED.into()),
78        _ => Ok(()),
79    }
80}
81
82/// `check` for handlers.
83pub(crate) fn check_rpc() -> Result<(), RpcError> {
84    check().map_err(|_| exceeded())
85}
86
87pub(crate) fn exceeded() -> RpcError {
88    rpc_err(
89        "tooBusy",
90        9,
91        "The request took too long. Ask for less: a smaller limit or a narrower ledger range.",
92    )
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn a_deadline_stops_only_its_own_request() {
101        assert!(check().is_ok());
102        {
103            let _d = start(Duration::ZERO);
104            assert_eq!(check(), Err(EXCEEDED.to_string()));
105            assert_eq!(check_rpc().unwrap_err().error, "tooBusy");
106            assert_eq!(crate::api::internal(EXCEEDED.into()).error, "tooBusy");
107        }
108        assert!(check().is_ok());
109        let _d = start(Duration::from_secs(60));
110        assert!(check().is_ok());
111    }
112
113    #[test]
114    fn a_deadline_carries_to_another_thread() {
115        let _d = start(Duration::ZERO);
116        let at = current();
117        assert!(at.is_some());
118        std::thread::spawn(move || {
119            assert!(check().is_ok());
120            {
121                let _d = start_at(at);
122                assert_eq!(check(), Err(EXCEEDED.to_string()));
123            }
124            assert!(check().is_ok());
125        })
126        .join()
127        .unwrap();
128    }
129}