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