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