Skip to main content

cosmic_applet_avestruz/
requests.rs

1// SPDX-License-Identifier: MIT
2
3//! What views ask for that has to be fetched: the asking, apart from what
4//! is asked for.
5//!
6//! A view is built from a model it can't change, and is built again and
7//! again. What it finds missing it asks for through [`Requests::ask`], which
8//! sends the request down a channel once however often it is asked. A
9//! subscription hands what the channel carries to the app, which starts the
10//! fetch if [`Requests::begin`] lets it: so many are on their way at once,
11//! and no more. Only what is on screen is ever built, so only what is on
12//! screen is ever asked for.
13//!
14//! ```mermaid
15//! stateDiagram-v2
16//!     [*] --> Asked: a view finds it missing, and asks
17//!     Asked --> Asked: built again, the view asks again. Nothing is sent twice
18//!     Asked --> InFlight: the app takes it up, and fewer than so many are on their way
19//!     Asked --> [*]: the app takes it up, but it is had already, or too many are on their way
20//!     InFlight --> [*]: fetched, or failed
21//! ```
22//!
23//! One that was turned away because too many were on their way is asked
24//! for again by the next view that still needs it, which is the next
25//! frame if it is still on screen and never if it scrolled away. So
26//! nothing is fetched for a row that was only passed by.
27//!
28//! The whole road a picture takes, from a row to the web and back, is in
29//! [`crate::guide::flows`].
30
31use std::cell::RefCell;
32use std::collections::HashSet;
33use std::hash::{Hash, Hasher};
34use std::sync::Arc;
35
36use cosmic::iced::Subscription;
37use futures_util::SinkExt;
38use tokio::sync::{Mutex, mpsc};
39
40/// The receiving end of some requests, as the app model keeps it for the
41/// subscription that drains it.
42pub type Inbox<K> = Arc<Mutex<mpsc::Receiver<K>>>;
43
44/// What views asked for through the [`Requests`] that `inbox` receives
45/// from, each as the message `message` makes of it. The app decides which
46/// are actually fetched.
47pub fn subscription<K, M>(inbox: &Inbox<K>, message: fn(K) -> M) -> Subscription<M>
48where
49    K: Send + 'static,
50    M: Send + 'static,
51{
52    /// An inbox and what to make of what it carries, hashed by where they
53    /// are so that they can key a `run_with` subscription.
54    struct Drain<K, M>(Inbox<K>, fn(K) -> M);
55
56    impl<K, M> Hash for Drain<K, M> {
57        fn hash<H: Hasher>(&self, state: &mut H) {
58            Arc::as_ptr(&self.0).hash(state);
59        }
60    }
61
62    Subscription::run_with(Drain(inbox.clone(), message), |drain: &Drain<K, M>| {
63        let (requests, message) = (drain.0.clone(), drain.1);
64        cosmic::iced::stream::channel(64, async move |mut channel| {
65            let mut requests = requests.lock().await;
66            while let Some(request) = requests.recv().await {
67                if channel.send(message(request)).await.is_err() {
68                    break;
69                }
70            }
71            futures_util::future::pending().await
72        })
73    })
74}
75
76/// The requests for one kind of thing, each named by a `K`.
77pub struct Requests<K> {
78    /// On their way.
79    in_flight: HashSet<K>,
80    /// Sent down `sender` and not taken up by the app yet, so that a view
81    /// built many times asks once.
82    asked: RefCell<HashSet<K>>,
83    sender: mpsc::Sender<K>,
84    /// How many may be on their way at once.
85    max_in_flight: usize,
86}
87
88impl<K: Clone + Eq + Hash> Requests<K> {
89    /// Requests of which `max_in_flight` may be on their way at once and
90    /// `queue` may wait between a view asking and the app answering, and
91    /// the receiving end of them. A request that doesn't fit the queue is
92    /// dropped: what is still on screen is asked for again the next time
93    /// the view is built.
94    pub fn new(queue: usize, max_in_flight: usize) -> (Self, mpsc::Receiver<K>) {
95        let (sender, receiver) = mpsc::channel(queue);
96        (Self { in_flight: HashSet::new(), asked: RefCell::new(HashSet::new()), sender, max_in_flight }, receiver)
97    }
98
99    /// Ask for `key`, unless it was asked for or is on its way already.
100    pub fn ask(&self, key: &K) {
101        if !self.in_flight.contains(key) && !self.asked.borrow().contains(key) && self.sender.try_send(key.clone()).is_ok() {
102            self.asked.borrow_mut().insert(key.clone());
103        }
104    }
105
106    /// The request for `key` reached the app; `wanted` says whether there
107    /// is still a use for what it asks. Returns whether to start fetching:
108    /// not what is on its way already, and nothing while as many as may be
109    /// are. A request turned away for that last reason is simply asked
110    /// again by the next view that needs it.
111    pub fn begin(&mut self, key: &K, wanted: bool) -> bool {
112        self.asked.get_mut().remove(key);
113        wanted && self.in_flight.len() < self.max_in_flight && self.in_flight.insert(key.clone())
114    }
115
116    /// The fetch of `key` ended, one way or the other.
117    pub fn end(&mut self, key: &K) {
118        self.in_flight.remove(key);
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::Requests;
125
126    #[test]
127    fn what_is_asked_for_often_is_asked_for_once_and_fetched_once() {
128        let (mut requests, mut receiver) = Requests::new(8, 2);
129
130        // A view is built several times before the app gets to the request.
131        for _ in 0..3 {
132            requests.ask(&"a");
133        }
134        assert_eq!(receiver.try_recv().ok(), Some("a"));
135        assert!(receiver.try_recv().is_err(), "asked once");
136
137        // On its way: not asked for again, and not begun again.
138        assert!(requests.begin(&"a", true));
139        requests.ask(&"a");
140        assert!(receiver.try_recv().is_err());
141        assert!(!requests.begin(&"a", true));
142
143        // Once it has ended, whoever keeps what came decides what is asked.
144        requests.end(&"a");
145        requests.ask(&"a");
146        assert_eq!(receiver.try_recv().ok(), Some("a"));
147        assert!(!requests.begin(&"a", false), "it is here already: nothing to fetch");
148    }
149
150    #[test]
151    fn only_so_many_are_on_their_way_at_once_and_the_rest_ask_again() {
152        let (mut requests, mut receiver) = Requests::new(8, 2);
153        for key in ["a", "b", "c"] {
154            requests.ask(&key);
155        }
156        assert!(requests.begin(&"a", true) && requests.begin(&"b", true));
157        assert!(!requests.begin(&"c", true), "two are on their way");
158        while receiver.try_recv().is_ok() {}
159
160        // Turned away, it is asked for again by the next view that needs it.
161        requests.ask(&"c");
162        assert_eq!(receiver.try_recv().ok(), Some("c"));
163        requests.end(&"a");
164        assert!(requests.begin(&"c", true));
165    }
166
167    #[test]
168    fn a_request_that_does_not_fit_the_queue_is_asked_again_later() {
169        let (requests, mut receiver) = Requests::new(1, 2);
170        requests.ask(&"a");
171        requests.ask(&"b");
172        assert_eq!(receiver.try_recv().ok(), Some("a"));
173        assert!(receiver.try_recv().is_err(), "no room for the second");
174
175        requests.ask(&"b");
176        assert_eq!(receiver.try_recv().ok(), Some("b"));
177    }
178}