1use std::collections::HashMap;
12use std::sync::{Arc, Mutex};
13use std::time::Duration;
14
15use futures::future::BoxFuture;
16
17use crate::changes::{Change, Publish, Scope};
18
19use crate::problem::Problem;
20
21pub type Link = (String, Option<usize>, String);
23
24#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum Outcome {
27 Fine,
29 Broken(String),
31 Unreachable(String),
33}
34
35pub trait Ask: Send + Sync {
37 fn ask<'a>(&'a self, address: &'a str, wait: Duration) -> BoxFuture<'a, Outcome>;
38}
39
40pub trait Background: Send + Sync {
43 fn spawn(&self, task: BoxFuture<'static, ()>) -> bool;
46 fn sleep(&self, pause: Duration) -> BoxFuture<'static, ()>;
48}
49
50#[derive(Debug, Clone, Copy)]
53pub struct Waits {
54 pub first: Duration,
55 pub retry: Duration,
57 pub retry_after: Duration,
59}
60
61impl Default for Waits {
62 fn default() -> Self {
63 Waits {
64 first: Duration::from_secs(10),
65 retry: Duration::from_secs(30),
66 retry_after: Duration::from_secs(30),
67 }
68 }
69}
70
71const FAILURES_BEFORE_A_PROBLEM: u32 = 3;
74
75enum Answer {
77 Pending,
78 Fine,
79 Broken(String),
80 Unreachable(u32, String),
82}
83
84pub struct External {
86 ask: Arc<dyn Ask>,
87 background: Arc<dyn Background>,
88 waits: Waits,
89 answers: Mutex<HashMap<String, Answer>>,
91 changes: Option<Arc<dyn Publish>>,
94}
95
96impl External {
97 pub fn new(
98 ask: Arc<dyn Ask>,
99 background: Arc<dyn Background>,
100 waits: Waits,
101 changes: Option<Arc<dyn Publish>>,
102 ) -> Arc<Self> {
103 Arc::new(External {
104 ask,
105 background,
106 waits,
107 answers: Mutex::default(),
108 changes,
109 })
110 }
111
112 pub async fn check(&self, links: Vec<Link>) -> Vec<Problem> {
115 let mut by_address: HashMap<String, Vec<(String, Option<usize>)>> = HashMap::new();
116 for (file, line, address) in links {
117 by_address.entry(address).or_default().push((file, line));
118 }
119 let checks = by_address.into_iter().map(|(address, links)| async move {
120 let Some(why) = self.broken(&address).await else {
121 return Vec::new();
122 };
123 links
124 .into_iter()
125 .map(|(file, line)| Problem {
126 file,
127 line,
128 message: format!("{address} — {why}"),
129 target: Some(address.clone()),
130 })
131 .collect()
132 });
133 futures::future::join_all(checks)
134 .await
135 .into_iter()
136 .flatten()
137 .collect()
138 }
139
140 async fn broken(&self, address: &str) -> Option<String> {
143 match self.ask.ask(address, self.waits.first).await {
144 Outcome::Fine => None,
145 Outcome::Broken(why) => Some(why),
146 Outcome::Unreachable(_) => match self.ask.ask(address, self.waits.retry).await {
147 Outcome::Fine => None,
148 Outcome::Broken(why) | Outcome::Unreachable(why) => Some(why),
149 },
150 }
151 }
152
153 pub fn preview(self: &Arc<Self>, links: Vec<Link>) -> Vec<Problem> {
158 let mut problems = Vec::new();
159 let mut answers = self
160 .answers
161 .lock()
162 .unwrap_or_else(|poisoned| poisoned.into_inner());
163 for (file, line, address) in links {
164 match answers.get(&address) {
165 Some(Answer::Broken(why)) => problems.push(Problem {
166 file,
167 line,
168 message: format!("{address} — {why}"),
169 target: Some(address),
170 }),
171 Some(Answer::Unreachable(failures, why))
172 if *failures >= FAILURES_BEFORE_A_PROBLEM =>
173 {
174 problems.push(Problem {
175 file,
176 line,
177 message: format!(
178 "{address} — {why}, {FAILURES_BEFORE_A_PROBLEM} times in a row"
179 ),
180 target: Some(address),
181 })
182 }
183 Some(Answer::Pending | Answer::Fine | Answer::Unreachable(..)) => {}
184 None => {
185 if self
188 .background
189 .spawn(Box::pin(Arc::clone(self).watch(address.clone())))
190 {
191 answers.insert(address, Answer::Pending);
192 }
193 }
194 }
195 }
196 problems
197 }
198
199 async fn watch(self: Arc<Self>, address: String) {
204 let mut failures = 0;
205 loop {
206 let outcome = self.ask.ask(&address, self.waits.first).await;
207 let shown_before = failures >= FAILURES_BEFORE_A_PROBLEM;
208 let (answer, shown_now, done) = match outcome {
209 Outcome::Fine => (Answer::Fine, false, true),
210 Outcome::Broken(why) => (Answer::Broken(why), true, true),
211 Outcome::Unreachable(why) => {
212 failures += 1;
213 let shown = failures >= FAILURES_BEFORE_A_PROBLEM;
214 (Answer::Unreachable(failures, why), shown, false)
215 }
216 };
217 self.answers
218 .lock()
219 .unwrap_or_else(|poisoned| poisoned.into_inner())
220 .insert(address.clone(), answer);
221 if shown_now != shown_before
223 && let Some(changes) = &self.changes
224 {
225 changes.publish(&Scope::Every, Change::Refresh);
227 }
228 if done {
229 return;
230 }
231 let pause = self.waits.retry_after * (1 << (failures - 1).min(2));
233 self.background.sleep(pause).await;
234 }
235 }
236
237 #[cfg(any(test, feature = "testing"))]
239 pub fn failures(&self, address: &str) -> u32 {
240 match self.answers.lock().unwrap().get(address) {
241 Some(Answer::Unreachable(failures, _)) => *failures,
242 _ => 0,
243 }
244 }
245}
246
247#[cfg(any(test, feature = "testing"))]
249pub mod testing {
250 use super::*;
251
252 struct Fine;
254
255 impl Ask for Fine {
256 fn ask<'a>(&'a self, _: &'a str, _: Duration) -> BoxFuture<'a, Outcome> {
257 Box::pin(async { Outcome::Fine })
258 }
259 }
260
261 struct Nowhere;
263
264 impl Background for Nowhere {
265 fn spawn(&self, _: BoxFuture<'static, ()>) -> bool {
266 false
267 }
268
269 fn sleep(&self, _: Duration) -> BoxFuture<'static, ()> {
270 Box::pin(async {})
271 }
272 }
273
274 pub fn offline() -> Arc<External> {
277 External::new(Arc::new(Fine), Arc::new(Nowhere), Waits::default(), None)
278 }
279}
280
281#[cfg(test)]
282mod tests {
283 use super::*;
284
285 #[derive(Default)]
288 struct Table {
289 script: HashMap<String, Vec<Outcome>>,
290 asked: Mutex<HashMap<String, usize>>,
291 }
292
293 impl Table {
294 fn with(mut self, address: &str, outcomes: &[Outcome]) -> Self {
295 self.script.insert(address.into(), outcomes.to_vec());
296 self
297 }
298
299 fn asked(&self, address: &str) -> usize {
300 self.asked
301 .lock()
302 .unwrap()
303 .get(address)
304 .copied()
305 .unwrap_or(0)
306 }
307 }
308
309 impl Ask for Table {
310 fn ask<'a>(&'a self, address: &'a str, _wait: Duration) -> BoxFuture<'a, Outcome> {
311 let mut asked = self.asked.lock().unwrap();
312 let n = asked.entry(address.into()).or_default();
313 let script = &self.script[address];
314 let outcome = script[(*n).min(script.len() - 1)].clone();
315 *n += 1;
316 Box::pin(async move { outcome })
317 }
318 }
319
320 fn quick() -> Waits {
321 Waits {
322 first: Duration::from_millis(1),
323 retry: Duration::from_millis(1),
324 retry_after: Duration::from_millis(1),
325 }
326 }
327
328 fn link(address: &str) -> Link {
329 ("README.md".into(), Some(3), address.into())
330 }
331
332 struct Tokio;
334
335 impl Background for Tokio {
336 fn spawn(&self, task: BoxFuture<'static, ()>) -> bool {
337 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
338 return false;
339 };
340 runtime.spawn(task);
341 true
342 }
343
344 fn sleep(&self, pause: Duration) -> BoxFuture<'static, ()> {
345 Box::pin(tokio::time::sleep(pause))
346 }
347 }
348
349 struct Heard(tokio::sync::mpsc::UnboundedSender<Change>);
351
352 impl Publish for Heard {
353 fn publish(&self, _scope: &Scope, change: Change) {
354 let _ = self.0.send(change);
355 }
356 }
357
358 fn down() -> Outcome {
359 Outcome::Unreachable("no connection".into())
360 }
361
362 #[tokio::test]
363 async fn check_asks_an_unreachable_address_once_more_and_a_broken_one_once() {
364 let table = Arc::new(
365 Table::default()
366 .with("slow", &[down(), Outcome::Fine])
367 .with("drop", &[down()])
368 .with("gone", &[Outcome::Broken("404 Not Found".into())]),
369 );
370 let external = External::new(table.clone(), Arc::new(Tokio), quick(), None);
371 let found: Vec<String> = external
372 .check(vec![link("slow"), link("drop"), link("gone"), link("gone")])
373 .await
374 .iter()
375 .map(ToString::to_string)
376 .collect();
377 let mut found = found;
378 found.sort();
379 assert_eq!(
380 found,
381 vec![
382 "README.md:3: drop — no connection",
383 "README.md:3: gone — 404 Not Found",
384 "README.md:3: gone — 404 Not Found",
385 ]
386 );
387 assert_eq!(
388 (
389 table.asked("slow"),
390 table.asked("drop"),
391 table.asked("gone")
392 ),
393 (2, 2, 1)
394 );
395 }
396
397 #[tokio::test]
398 async fn the_preview_shows_an_unreachable_address_only_after_three_failures() {
399 let table = Arc::new(Table::default().with("flaky", &[down()]));
400 let (changes, mut heard) = tokio::sync::mpsc::unbounded_channel();
401 let external = External::new(
402 table,
403 Arc::new(Tokio),
404 quick(),
405 Some(Arc::new(Heard(changes))),
406 );
407 assert!(external.preview(vec![link("flaky")]).is_empty());
408 assert_eq!(heard.recv().await, Some(Change::Refresh));
410 assert!(external.failures("flaky") >= FAILURES_BEFORE_A_PROBLEM);
411 assert_eq!(
412 external
413 .preview(vec![link("flaky")])
414 .iter()
415 .map(ToString::to_string)
416 .collect::<Vec<_>>(),
417 vec!["README.md:3: flaky — no connection, 3 times in a row"]
418 );
419 }
420
421 #[test]
422 fn outside_a_runtime_the_preview_asks_nothing() {
423 let table = Arc::new(Table::default().with("x", &[Outcome::Fine]));
424 let external = External::new(table.clone(), Arc::new(Tokio), quick(), None);
425 assert!(external.preview(vec![link("x")]).is_empty());
426 assert_eq!(table.asked("x"), 0);
427 }
428}