Skip to main content

mln_engine/storage/
request.rs

1//! A request for a resource, and the file source's side of it.
2
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5
6use parking_lot::Mutex;
7
8use crate::storage::response::Response;
9
10/// Receives a request's responses, on the thread that sends each one.
11pub type Callback = Box<dyn FnMut(Response) + Send + 'static>;
12
13/// A request for a resource. Dropping it cancels the request: the file
14/// source stops what work it can, and no response reaches the callback
15/// after the drop. The drop doesn't wait for a call that began before it,
16/// on the responder's thread, so a callback may drop its own request.
17#[must_use = "dropping a request cancels it"]
18pub struct Request {
19    shared: Arc<Shared>,
20}
21
22/// The file source's side of a [`Request`]: where it sends the responses,
23/// from any thread, and how it learns that the requester cancelled.
24///
25/// Dropping it ends the request without a response; a file source that
26/// can't load a resource sends a response with an error instead.
27#[derive(Clone)]
28pub struct Responder {
29    shared: Arc<Shared>,
30}
31
32struct Shared {
33    cancelled: AtomicBool,
34    /// The first response ends the request.
35    once: bool,
36    on_cancel: Mutex<Option<Box<dyn FnOnce() + Send>>>,
37    /// `None` once the request dropped while no response was being sent.
38    callback: Mutex<Option<Callback>>,
39}
40
41impl Shared {
42    fn new(callback: Callback, once: bool) -> Arc<Self> {
43        Arc::new(Shared {
44            cancelled: AtomicBool::new(false),
45            once,
46            on_cancel: Mutex::new(None),
47            callback: Mutex::new(Some(callback)),
48        })
49    }
50
51    fn is_cancelled(&self) -> bool {
52        self.cancelled.load(Ordering::SeqCst)
53    }
54
55    fn cancel(&self) {
56        self.cancelled.store(true, Ordering::SeqCst);
57        let on_cancel = self.on_cancel.lock().take();
58        if let Some(on_cancel) = on_cancel {
59            on_cancel();
60        }
61    }
62}
63
64impl Request {
65    /// A request whose responses `callback` receives on the thread that sends
66    /// each one.
67    pub fn new(callback: impl FnMut(Response) + Send + 'static) -> (Request, Responder) {
68        let shared = Shared::new(Box::new(callback), false);
69        (Request { shared: Arc::clone(&shared) }, Responder { shared })
70    }
71
72    /// A request for one response, which `callback` receives on the thread
73    /// that sends it. The request ends with it: the file source sees it
74    /// cancelled and sends nothing more, though its cancel hook runs only
75    /// when the request drops.
76    pub fn once(callback: impl FnOnce(Response) + Send + 'static) -> (Request, Responder) {
77        let mut callback = Some(callback);
78        let shared = Shared::new(
79            Box::new(move |response| {
80                if let Some(callback) = callback.take() {
81                    callback(response);
82                }
83            }),
84            true,
85        );
86        (Request { shared: Arc::clone(&shared) }, Responder { shared })
87    }
88}
89
90impl Drop for Request {
91    fn drop(&mut self) {
92        self.shared.cancel();
93        // While a response is being sent, its callback goes when the
94        // responders drop, rather than the drop waiting for it.
95        let callback = self.shared.callback.try_lock().and_then(|mut callback| callback.take());
96        drop(callback);
97    }
98}
99
100impl Responder {
101    /// Sends a response to the callback, on this thread. It does nothing
102    /// once the requester cancelled.
103    pub fn send(&self, response: Response) {
104        if self.is_cancelled() {
105            return;
106        }
107        let mut callback = self.shared.callback.lock();
108        // The request may have dropped while this waited for the lock.
109        if self.is_cancelled() {
110            return;
111        }
112        if self.shared.once {
113            self.shared.cancelled.store(true, Ordering::SeqCst);
114        }
115        if let Some(callback) = callback.as_mut() {
116            callback(response);
117        }
118    }
119
120    /// Whether the requester cancelled the request.
121    #[must_use]
122    pub fn is_cancelled(&self) -> bool {
123        self.shared.is_cancelled()
124    }
125
126    /// Runs `on_cancel` when the requester cancels the request, on the thread
127    /// that cancels it, or now if it has. It replaces the one before.
128    pub fn on_cancel(&self, on_cancel: impl FnOnce() + Send + 'static) {
129        *self.shared.on_cancel.lock() = Some(Box::new(on_cancel));
130        // The request may have been cancelled before `on_cancel` was there.
131        if self.is_cancelled() {
132            let on_cancel = self.shared.on_cancel.lock().take();
133            if let Some(on_cancel) = on_cancel {
134                on_cancel();
135            }
136        }
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use std::sync::atomic::AtomicUsize;
143
144    use super::*;
145
146    fn counter() -> (Arc<AtomicUsize>, impl FnMut(Response) + Send + 'static) {
147        let count = Arc::new(AtomicUsize::new(0));
148        let counted = Arc::clone(&count);
149        (count, move |_| {
150            counted.fetch_add(1, Ordering::SeqCst);
151        })
152    }
153
154    /// A request for one response ends at it: the responder sees it
155    /// cancelled, and a second response goes nowhere.
156    #[test]
157    fn a_once_request_ends_at_its_response() {
158        let (responses, callback) = counter();
159        let (request, responder) = Request::once(callback);
160        assert!(!responder.is_cancelled());
161        responder.send(Response::new());
162        assert!(responder.is_cancelled());
163        responder.send(Response::new());
164        assert_eq!(responses.load(Ordering::SeqCst), 1);
165        drop(request);
166    }
167
168    /// No response reaches the callback after the request drops, and the
169    /// drop releases the callback without waiting for the responders.
170    #[test]
171    fn a_dropped_request_answers_nothing_more() {
172        let (responses, callback) = counter();
173        let (request, responder) = Request::new(callback);
174        responder.send(Response::new());
175        drop(request);
176        responder.send(Response::new());
177        assert_eq!(responses.load(Ordering::SeqCst), 1);
178        assert_eq!(Arc::strong_count(&responses), 1, "the callback went with the request");
179    }
180
181    /// A callback may drop its own request, which cancels it without
182    /// waiting for the call that drops it.
183    #[test]
184    fn a_callback_drops_its_own_request() {
185        let slot: Arc<Mutex<Option<Request>>> = Arc::default();
186        let held = Arc::clone(&slot);
187        let (request, responder) = Request::new(move |_| drop(held.lock().take()));
188        *slot.lock() = Some(request);
189        responder.send(Response::new());
190        assert!(responder.is_cancelled());
191        assert!(slot.lock().is_none());
192    }
193}