reqwest_cross/
data_state_retry.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
use tracing::{error, warn};

use crate::{data_state::CanMakeProgress, Awaiting, DataState, ErrorBounds};
use std::fmt::Debug;
use std::ops::Range;
use std::time::{Duration, Instant};

/// Automatically retries with a delay on failure until attempts are exhausted
#[derive(Debug)]
pub struct DataStateRetry<T, E: ErrorBounds = anyhow::Error> {
    /// Number of attempts that the retries get reset to
    pub max_attempts: u8,
    /// The range of milliseconds to select a random value from to set the delay
    /// to retry
    pub retry_delay_millis: Range<u16>,
    attempts_left: u8,
    inner: DataState<T, E>, // Not public to ensure resets happen as they should
    next_allowed_attempt: Instant,
}

impl<T, E: ErrorBounds> DataStateRetry<T, E> {
    /// Creates a new instance of [DataStateRetry]
    pub fn new(max_attempts: u8, retry_delay_millis: Range<u16>) -> Self {
        Self {
            max_attempts,
            retry_delay_millis,
            ..Default::default()
        }
    }

    /// The number times left to retry before stopping trying
    pub fn attempts_left(&self) -> u8 {
        self.attempts_left
    }

    /// The instant that needs to be waited for before another attempt is
    /// allowed
    pub fn next_allowed_attempt(&self) -> Instant {
        self.next_allowed_attempt
    }

    /// Provides access to the inner [`DataState`]
    pub fn inner(&self) -> &DataState<T, E> {
        &self.inner
    }

    /// Consumes self and returns the unwrapped inner
    pub fn into_inner(self) -> DataState<T, E> {
        self.inner
    }

    /// Provides access to the stored data if available (returns Some if
    /// self.inner is `Data::Present(_)`)
    pub fn present(&self) -> Option<&T> {
        if let DataState::Present(data) = self.inner.as_ref() {
            Some(data)
        } else {
            None
        }
    }

    /// Provides mutable access to the stored data if available (returns Some if
    /// self.inner is `Data::Present(_)`)
    pub fn present_mut(&mut self) -> Option<&mut T> {
        if let DataState::Present(data) = self.inner.as_mut() {
            Some(data)
        } else {
            None
        }
    }

    #[cfg(feature = "egui")]
    /// Attempts to load the data and displays appropriate UI if applicable.
    ///
    /// Note see [`DataState::egui_get`] for more info.
    #[must_use]
    pub fn egui_get<F>(
        &mut self,
        ui: &mut egui::Ui,
        retry_msg: Option<&str>,
        fetch_fn: F,
    ) -> CanMakeProgress
    where
        F: FnOnce() -> Awaiting<T, E>,
    {
        match self.inner.as_ref() {
            DataState::None | DataState::AwaitingResponse(_) => {
                self.ui_spinner_with_attempt_count(ui);
                self.get(fetch_fn)
            }
            DataState::Present(_data) => {
                // Does nothing as data is already present
                CanMakeProgress::UnableToMakeProgress
            }
            DataState::Failed(e) => {
                if self.attempts_left == 0 {
                    ui.colored_label(
                        ui.visuals().error_fg_color,
                        format!("{} attempts exhausted. {e}", self.max_attempts),
                    );
                    if ui.button(retry_msg.unwrap_or("Restart Requests")).clicked() {
                        self.reset_attempts();
                        self.inner = DataState::default();
                    }
                } else {
                    let wait_left = wait_before_next_attempt(self.next_allowed_attempt);
                    ui.colored_label(
                        ui.visuals().error_fg_color,
                        format!(
                            "{} attempt(s) left. {} seconds before retry. {e}",
                            self.attempts_left,
                            wait_left.as_secs()
                        ),
                    );
                    let is_able_to_make_progress = self.get(fetch_fn).is_able_to_make_progress();
                    assert!(
                        is_able_to_make_progress,
                        "if this is not true something is very wrong"
                    );
                }

                CanMakeProgress::AbleToMakeProgress
            }
        }
    }

    /// Attempts to load the data and returns if it is able to make progress.
    ///
    /// See [`DataState::get`] for more info.
    #[must_use]
    pub fn get<F>(&mut self, fetch_fn: F) -> CanMakeProgress
    where
        F: FnOnce() -> Awaiting<T, E>,
    {
        match self.inner.as_mut() {
            DataState::None => {
                // Going to make an attempt, set when the next attempt is allowed
                use rand::Rng;
                let wait_time_in_millis = rand::thread_rng()
                    .gen_range(self.retry_delay_millis.clone())
                    .into();
                self.next_allowed_attempt = Instant::now()
                    .checked_add(Duration::from_millis(wait_time_in_millis))
                    .expect("failed to get random delay, value was out of range");

                self.inner.get(fetch_fn)
            }
            DataState::AwaitingResponse(rx) => {
                if let Some(new_state) = DataState::await_data(rx) {
                    // TODO 4: Add some tests to ensure await_data work as this function assumes
                    self.inner = match new_state.as_ref() {
                        DataState::None => {
                            error!("Unexpected new state received of DataState::None");
                            unreachable!("Only expect Failed or Present variants to be returned but got None")
                        }
                        DataState::AwaitingResponse(_) => {
                            error!("Unexpected new state received of AwaitingResponse");
                            unreachable!("Only expect Failed or Present variants to be returned bug got AwaitingResponse")
                        }
                        DataState::Present(_) => {
                            // Data was successfully received
                            self.reset_attempts();
                            new_state
                        }
                        DataState::Failed(_) => new_state,
                    };
                }
                CanMakeProgress::AbleToMakeProgress
            }
            DataState::Present(_) => self.inner.get(fetch_fn),
            DataState::Failed(err_msg) => {
                if self.attempts_left == 0 {
                    self.inner.get(fetch_fn)
                } else {
                    let wait_left = wait_before_next_attempt(self.next_allowed_attempt);
                    if wait_left.is_zero() {
                        warn!(?err_msg, ?self.attempts_left, "retrying request");
                        self.attempts_left -= 1;
                        self.inner = DataState::None;
                    }
                    CanMakeProgress::AbleToMakeProgress
                }
            }
        }
    }

    /// Resets the attempts taken
    pub fn reset_attempts(&mut self) {
        self.attempts_left = self.max_attempts;
        self.next_allowed_attempt = Instant::now();
    }

    /// Clear stored data
    pub fn clear(&mut self) {
        self.inner = DataState::default();
    }

    /// Returns `true` if the internal data state is [`DataState::Present`].
    #[must_use]
    pub fn is_present(&self) -> bool {
        self.inner.is_present()
    }

    /// Returns `true` if the internal data state is [`DataState::None`].
    #[must_use]
    pub fn is_none(&self) -> bool {
        self.inner.is_none()
    }

    #[cfg(feature = "egui")]
    fn ui_spinner_with_attempt_count(&self, ui: &mut egui::Ui) {
        ui.horizontal(|ui| {
            ui.spinner();
            ui.separator();
            ui.label(format!("{} attempts left", self.attempts_left))
        });
    }
}

impl<T, E: ErrorBounds> Default for DataStateRetry<T, E> {
    fn default() -> Self {
        Self {
            inner: Default::default(),
            max_attempts: 3,
            retry_delay_millis: 1000..5000,
            attempts_left: 3,
            next_allowed_attempt: Instant::now(),
        }
    }
}

impl<T, E: ErrorBounds> AsRef<DataStateRetry<T, E>> for DataStateRetry<T, E> {
    fn as_ref(&self) -> &DataStateRetry<T, E> {
        self
    }
}

impl<T, E: ErrorBounds> AsMut<DataStateRetry<T, E>> for DataStateRetry<T, E> {
    fn as_mut(&mut self) -> &mut DataStateRetry<T, E> {
        self
    }
}

/// The duration before the next attempt will be made
fn wait_before_next_attempt(next_allowed_attempt: Instant) -> Duration {
    next_allowed_attempt.saturating_duration_since(Instant::now())
}