1use 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
23pub const EXCEEDED: &str = "request time limit exceeded";
26
27#[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
39pub fn start(limit: Duration) -> Deadline {
41 DEADLINE.with(|d| d.set(Some(Instant::now() + limit)));
42 Deadline(())
43}
44
45pub fn start_public(limit: Duration) -> Deadline {
49 let d = start(limit);
50 NO_OLD_STATE.with(|o| o.set(true));
51 d
52}
53
54pub fn old_state_allowed() -> bool {
57 !NO_OLD_STATE.with(Cell::get)
58}
59
60pub fn current() -> Option<Instant> {
63 DEADLINE.with(Cell::get)
64}
65
66pub fn start_at(at: Option<Instant>) -> Deadline {
69 DEADLINE.with(|d| d.set(at));
70 Deadline(())
71}
72
73pub 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
82pub(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}