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, Scope};
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    fn ask<'a>(&'a self, address: &'a str, wait: Duration) -> BoxFuture<'a, Outcome>;
38}
39
40/// Where the preview's background asking runs, and how it waits between
41/// tries.
42pub trait Background: Send + Sync {
43    /// Runs `task` in the background; `false` when there is nowhere to run
44    /// it — a unit test rendering a page outside a runtime.
45    fn spawn(&self, task: BoxFuture<'static, ()>) -> bool;
46    /// Waits `pause`.
47    fn sleep(&self, pause: Duration) -> BoxFuture<'static, ()>;
48}
49
50/// How long an address gets to answer, and how the preview retries one that
51/// didn't.
52#[derive(Debug, Clone, Copy)]
53pub struct Waits {
54    pub first: Duration,
55    /// `devpage check`'s second, longer try.
56    pub retry: Duration,
57    /// The preview's first pause before asking again; it doubles twice.
58    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
71/// The preview reports an address that can't be reached only after this many
72/// failures in a row; one slow answer is the network, not a broken link.
73const FAILURES_BEFORE_A_PROBLEM: u32 = 3;
74
75/// What the preview knows about each external address.
76enum Answer {
77    Pending,
78    Fine,
79    Broken(String),
80    /// Not reached this many times in a row; still being retried.
81    Unreachable(u32, String),
82}
83
84/// The external-link checker: one per devpage process, shared by every page.
85pub struct External {
86    ask: Arc<dyn Ask>,
87    background: Arc<dyn Background>,
88    waits: Waits,
89    /// Every address the preview has asked about, for as long as it lives.
90    answers: Mutex<HashMap<String, Answer>>,
91    /// Where the preview announces a change in what it would show, so open
92    /// pages fetch themselves again.
93    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    /// Checks each address once, however many pages link to it, and reports
113    /// a problem for every link to a broken one — for `devpage check`.
114    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    /// Why an address is broken, or `None` when it answers. One that can't be
141    /// reached is asked once more, with longer to answer, before it counts.
142    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    /// The problems the preview can show now for these links: a definite
154    /// error, or an address not reached three times in a row. An address it
155    /// hasn't asked about is asked in the background — outside a runtime (a
156    /// unit test rendering a page) nothing is.
157    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                    // The answers stay locked until `Pending` is in, so the
186                    // task can't record an answer before it.
187                    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    /// Asks an address in the background until it gives a definite answer,
200    /// retrying one that can't be reached after a growing pause, and asks
201    /// open pages to fetch themselves again whenever what they would show
202    /// changes.
203    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            // A problem appeared or cleared: open pages show the difference.
222            if shown_now != shown_before
223                && let Some(changes) = &self.changes
224            {
225                // Any page may link to the address, whatever its document.
226                changes.publish(&Scope::Every, Change::Refresh);
227            }
228            if done {
229                return;
230            }
231            // 30 s, then 60 s, then every 120 s while it stays out of reach.
232            let pause = self.waits.retry_after * (1 << (failures - 1).min(2));
233            self.background.sleep(pause).await;
234        }
235    }
236
237    /// How many times in a row the preview has failed to reach `address`.
238    #[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/// External checkers for tests.
248#[cfg(any(test, feature = "testing"))]
249pub mod testing {
250    use super::*;
251
252    /// Answers every address fine.
253    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    /// Runs nothing in the background.
262    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    /// A checker that finds every address fine and whose preview asks none:
275    /// for tests about everything but external links.
276    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    /// Answers from a script per address, one outcome per ask, repeating the
286    /// last; and counts the asks.
287    #[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    /// Runs on the test's tokio runtime, as `devpage` runs on its own.
333    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    /// Hears what the preview publishes.
350    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        // Announced once, when the third failure makes it a problem.
409        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}