Skip to main content

devpage_core/
external.rs

1//! External links: whether each address a page links to outside devpage
2//! answers. `devpage check` asks each address once (twice if it can't be
3//! reached); the preview asks in the background and shows what it has heard,
4//! announcing on the change bus when that changes.
5//!
6//! How an address is asked is the [`Ask`] port, and where the preview's
7//! background asking runs is the [`Background`] port: the `devpage` binary
8//! asks the network over HTTP and runs on its runtime; tests answer from a
9//! table.
10
11use 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
21/// One external link: the page it is on, its line, and the address.
22pub type Link = (String, Option<usize>, String);
23
24/// What asking an external address once found.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum Outcome {
27    /// A status below 400, following redirects.
28    Fine,
29    /// A definite answer of 400 or above: the link is broken.
30    Broken(String),
31    /// No answer in time, or no connection: maybe the network, maybe the site.
32    Unreachable(String),
33}
34
35/// Asks an address once, giving it `wait` to answer.
36pub trait Ask: Send + Sync {
37    /// What asking `address` once found, given `wait` to answer.
38    fn ask<'a>(&'a self, address: &'a str, wait: Duration) -> BoxFuture<'a, Outcome>;
39}
40
41/// Where the preview's background asking runs, and how it waits between
42/// tries.
43pub trait Background: Send + Sync {
44    /// Runs `task` in the background; `false` when there is nowhere to run
45    /// it — a unit test rendering a page outside a runtime.
46    fn spawn(&self, task: BoxFuture<'static, ()>) -> bool;
47    /// Waits `pause`.
48    fn sleep(&self, pause: Duration) -> BoxFuture<'static, ()>;
49}
50
51/// How long an address gets to answer, and how the preview retries one that
52/// didn't.
53#[derive(Debug, Clone, Copy)]
54pub struct Waits {
55    /// How long an address gets to answer the first time it is asked.
56    pub first: Duration,
57    /// `devpage check`'s second, longer try.
58    pub retry: Duration,
59    /// The preview's first pause before asking again; it doubles twice.
60    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
73/// The preview reports an address that can't be reached only after this many
74/// failures in a row; one slow answer is the network, not a broken link.
75const FAILURES_BEFORE_A_PROBLEM: u32 = 3;
76
77/// What the preview knows about each external address.
78enum Answer {
79    /// Being asked for the first time; no answer yet.
80    Pending,
81    /// A status below 400, following redirects.
82    Fine,
83    /// A definite answer of 400 or above, and what it was.
84    Broken(String),
85    /// Not reached this many times in a row; still being retried.
86    Unreachable(u32, String),
87}
88
89/// The external-link checker: one per devpage process, shared by every page.
90pub struct External {
91    /// How an address is asked.
92    ask: Arc<dyn Ask>,
93    /// Where the preview's background asking runs.
94    background: Arc<dyn Background>,
95    /// How long an address gets to answer, and how the preview retries one that
96    /// didn't.
97    waits: Waits,
98    /// Every address the preview has asked about, for as long as it lives.
99    answers: Mutex<HashMap<String, Answer>>,
100    /// Where the preview announces a change in what it would show, so open
101    /// pages fetch themselves again.
102    changes: Option<Arc<dyn Publish>>,
103}
104
105impl External {
106    /// The checker that asks with `ask`, runs the preview's asking on
107    /// `background` with `waits`, and announces changes on `changes` — or
108    /// nowhere.
109    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    /// Checks each address once, however many pages link to it, and reports
125    /// a problem for every link to a broken one — for `devpage check`.
126    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    /// Why an address is broken, or `None` when it answers. One that can't be
154    /// reached is asked once more, with longer to answer, before it counts.
155    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    /// The problems the preview can show now for these links: a definite
167    /// error, or an address not reached three times in a row. An address it
168    /// hasn't asked about is asked in the background — outside a runtime (a
169    /// unit test rendering a page) nothing is.
170    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                    // The answers stay locked until `Pending` is in, so the
201                    // task can't record an answer before it.
202                    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    /// Asks an address in the background until it gives a definite answer,
215    /// retrying one that can't be reached after a growing pause, and asks
216    /// open pages to fetch themselves again whenever what they would show
217    /// changes.
218    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            // A problem appeared or cleared: open pages show the difference.
237            if shown_now != shown_before
238                && let Some(changes) = &self.changes
239            {
240                // Any page on the bus may link to the address.
241                changes.publish(Change::Refresh);
242            }
243            if done {
244                return;
245            }
246            // 30 s, then 60 s, then every 120 s while it stays out of reach.
247            let pause = self.waits.retry_after * (1 << (failures - 1).min(2));
248            self.background.sleep(pause).await;
249        }
250    }
251
252    /// How many times in a row the preview has failed to reach `address`.
253    #[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/// External checkers for tests.
263#[cfg(any(test, feature = "testing"))]
264pub mod testing {
265    use super::*;
266
267    /// Answers every address fine.
268    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    /// Runs nothing in the background.
277    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    /// A checker that finds every address fine and whose preview asks none:
290    /// for tests about everything but external links.
291    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    /// Answers from a script per address, one outcome per ask, repeating the
301    /// last; and counts the asks.
302    #[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    /// Runs on the test's tokio runtime, as `devpage` runs on its own.
348    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    /// Hears what the preview publishes.
365    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        // Announced once, when the third failure makes it a problem.
424        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}