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