Skip to main content

mln_engine/storage/
loader.rs

1use std::sync::Arc;
2
3use parking_lot::Mutex;
4
5use crate::exec::pool::Pool;
6use crate::storage::asset_file_source::AssetFileSource;
7#[cfg(feature = "sqlite")]
8use crate::storage::chrono::now;
9#[cfg(feature = "sqlite")]
10use crate::storage::database_file_source::Cache;
11#[cfg(all(feature = "sqlite", not(target_family = "wasm")))]
12use crate::storage::database_file_source::DatabaseFileSource;
13use crate::storage::file_source::FileSource;
14use crate::storage::local_file_source::LocalFileSource;
15#[cfg(feature = "sqlite")]
16use crate::storage::mbtiles_file_source::MBTilesFileSource;
17#[cfg(not(target_family = "wasm"))]
18use crate::storage::network_status::NetworkStatus;
19#[cfg(not(target_family = "wasm"))]
20use crate::storage::online_file_source::OnlineFileSource;
21use crate::storage::pmtiles_file_source::PMTilesFileSource;
22use crate::storage::request::{Request, Responder};
23#[cfg(feature = "sqlite")]
24use crate::storage::resource::Priority;
25use crate::storage::resource::{LoadingMethod, Resource};
26#[cfg(not(target_family = "wasm"))]
27use crate::storage::resource_options::ResourceOptions;
28use crate::storage::response::{Reason, ResourceError, Response};
29
30/// The file sources a [`Loader`] picks from.
31#[derive(Clone)]
32struct Sources {
33    asset: Arc<dyn FileSource>,
34    local: Arc<dyn FileSource>,
35    #[cfg(feature = "sqlite")]
36    mbtiles: Arc<dyn FileSource>,
37    pmtiles: Option<Arc<dyn FileSource>>,
38    #[cfg(feature = "sqlite")]
39    database: Option<Arc<dyn Cache>>,
40    network: Option<Arc<dyn FileSource>>,
41}
42
43/// A request's sub-request in flight, which goes when the request is
44/// cancelled.
45type Task = Arc<Mutex<Option<Request>>>;
46
47impl Sources {
48    /// The first of the local file sources that loads `resource`.
49    fn local_for(&self, resource: &Resource) -> Option<&Arc<dyn FileSource>> {
50        #[cfg(feature = "sqlite")]
51        let mbtiles = Some(&self.mbtiles);
52        #[cfg(not(feature = "sqlite"))]
53        let mbtiles = None;
54        [Some(&self.asset), mbtiles, self.pmtiles.as_ref(), Some(&self.local)]
55            .into_iter()
56            .flatten()
57            .find(|source| source.can_request(resource))
58    }
59
60    #[cfg(feature = "sqlite")]
61    fn database_for(&self, resource: &Resource) -> Option<&Arc<dyn Cache>> {
62        self.database.as_ref().filter(|database| database.can_request(resource))
63    }
64
65    #[cfg(not(feature = "sqlite"))]
66    #[expect(clippy::unused_self, reason = "the build without SQLite has no database")]
67    fn database_for(&self, _resource: &Resource) -> Option<&Arc<dyn FileSource>> {
68        None
69    }
70
71    fn network_for(&self, resource: &Resource) -> Option<&Arc<dyn FileSource>> {
72        self.network.as_ref().filter(|network| network.can_request(resource))
73    }
74
75    #[cfg(feature = "sqlite")]
76    fn has_database(&self) -> bool {
77        self.database.is_some()
78    }
79
80    #[cfg(not(feature = "sqlite"))]
81    #[expect(clippy::unused_self, reason = "the build without SQLite has no database")]
82    fn has_database(&self) -> bool {
83        false
84    }
85
86    /// Stores a response from the network in the database.
87    #[cfg(feature = "sqlite")]
88    fn store(&self, resource: &Resource, response: &Response) {
89        if let Some(database) = &self.database {
90            database.put(resource, response);
91        }
92    }
93
94    #[cfg(not(feature = "sqlite"))]
95    #[expect(clippy::unused_self, reason = "the build without SQLite has no database")]
96    fn store(&self, _resource: &Resource, _response: &Response) {}
97
98    /// Requests `res` from the network for `resource`'s requester, in place
99    /// of `task`'s request before, and stores the responses in the database.
100    /// Without a network file source that loads `resource`, `task`'s request
101    /// stays.
102    ///
103    /// The callbacks that the file sources hold reach the sources weakly:
104    /// the network and the database refer to each other's file sources, and
105    /// a strong reference would leave the last of them to drop on its own
106    /// thread.
107    fn request_from_network(self: &Arc<Self>, resource: &Resource, res: &Resource, task: &Task, responder: &Responder) {
108        let Some(network) = self.network_for(resource) else {
109            return;
110        };
111        if !self.has_database() {
112            let previous = task.lock().take();
113            drop(previous);
114            network.load(res, responder.clone());
115            return;
116        }
117        let (sources, stored, responder) = (Arc::downgrade(self), res.clone(), responder.clone());
118        let (request, network_responder) = Request::new(move |response: Response| {
119            if let Some(sources) = sources.upgrade() {
120                sources.store(&stored, &response);
121            }
122            responder.send(response);
123        });
124        let previous = task.lock().replace(request);
125        drop(previous);
126        network.load(res, network_responder);
127    }
128
129    /// Loads `resource` from the cache, then from the network. A usable
130    /// cached copy goes to the requester at once, and the network revalidates
131    /// it at low priority once it is stale. A copy that must revalidate first
132    /// waits for the network, and the requester gets it on a 304
133    /// (`Resource::deliver`).
134    #[cfg(feature = "sqlite")]
135    fn request_cached(self: &Arc<Self>, database: &dyn Cache, resource: &Resource, responder: Responder) {
136        let task: Task = Arc::default();
137        let cancelled = Arc::clone(&task);
138        responder.on_cancel(move || drop(cancelled.lock().take()));
139
140        let (sources, resource_copy, chain) = (Arc::downgrade(self), resource.clone(), Arc::clone(&task));
141        let (request, database_responder) = Request::new(move |response: Response| {
142            let Some(sources) = sources.upgrade() else { return };
143            let mut res = resource_copy.clone();
144
145            // A cached copy.
146            if response.error.is_none() && !response.no_content {
147                res.set_prior(&response);
148                if response.caching.is_usable(now()) {
149                    responder.send(response.clone());
150                    res.set_priority(Priority::Low);
151                } else {
152                    res.prior_data = response.data.clone();
153                }
154            }
155
156            sources.request_from_network(&resource_copy, &res, &chain, &responder);
157        });
158        *task.lock() = Some(request);
159        database.load(resource, database_responder);
160    }
161}
162
163/// The resource loader: one file source over the asset, file, MBTiles and
164/// PMTiles file sources, and the cache database and network, if it has them.
165///
166/// A request goes to the first local file source that loads its URL.
167/// Failing that, it goes to the database, and on to the network unless it's
168/// cache-only: the network revalidates a cached copy as its caching rules
169/// say, and the database stores what the network answers. A cache-only
170/// request gets the stored copy whatever its freshness; its caching rules
171/// say how it may be used.
172pub struct Loader {
173    sources: Arc<Sources>,
174}
175
176impl Loader {
177    /// A loader for `options`: assets from its asset path, a cache database
178    /// at its cache path (when the `sqlite` feature is on), and an
179    /// [`OnlineFileSource`] for the network, with a [`NetworkStatus`] of its
180    /// own, which stays online. It reads files and archives on `pool`.
181    #[cfg(not(target_family = "wasm"))]
182    #[must_use]
183    pub fn new(options: &ResourceOptions, pool: &Pool) -> Loader {
184        let network: Arc<dyn FileSource> = Arc::new(OnlineFileSource::new(Arc::new(NetworkStatus::new())));
185        let builder = Loader::builder(pool).asset_path(&options.asset_path).network(Arc::clone(&network));
186        #[cfg(feature = "sqlite")]
187        let builder = builder.database(Arc::new(DatabaseFileSource::new(&options.cache_path, Some(network))));
188        builder.build()
189    }
190
191    /// A builder for a loader with neither a database nor a network, which
192    /// reads files and archives on `pool`.
193    pub fn builder(pool: &Pool) -> LoaderBuilder {
194        LoaderBuilder {
195            asset_path: ".".to_owned(),
196            #[cfg(feature = "sqlite")]
197            database: None,
198            network: None,
199            pool: pool.clone(),
200        }
201    }
202}
203
204/// Builds a [`Loader`] from the file sources it's given.
205#[must_use]
206pub struct LoaderBuilder {
207    asset_path: String,
208    #[cfg(feature = "sqlite")]
209    database: Option<Arc<dyn Cache>>,
210    network: Option<Arc<dyn FileSource>>,
211    pool: Pool,
212}
213
214impl LoaderBuilder {
215    /// Loads `asset://` URLs from the directory `path`, rather than the
216    /// working directory.
217    pub fn asset_path(mut self, path: &str) -> Self {
218        path.clone_into(&mut self.asset_path);
219        self
220    }
221
222    /// Caches responses in `database`, and answers cache-only requests from
223    /// it.
224    #[cfg(feature = "sqlite")]
225    pub fn database(mut self, database: Arc<dyn Cache>) -> Self {
226        self.database = Some(database);
227        self
228    }
229
230    /// Loads the requests that no local file source loads through `network`.
231    pub fn network(mut self, network: Arc<dyn FileSource>) -> Self {
232        self.network = Some(network);
233        self
234    }
235
236    #[must_use]
237    pub fn build(self) -> Loader {
238        let pool = self.pool;
239        let mut sources = Sources {
240            asset: Arc::new(AssetFileSource::new(&self.asset_path, pool.clone())),
241            local: Arc::new(LocalFileSource::new(pool.clone())),
242            #[cfg(feature = "sqlite")]
243            mbtiles: Arc::new(MBTilesFileSource::new(pool.clone())),
244            pmtiles: None,
245            #[cfg(feature = "sqlite")]
246            database: self.database,
247            network: self.network,
248        };
249        // PMTiles archives load through the same file sources, but a PMTiles
250        // archive inside another isn't one.
251        let archives: Arc<dyn FileSource> = Arc::new(Loader { sources: Arc::new(sources.clone()) });
252        sources.pmtiles = Some(Arc::new(PMTilesFileSource::new(archives, pool)));
253        Loader { sources: Arc::new(sources) }
254    }
255}
256
257impl FileSource for Loader {
258    fn supports_cache_only(&self) -> bool {
259        self.sources.has_database()
260    }
261
262    fn load(&self, resource: &Resource, responder: Responder) {
263        let sources = &self.sources;
264        if let Some(local) = sources.local_for(resource) {
265            local.load(resource, responder);
266        } else if let Some(database) = sources.database_for(resource) {
267            if resource.loading_method == LoadingMethod::CacheOnly {
268                database.load(resource, responder);
269            } else {
270                #[cfg(feature = "sqlite")]
271                sources.request_cached(&**database, resource, responder);
272            }
273        } else if sources.network_for(resource).is_some() {
274            let task: Task = Arc::default();
275            let cancelled = Arc::clone(&task);
276            responder.on_cancel(move || drop(cancelled.lock().take()));
277            sources.request_from_network(resource, resource, &task, &responder);
278        } else {
279            // No file source loads the resource.
280            let mut response = Response::new();
281            response.no_content = true;
282            response.error = Some(Box::new(ResourceError::new(Reason::Other, "Unsupported resource request.")));
283            responder.send(response);
284        }
285    }
286
287    fn can_request(&self, resource: &Resource) -> bool {
288        self.sources.local_for(resource).is_some()
289            || self.sources.database_for(resource).is_some()
290            || self.sources.network_for(resource).is_some()
291    }
292}