Skip to main content

jsonld_core/loader/
chain.rs

1use crate::LoadError;
2use iri_rs::{Iri, IriBuf};
3
4use super::{Loader, RemoteDocument};
5
6/// * [`ChainLoader`]: loads document from the first loader, otherwise falls back to the second one.
7///
8/// This can be useful for combining, for example,
9/// an [`FsLoader`](super::FsLoader) for loading some contexts from a local cache,
10/// and a [`ReqwestLoader`](super::ReqwestLoader) for loading any other context from the web.
11///
12/// Note that it is also possible to nest several [`ChainLoader`]s,
13/// to combine more than two loaders.
14#[derive(Debug, Clone)]
15pub struct ChainLoader<L1, L2>(L1, L2);
16
17impl<L1, L2> ChainLoader<L1, L2> {
18    /// Build a new chain loader
19    pub fn new(l1: L1, l2: L2) -> Self {
20        ChainLoader(l1, l2)
21    }
22}
23
24impl<L1, L2> Loader for ChainLoader<L1, L2>
25where
26    L1: Loader,
27    L2: Loader,
28{
29    type Error = ChainError<L1::Error, L2::Error>;
30
31    #[expect(
32        clippy::disallowed_methods,
33        reason = "a loader delegating to the loader it wraps already runs inside its caller's guarded poll"
34    )]
35    async fn load(&self, url: Iri<&str>) -> Result<RemoteDocument<IriBuf>, LoadError<Self::Error>> {
36        match self.0.load(url).await {
37            Ok(doc) => Ok(doc),
38            Err(LoadError { source: e1, .. }) => match self.1.load(url).await {
39                Ok(doc) => Ok(doc),
40                Err(LoadError { target, source: e2 }) => Err(LoadError::new(target, ChainError::Both(e1, e2))),
41            },
42        }
43    }
44}
45
46/// Combined error from two chained loaders.
47///
48/// The second loader is only consulted after the first has failed, so a
49/// chain failure always carries both errors.
50#[derive(Debug, thiserror::Error)]
51pub enum ChainError<A, B> {
52    /// Both loaders failed.
53    #[error("both loaders failed: {0}, then {1}")]
54    Both(A, B),
55}