Skip to main content

shaul_core/
router.rs

1use std::sync::Arc;
2
3use crate::backend::DownloadBackend;
4use crate::error::{Error, Result};
5use crate::link::Link;
6use crate::parser::{LinkParser, ParseOptions, ParserRegistry};
7use crate::resource::Resource;
8
9/// A parsed resource together with the parser and backend selected for it.
10#[derive(Clone)]
11pub struct RoutedResource {
12    /// The protocol-agnostic resource produced by the parser.
13    pub resource: Resource,
14    /// The first registered backend whose `supports` accepted the resource.
15    pub backend: Arc<dyn DownloadBackend>,
16    /// Name of the parser that produced the resource.
17    pub parser: &'static str,
18}
19
20/// Resolves links through an ordered parser list and selects the first
21/// backend that supports the resulting resource.
22pub struct Router {
23    parsers: ParserRegistry,
24    backends: Vec<Arc<dyn DownloadBackend>>,
25}
26
27impl Router {
28    /// Creates a router from parser and backend lists. Both lists are ordered:
29    /// the first parser that claims a link and the first backend that supports
30    /// the resulting resource win.
31    pub fn new(parsers: ParserRegistry, backends: Vec<Arc<dyn DownloadBackend>>) -> Self {
32        Self { parsers, backends }
33    }
34
35    /// Returns the parser registry used by [`Router::resolve`].
36    pub fn parsers(&self) -> &ParserRegistry {
37        &self.parsers
38    }
39
40    /// Returns the backends in priority order.
41    pub fn backends(&self) -> &[Arc<dyn DownloadBackend>] {
42        &self.backends
43    }
44
45    /// The first parser that claims a link is authoritative. Falling through
46    /// to a later parser after a Hub metadata error would silently download
47    /// an HTML page as if it were a file, so parse errors are propagated.
48    pub async fn resolve(&self, link: &Link, options: &ParseOptions) -> Result<RoutedResource> {
49        for parser in self.parsers.iter() {
50            if !parser.supports(link) {
51                continue;
52            }
53            let resource = parser.parse(link, options).await?;
54            let backend = self.backend_for(&resource)?;
55            return Ok(RoutedResource {
56                resource,
57                backend,
58                parser: parser.name(),
59            });
60        }
61        Err(Error::NoParser(link.to_string()))
62    }
63
64    /// Returns the first registered backend that supports `resource`, or
65    /// [`Error::NoBackend`] when none does.
66    pub fn backend_for(&self, resource: &Resource) -> Result<Arc<dyn DownloadBackend>> {
67        self.backends
68            .iter()
69            .find(|backend| backend.supports(resource))
70            .cloned()
71            .ok_or_else(|| Error::NoBackend(format!("{:?}", resource.kind)))
72    }
73}
74
75/// Erases a concrete parser into the trait object accepted by
76/// [`ParserRegistry::register`](crate::parser::ParserRegistry::register).
77pub fn parser_arc(parser: impl LinkParser + 'static) -> Arc<dyn LinkParser> {
78    Arc::new(parser)
79}
80
81/// Erases a concrete backend into the trait object accepted by
82/// [`Router::new`].
83pub fn backend_arc(backend: impl DownloadBackend + 'static) -> Arc<dyn DownloadBackend> {
84    Arc::new(backend)
85}