Skip to main content

subspace_core/
keyed_request.rs

1//! Identity checks for asynchronous results. This does not stop remote work;
2//! the owner keeps its tasks and decides when to discard an old result.
3
4/// One attempt for a typed target, captured when the request starts.
5#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct Request<K> {
7    generation: u64,
8    key: K,
9}
10
11impl<K> Request<K> {
12    pub fn key(&self) -> &K {
13        &self.key
14    }
15}
16
17/// The current attempt in one independent request lane.
18// qual:api
19#[derive(Debug)]
20pub struct KeyedRequest<K> {
21    generation: u64,
22    current: Option<Request<K>>,
23}
24
25// qual:allow(dry, boilerplate) reason: "Derived Default would require K: Default, although an empty request lane has no key."
26impl<K> Default for KeyedRequest<K> {
27    fn default() -> Self {
28        Self {
29            generation: 0,
30            current: None,
31        }
32    }
33}
34
35impl<K: Clone + PartialEq> KeyedRequest<K> {
36    /// Replaces the previous attempt, even for the same target.
37    pub fn begin(&mut self, key: K) -> Request<K> {
38        self.generation = self.generation.wrapping_add(1);
39        let request = Request {
40            generation: self.generation,
41            key,
42        };
43        self.current = Some(request.clone());
44        request
45    }
46
47    // qual:api
48    pub fn is_current(&self, request: &Request<K>) -> bool {
49        self.current.as_ref() == Some(request)
50    }
51
52    /// Rejects completions from the current attempt without stopping its work.
53    pub fn invalidate(&mut self) {
54        self.current = None;
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use super::KeyedRequest;
61
62    #[test]
63    fn only_the_latest_attempt_for_the_current_target_is_accepted() {
64        let mut lane = KeyedRequest::default();
65        let first = lane.begin("first");
66        assert_eq!(first.key(), &"first");
67        assert!(lane.is_current(&first));
68        let second = lane.begin("first");
69        assert!(!lane.is_current(&first));
70        assert!(lane.is_current(&second));
71        let third = lane.begin("other");
72        assert!(!lane.is_current(&second));
73        assert!(lane.is_current(&third));
74    }
75
76    #[test]
77    fn invalidation_rejects_an_attempt_even_if_its_target_returns() {
78        let mut lane = KeyedRequest::default();
79        let old = lane.begin("target");
80        lane.invalidate();
81        assert!(!lane.is_current(&old));
82        let new = lane.begin("target");
83        assert!(!lane.is_current(&old));
84        assert!(lane.is_current(&new));
85    }
86}