Skip to main content

mln_runtime/
resources.rs

1//! How a runtime loads resources: a host's resource provider in front of the
2//! network, and the transforms of request URLs and headers.
3
4use std::sync::Arc;
5use std::sync::atomic::{AtomicBool, Ordering};
6
7use mln_storage::http_header_transform::HttpHeaders;
8use mln_storage::resource::Kind;
9use mln_storage::response::Reason;
10use mln_storage::{FileSource, OnlineFileSource, Resource, ResourceError, Responder, Response};
11use mln_util::error::Error;
12use parking_lot::{Mutex, RwLock};
13
14/// Serves a runtime's network requests in place of the library.
15///
16/// A closure `Fn(ResourceRequest)` is a provider that serves every request.
17/// The library loads only `http` and `https`, so without a resource
18/// transform, a request for another scheme that no provider serves fails at
19/// once.
20pub trait ResourceProvider: Send + Sync + 'static {
21    /// Whether the provider serves a request for a resource of `kind` at
22    /// `url`. The library loads the requests that the provider doesn't
23    /// serve.
24    fn serves(&self, _kind: Kind, _url: &str) -> bool {
25        true
26    }
27
28    /// Serves `request`: answer it with [`ResourceRequest::respond`], or hand
29    /// it back with [`ResourceRequest::pass_through`], now or later and on
30    /// any thread. It runs on a thread of the library's, which waits for it,
31    /// and so does a replacement of the provider, so it should hand slow
32    /// work elsewhere.
33    fn request(&self, request: ResourceRequest);
34}
35
36impl<F: Fn(ResourceRequest) + Send + Sync + 'static> ResourceProvider for F {
37    fn request(&self, request: ResourceRequest) {
38        self(request);
39    }
40}
41
42/// A maintenance action on a runtime's cache database.
43#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
44pub enum CacheDatabaseOperation {
45    /// Deletes the ambient cache's resources and frees their space. Offline
46    /// regions keep theirs.
47    Clear,
48    /// Keeps the ambient cache's resources, but makes them stale: maps check
49    /// each with its server when they next use it, and show it meanwhile
50    /// unless the server requires checking it first. Offline regions are
51    /// unaffected.
52    Invalidate,
53    /// Compacts the database file to free the space it no longer uses.
54    Pack,
55    /// Deletes the whole database, offline regions included, and starts an
56    /// empty one.
57    Reset,
58}
59
60/// The runtime's hooks that its network file source reads on each request.
61#[derive(Default)]
62pub(crate) struct ResourceHooks {
63    /// A request reads the provider for as long as it routes to it and calls
64    /// it, so that a replacement, which writes it, comes after any call to
65    /// the provider it replaces, and drops that provider itself.
66    provider: RwLock<Option<Box<dyn ResourceProvider>>>,
67    /// Whether a resource transform is set, which may rewrite a URL of any
68    /// scheme into one that the library loads.
69    transform_set: AtomicBool,
70}
71
72impl ResourceHooks {
73    /// Replaces the provider, once no request is calling the one before,
74    /// and gives that one back.
75    pub(crate) fn set_provider(
76        &self,
77        provider: Option<Box<dyn ResourceProvider>>,
78    ) -> Option<Box<dyn ResourceProvider>> {
79        std::mem::replace(&mut *self.provider.write(), provider)
80    }
81
82    pub(crate) fn set_transform_set(&self, set: bool) {
83        self.transform_set.store(set, Ordering::Release);
84    }
85}
86
87/// The runtime's network file source: the library's online file source,
88/// behind the host's resource provider.
89pub(crate) struct ProviderFileSource {
90    online: Arc<OnlineFileSource>,
91    hooks: Arc<ResourceHooks>,
92}
93
94/// Who loads a request.
95enum Route<'a> {
96    /// The provider.
97    Provider(&'a dyn ResourceProvider),
98    /// The library. `declined` says whether a provider is set, which the
99    /// message of a request that the library can't load names.
100    Native { declined: bool },
101}
102
103impl ProviderFileSource {
104    pub(crate) fn new(online: Arc<OnlineFileSource>, hooks: Arc<ResourceHooks>) -> Self {
105        ProviderFileSource { online, hooks }
106    }
107
108    /// Who loads `resource`, when `provider` is the runtime's provider.
109    fn route<'a>(resource: &Resource, provider: Option<&'a dyn ResourceProvider>) -> Route<'a> {
110        if !resource.has_loading_method(mln_storage::LoadingMethod::Network) {
111            return Route::Native { declined: false };
112        }
113        let Some(provider) = provider else {
114            return Route::Native { declined: false };
115        };
116        if provider.serves(resource.kind, &resource.url) {
117            Route::Provider(provider)
118        } else {
119            Route::Native { declined: true }
120        }
121    }
122
123    fn native(&self) -> Native {
124        Native { online: Arc::clone(&self.online), hooks: Arc::clone(&self.hooks) }
125    }
126}
127
128/// The library's own loading, which fails a request for a URL scheme that
129/// it can't load at once, rather than sending it to the network.
130#[derive(Clone)]
131struct Native {
132    online: Arc<OnlineFileSource>,
133    hooks: Arc<ResourceHooks>,
134}
135
136impl Native {
137    fn load(&self, resource: &Resource, responder: Responder, declined: bool) {
138        match self.unsupported_scheme(&resource.url) {
139            Some(scheme) => responder.send(unsupported_scheme(scheme, &resource.url, declined)),
140            None => self.online.load(resource, responder),
141        }
142    }
143
144    /// The scheme of `url` when the online file source can't load it.
145    fn unsupported_scheme<'a>(&self, url: &'a str) -> Option<&'a str> {
146        if self.hooks.transform_set.load(Ordering::Acquire) {
147            return None;
148        }
149        let scheme = url_scheme(url)?;
150        let loadable = ["http", "https"].iter().any(|known| known.eq_ignore_ascii_case(scheme));
151        (!loadable).then_some(scheme)
152    }
153}
154
155/// The scheme of `url`, as RFC 3986 spells one: a letter, then letters,
156/// digits, `+`, `-` and `.`, before a colon.
157fn url_scheme(url: &str) -> Option<&str> {
158    let (scheme, _) = url.split_once(':')?;
159    let mut bytes = scheme.bytes();
160    let first = bytes.next()?;
161    (first.is_ascii_alphabetic() && bytes.all(|byte| byte.is_ascii_alphanumeric() || b"+-.".contains(&byte)))
162        .then_some(scheme)
163}
164
165/// `url` without its query, fragment and user information, so that a
166/// message never carries credentials.
167fn redacted_url(url: &str) -> String {
168    let end = url.find(['?', '#']).unwrap_or(url.len());
169    let mut url = url[..end].to_owned();
170    if let Some(separator) = url.find("://") {
171        let authority = separator + 3;
172        let authority_end = url[authority..].find('/').map_or(url.len(), |end| authority + end);
173        if let Some(at) = url[authority..authority_end].rfind('@') {
174            url.replace_range(authority..=authority + at, "");
175        }
176    }
177    url
178}
179
180fn unsupported_scheme(scheme: &str, url: &str, declined: bool) -> Response {
181    let advice = if declined {
182        "the registered resource provider declined this request; update it to serve this scheme"
183    } else {
184        "register a resource provider with mln_runtime_set_resource_provider() or Runtime::set_resource_provider to \
185         serve this scheme"
186    };
187    let message =
188        format!("unsupported URL scheme \"{scheme}\" for network request \"{}\"; {advice}", redacted_url(url));
189    // A reason that the library doesn't retry, since no retry can succeed.
190    Response { error: Some(Box::new(ResourceError::new(Reason::Other, message))), ..Response::default() }
191}
192
193impl FileSource for ProviderFileSource {
194    fn load(&self, resource: &Resource, responder: Responder) {
195        let hooked = self.hooks.provider.read();
196        let provider = match Self::route(resource, hooked.as_deref()) {
197            Route::Provider(provider) => provider,
198            Route::Native { declined } => {
199                drop(hooked);
200                return self.native().load(resource, responder, declined);
201            }
202        };
203        let shared = Arc::new(RequestShared {
204            state: Mutex::new(RequestState::default()),
205            native: self.native(),
206            resource: resource.clone(),
207            responder: responder.clone(),
208        });
209        let cancelled = Arc::downgrade(&shared);
210        responder.on_cancel(move || {
211            if let Some(shared) = cancelled.upgrade() {
212                shared.cancel();
213            }
214        });
215        let request = ResourceRequest { resource: resource.clone(), shared: Some(Arc::clone(&shared)) };
216        shared.state.lock().in_call = true;
217        provider.request(request);
218        drop(hooked);
219        // An answer that came during the call goes out now, so that the
220        // requester never sees it before the provider's call has returned.
221        let deferred = {
222            let mut state = shared.state.lock();
223            state.in_call = false;
224            state.deferred.take()
225        };
226        if let Some(answer) = deferred {
227            answer(&shared);
228        }
229    }
230
231    fn supports_cache_only(&self) -> bool {
232        self.online.supports_cache_only()
233    }
234
235    fn can_request(&self, resource: &Resource) -> bool {
236        let hooked = self.hooks.provider.read();
237        matches!(Self::route(resource, hooked.as_deref()), Route::Provider(..)) || self.online.can_request(resource)
238    }
239}
240
241#[derive(Default)]
242struct RequestState {
243    /// The requester dropped the request.
244    cancelled: bool,
245    /// The provider answered or passed through.
246    answered: bool,
247    on_cancel: Option<Box<dyn FnOnce() + Send>>,
248    /// The provider's `request` call is running.
249    in_call: bool,
250    /// The answer given during that call, which goes out once it returns.
251    deferred: Option<Answer>,
252}
253
254/// What a provider's answer does with the request.
255type Answer = Box<dyn FnOnce(&RequestShared) + Send>;
256
257/// A provider's request, which its [`ResourceRequest`] and the requester's
258/// cancellation share.
259struct RequestShared {
260    state: Mutex<RequestState>,
261    native: Native,
262    resource: Resource,
263    responder: Responder,
264}
265
266impl RequestShared {
267    /// The requester dropped the request: the host's cancel callback runs
268    /// unless the provider answered.
269    fn cancel(&self) {
270        let on_cancel = {
271            let mut state = self.state.lock();
272            state.cancelled = true;
273            if state.answered { None } else { state.on_cancel.take() }
274        };
275        if let Some(on_cancel) = on_cancel {
276            on_cancel();
277        }
278    }
279
280    fn respond(&self, response: Response) {
281        // A revalidation may withhold the cached copy from the requester
282        // until a "not modified" answer delivers it, as the online file
283        // source's do.
284        let response = self.resource.deliver(response);
285        self.responder.send(response);
286    }
287
288    fn pass_through(&self) {
289        self.native.load(&self.resource, self.responder.clone(), true);
290    }
291}
292
293/// A network request that a [`ResourceProvider`] serves.
294///
295/// Answer it once, with [`respond`](Self::respond) or
296/// [`pass_through`](Self::pass_through). Dropping it unanswered fails the
297/// request.
298pub struct ResourceRequest {
299    resource: Resource,
300    shared: Option<Arc<RequestShared>>,
301}
302
303impl ResourceRequest {
304    /// The resource as the style names it, with the cache's earlier copy in
305    /// its `prior_*` fields.
306    #[must_use]
307    pub fn resource(&self) -> &Resource {
308        &self.resource
309    }
310
311    /// Whether the library no longer needs the request.
312    #[must_use]
313    pub fn is_cancelled(&self) -> bool {
314        self.shared.as_ref().is_none_or(|shared| shared.state.lock().cancelled)
315    }
316
317    /// Calls `on_cancel`, on the requesting thread, if the library cancels
318    /// the request before it is answered. Fails with
319    /// [`ErrorKind::Cancelled`](mln_util::ErrorKind::Cancelled) when the
320    /// library already cancelled it, and
321    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind::InvalidState) when
322    /// the request has a cancel callback already.
323    pub fn on_cancel(&self, on_cancel: impl FnOnce() + Send + 'static) -> Result<(), Error> {
324        let Some(shared) = &self.shared else {
325            return Err(Error::invalid_state("the request was answered"));
326        };
327        let mut state = shared.state.lock();
328        if state.cancelled {
329            return Err(Error::cancelled("the library cancelled the request"));
330        }
331        if state.on_cancel.is_some() {
332            return Err(Error::invalid_state("the request has a cancel callback already"));
333        }
334        state.on_cancel = Some(Box::new(on_cancel));
335        Ok(())
336    }
337
338    /// Answers the request with `response`. Fails with
339    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind::InvalidState) when
340    /// the library cancelled the request.
341    pub fn respond(mut self, response: Response) -> Result<(), Error> {
342        self.answer(move |target| target.respond(response))
343    }
344
345    /// Hands the request back to the library, which loads it from the
346    /// network as it would without a provider. Fails with
347    /// [`ErrorKind::InvalidState`](mln_util::ErrorKind::InvalidState) when
348    /// the library cancelled the request.
349    pub fn pass_through(mut self) -> Result<(), Error> {
350        self.answer(RequestShared::pass_through)
351    }
352
353    fn answer(&mut self, answer: impl FnOnce(&RequestShared) + Send + 'static) -> Result<(), Error> {
354        let Some(shared) = self.shared.take() else {
355            return Err(Error::invalid_state("the request was answered"));
356        };
357        let (on_cancel, answer) = {
358            let mut state = shared.state.lock();
359            if state.cancelled {
360                return Err(Error::invalid_state("the library cancelled the request"));
361            }
362            state.answered = true;
363            let answer = if state.in_call {
364                state.deferred = Some(Box::new(answer));
365                None
366            } else {
367                Some(answer)
368            };
369            (state.on_cancel.take(), answer)
370        };
371        drop(on_cancel);
372        if let Some(answer) = answer {
373            answer(&shared);
374        }
375        Ok(())
376    }
377}
378
379impl Drop for ResourceRequest {
380    fn drop(&mut self) {
381        if self.shared.is_some() {
382            let mut response = Response::new();
383            response.error =
384                Some(Box::new(ResourceError::new(Reason::Other, "resource request was released without a response")));
385            let _ = self.answer(move |target| target.respond(response));
386        }
387    }
388}
389
390impl std::fmt::Debug for ResourceRequest {
391    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
392        f.debug_struct("ResourceRequest")
393            .field("kind", &self.resource.kind)
394            .field("url", &self.resource.url)
395            .finish_non_exhaustive()
396    }
397}
398
399/// The headers that the library or the platform manages, which a header
400/// transform can't set.
401const MANAGED_HEADERS: [&str; 15] = [
402    "accept-encoding",
403    "connection",
404    "content-length",
405    "host",
406    "if-modified-since",
407    "if-none-match",
408    "keep-alive",
409    "proxy-authorization",
410    "proxy-connection",
411    "range",
412    "te",
413    "trailer",
414    "transfer-encoding",
415    "upgrade",
416    "user-agent",
417];
418
419/// Whether the library or the platform manages the HTTP header `name`, in
420/// any letter case, so that a header transform can't set it.
421#[must_use]
422pub fn is_managed_http_header(name: &str) -> bool {
423    MANAGED_HEADERS.iter().any(|managed| managed.eq_ignore_ascii_case(name))
424}
425
426/// `headers` without the ones the library manages, and with each name once:
427/// a later value replaces an earlier one, whatever the letter case.
428pub(crate) fn sanitize_headers(headers: HttpHeaders) -> HttpHeaders {
429    let mut sanitized: HttpHeaders = Vec::with_capacity(headers.len());
430    for (name, value) in headers {
431        if is_managed_http_header(&name) {
432            mln_util::logging::Log::warning(
433                mln_util::logging::Event::HttpRequest,
434                format!("a header transform can't set the managed header {name}"),
435            );
436            continue;
437        }
438        match sanitized.iter_mut().find(|(existing, _)| existing.eq_ignore_ascii_case(&name)) {
439            Some(existing) => existing.1 = value,
440            None => sanitized.push((name, value)),
441        }
442    }
443    sanitized
444}
445
446#[cfg(test)]
447mod tests {
448    use super::*;
449
450    #[test]
451    fn managed_and_repeated_headers_are_dropped() {
452        let headers = vec![
453            ("X-Token".to_owned(), "a".to_owned()),
454            ("Range".to_owned(), "bytes=0-1".to_owned()),
455            ("x-token".to_owned(), "b".to_owned()),
456            ("User-Agent".to_owned(), "me".to_owned()),
457        ];
458        assert_eq!(vec![("X-Token".to_owned(), "b".to_owned())], sanitize_headers(headers));
459    }
460}