Skip to main content

mln_engine/storage/
online_file_source.rs

1// The requests run in the online core (`OnlineCore`), which owns their state
2// and runs the tasks of its queue (`OnlineQueue`): an `OnlineRequest` per
3// caller request, started by a deadline (the first request at once, then
4// revalidation when a response that came fresh expires, or retries with
5// backoff after errors), queued while `maximum_concurrent_requests` transfers are active
6// (regular priority before low priority, and within a priority by the
7// resource's `RequestOrder`), and performed by the HTTPFileSource.
8// `requests` is keyed by id, so it iterates in id order.
9//
10// Requests whose transfers would be the same, of one URL, byte range and
11// validators, share one: a request due while that transfer is in flight, or
12// waiting for room when it starts, joins it, and each request takes its
13// response as its own. A shared transfer takes one place in the active set,
14// and is cancelled when the last of its requests is.
15//
16// The resource transform's answers and the transfers' responses come back
17// to the core as tasks, from whichever thread posts them, numbered with a
18// generation: an answer whose generation is no longer the one its request
19// waits for, or a response to a transfer no longer in flight, is dropped,
20// so a stale one can't end a transfer twice; they need the number because
21// they may already be on their way when the core moves on. A deadline is a timed task of the core's own
22// queue, which runs on the core's thread, so restarting or stopping a
23// request's deadline, or cancelling the request, cancels that task instead.
24//
25// The core runs on a thread of its own, except in the browser, where the
26// host's pump runs its queue (`OnlineFileSource::local`).
27
28use std::collections::VecDeque;
29use std::sync::Arc;
30#[cfg(test)]
31use std::sync::atomic::AtomicU32;
32use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
33use std::time::Duration;
34
35use mln_style::collections::VecMap;
36use mln_style::sort;
37use mln_style::time::Instant;
38#[cfg(not(target_family = "wasm"))]
39use parking_lot::Mutex;
40
41use crate::exec::queue::{Queue, TimedTask};
42use crate::log_target;
43use crate::storage::chrono::{Timestamp, now};
44use crate::storage::constants::{ASSET_PROTOCOL, DEFAULT_MAXIMUM_CONCURRENT_REQUESTS, FILE_PROTOCOL};
45use crate::storage::file_source::FileSource;
46use crate::storage::http_file_source::HTTPFileSource;
47use crate::storage::http_header_transform::HttpHeaderTransform;
48use crate::storage::http_timeout::{error_retry_timeout, until};
49use crate::storage::network_status::{NetworkStatus, Status, Subscription};
50use crate::storage::request::{Request, Responder};
51use crate::storage::resource::{Priority, RequestOrder, Resource};
52use crate::storage::resource_transform::{ResourceTransform, TransformResult};
53use crate::storage::response::{Reason, ResourceError, Response};
54
55/// The queue of an [`OnlineCore`], whose tasks run in the order they were
56/// posted. It stops once its source has dropped, and the queue's owner then
57/// closes it.
58pub(crate) type OnlineQueue = Queue<OnlineCore>;
59
60struct OnlineRequest {
61    resource: Resource,
62    responder: Responder,
63    /// The generation of the transfer in flight that it waits for.
64    transfer: Option<u64>,
65    /// The generation of the resource transform's answer it waits for.
66    transforming: Option<u64>,
67    /// The task of the deadline that starts it again, while one runs.
68    timer: Option<TimedTask>,
69
70    /// Counts the number of subsequent failed requests. We're using this
71    /// value for exponential backoff when retrying requests.
72    failed_requests: u32,
73    failed_request_reason: Reason,
74    retry_after: Option<Timestamp>,
75
76    /// Whether the resource transform failed the request. A retry calls the
77    /// transform again instead of loading the original URL.
78    transform_failed: bool,
79}
80
81/// A transfer in flight, for the requests that wait for it.
82struct Transfer {
83    /// Cancels the transfer when it drops.
84    _request: Request,
85    /// The requests that wait for it, in the order they joined. Never
86    /// empty, and none of their resources change while they wait, so any
87    /// one of them says what the transfer sends.
88    waiters: Vec<u64>,
89}
90
91/// Whether transfers of `a` and `b` would send the same, so that their
92/// requests can share one.
93fn same_transfer(a: &Resource, b: &Resource) -> bool {
94    a.kind == b.kind
95        && a.url == b.url
96        && a.data_range == b.data_range
97        && a.prior_etag == b.prior_etag
98        && a.prior_modified == b.prior_modified
99}
100
101/// What waiting requests start by, lowest first: regular priority before
102/// low priority, then the resource's [`RequestOrder`] as it is now.
103fn start_key(priority: Priority, order: &RequestOrder) -> (bool, u32) {
104    (priority == Priority::Low, order.get())
105}
106
107/// The requests waiting for room in the active set, in the order they
108/// started to wait.
109#[derive(Default)]
110struct PendingRequests {
111    requests: VecDeque<PendingRequest>,
112}
113
114struct PendingRequest {
115    id: u64,
116    priority: Priority,
117    order: RequestOrder,
118}
119
120impl PendingRequests {
121    fn remove(&mut self, id: u64) {
122        self.requests.retain(|request| request.id != id);
123    }
124
125    /// Removes the requests that `joins` picks, in the order they started
126    /// to wait.
127    fn take(&mut self, mut joins: impl FnMut(u64) -> bool) -> Vec<u64> {
128        let mut taken = Vec::new();
129        self.requests.retain(|request| {
130            let join = joins(request.id);
131            if join {
132                taken.push(request.id);
133            }
134            !join
135        });
136        taken
137    }
138
139    fn insert(&mut self, id: u64, resource: &Resource) {
140        self.requests.push_back(PendingRequest { id, priority: resource.priority, order: resource.order.clone() });
141    }
142
143    /// Removes the request to start next: the one with the lowest
144    /// [`start_key`], and of those the one that has waited longest. A
145    /// request's order may change while it waits, so every call reads them
146    /// all.
147    fn pop(&mut self) -> Option<u64> {
148        // `min_by_key` returns the first of equal elements.
149        let (index, _) =
150            self.requests.iter().enumerate().min_by_key(|(_, request)| start_key(request.priority, &request.order))?;
151        self.requests.remove(index).map(|request| request.id)
152    }
153
154    fn contains(&self, id: u64) -> bool {
155        self.requests.iter().any(|request| request.id == id)
156    }
157}
158
159/// The URL without its query string.
160fn sanitize_url(url: &str) -> &str {
161    match url.find('?') {
162        Some(query_index) => &url[..query_index],
163        None => url,
164    }
165}
166
167impl OnlineRequest {
168    /// When to request the resource again after a response: after an error,
169    /// its retry's backoff; else when the data expires, if it came fresh. A
170    /// response that came stale, as one without a freshness lifetime,
171    /// isn't asked for again until it is requested anew.
172    fn update_interval(&self, response: &Response) -> Option<Duration> {
173        let now = now();
174        if response.error.is_some() {
175            return error_retry_timeout(self.failed_request_reason, self.failed_requests, self.retry_after, now);
176        }
177        response
178            .caching
179            .expires
180            .filter(|&expires| expires > now)
181            .map(|expires| until(expires, now).max(self.resource.minimum_update_interval))
182    }
183}
184
185/// The state of an [`OnlineFileSource`]'s requests, which the tasks of its
186/// [`OnlineQueue`] change on the thread that owns it.
187#[cfg_attr(
188    not(target_family = "wasm"),
189    expect(unreachable_pub, reason = "only the browser build's `OnlineFileSource::local` hands it out")
190)]
191pub struct OnlineCore {
192    /// For the transform's answers, the transfers' responses and the
193    /// deadlines.
194    queue: OnlineQueue,
195    /// The lifetime of a request is:
196    ///
197    /// 1. Waiting for its deadline (revalidation or retry)
198    /// 2. Pending (waiting for room in the active set)
199    /// 3. Active (waiting for a transfer in flight, maybe shared)
200    /// 4. Back to #1
201    ///
202    /// Requests in any state are in `requests`. Requests in the pending
203    /// state are in `pending_requests`. The transfers of requests in the
204    /// active state are in `transfers`, by their generation: the active set.
205    requests: VecMap<u64, OnlineRequest>,
206    pending_requests: PendingRequests,
207    transfers: VecMap<u64, Transfer>,
208    /// The last generation handed out.
209    generation: u64,
210
211    online: bool,
212    maximum_concurrent_requests: u32,
213    http_file_source: HTTPFileSource,
214    resource_transform: Option<ResourceTransform>,
215    network: Arc<NetworkStatus>,
216    /// A task that tells the core the network is reachable again is on its
217    /// way.
218    reachable: Arc<AtomicBool>,
219    /// The clock that the deadlines go by, in place of the system's
220    /// (`crate::storage::simulated_network`).
221    #[cfg(all(any(test, feature = "bench"), not(target_family = "wasm")))]
222    clock: Option<crate::storage::simulated_network::Clock>,
223}
224
225impl OnlineCore {
226    fn next_generation(&mut self) -> u64 {
227        self.generation += 1;
228        self.generation
229    }
230
231    /// The resource transform's answer for request `id`, which it takes
232    /// unless it no longer waits for answer `generation`.
233    fn transformed(&mut self, id: u64, generation: u64, result: TransformResult) {
234        if self.requests.get(&id).is_some_and(|req| req.transforming == Some(generation)) {
235            self.set_transform_result(id, result);
236        }
237    }
238
239    /// Transfer `generation`'s response, which goes to each request that
240    /// waits for it, unless the transfer is no longer in flight. Starts the
241    /// pending requests that the room it leaves allows.
242    fn transferred(&mut self, generation: u64, response: &Response) {
243        let Some(transfer) = self.transfers.remove(&generation) else { return };
244        for id in transfer.waiters {
245            if let Some(req) = self.requests.get_mut(&id) {
246                req.transfer = None;
247                self.completed(id, response.clone());
248            }
249        }
250        self.activate_pending_requests();
251    }
252
253    /// Starts request `id` again: what its deadline's task does. Cancelling
254    /// or replacing the request's deadline cancels that task, so it runs
255    /// only for the deadline that the request waits for.
256    fn deadline_passed(&mut self, id: u64) {
257        let Some(req) = self.requests.get_mut(&id) else { return };
258        req.timer = None;
259        if req.transform_failed {
260            self.transform(id);
261        } else {
262            self.activate_or_queue_request(id);
263        }
264    }
265
266    fn request(&mut self, id: u64, resource: Resource, responder: Responder) {
267        // A request cancelled before this ran had its cancel run first,
268        // which found nothing to cancel.
269        if responder.is_cancelled() {
270            return;
271        }
272        self.requests.insert(
273            id,
274            OnlineRequest {
275                resource,
276                responder,
277                transfer: None,
278                transforming: None,
279                timer: None,
280                failed_requests: 0,
281                failed_request_reason: Reason::Success,
282                retry_after: None,
283                transform_failed: false,
284            },
285        );
286        self.transform(id);
287    }
288
289    fn transform(&mut self, id: u64) {
290        let generation = self.next_generation();
291        let transform = self.resource_transform.clone();
292        let Some(req) = self.requests.get_mut(&id) else { return };
293        req.transform_failed = false;
294        let Some(transform) = transform else {
295            self.activate(id);
296            return;
297        };
298        // Ask the resource transform for a new URL, and replace the
299        // resource's URL with the transformed one before scheduling the
300        // request.
301        req.transforming = Some(generation);
302        let (kind, url) = (req.resource.kind, req.resource.url.clone());
303        let queue = self.queue.clone();
304        transform(
305            kind,
306            &url,
307            Box::new(move |result: TransformResult| {
308                queue.post(move |core| core.transformed(id, generation, result));
309            }),
310        );
311    }
312
313    fn set_transform_result(&mut self, id: u64, result: TransformResult) {
314        let Some(req) = self.requests.get_mut(&id) else { return };
315        req.transforming = None;
316        match result {
317            Ok(url) => {
318                req.resource.url = url;
319                self.activate(id);
320            }
321            Err(error) => {
322                req.transform_failed = true;
323                let mut response = Response::new();
324                response.error = Some(Box::new(error));
325                self.completed(id, response);
326            }
327        }
328    }
329
330    fn cancel(&mut self, id: u64) {
331        self.pending_requests.remove(id);
332        let Some(req) = self.requests.remove(&id) else { return };
333        if let Some(timer) = req.timer {
334            self.queue.cancel(timer);
335        }
336        // The transfer goes on while another request waits for it.
337        if let Some(generation) = req.transfer
338            && let Some(transfer) = self.transfers.get_mut(&generation)
339        {
340            transfer.waiters.retain(|&waiter| waiter != id);
341            if transfer.waiters.is_empty() {
342                self.transfers.remove(&generation);
343                self.activate_pending_requests();
344            }
345        }
346    }
347
348    /// Starts request `id`: it joins the transfer in flight that it shares,
349    /// or starts its own if the active set has room, or waits for room.
350    fn activate_or_queue_request(&mut self, id: u64) {
351        let Some(req) = self.requests.get(&id) else { return };
352        debug_assert!(req.transfer.is_none());
353        let requests = &self.requests;
354        let shared = self
355            .transfers
356            .iter()
357            .find(|(_, transfer)| {
358                transfer
359                    .waiters
360                    .first()
361                    .and_then(|waiter| requests.get(waiter))
362                    .is_some_and(|waiter| same_transfer(&waiter.resource, &req.resource))
363            })
364            .map(|(&generation, _)| generation);
365        if let Some(generation) = shared {
366            if let Some(transfer) = self.transfers.get_mut(&generation) {
367                transfer.waiters.push(id);
368            }
369            if let Some(req) = self.requests.get_mut(&id) {
370                req.transfer = Some(generation);
371            }
372        } else if self.transfers.len() >= self.maximum_concurrent_requests as usize {
373            self.pending_requests.insert(id, &req.resource);
374        } else {
375            self.activate_request(id);
376        }
377    }
378
379    /// Starts request `id`'s transfer, which the pending requests that
380    /// share it join.
381    fn activate_request(&mut self, id: u64) {
382        if !self.online {
383            let mut response = Response::new();
384            response.error = Some(Box::new(ResourceError::new(Reason::Connection, "Online connectivity is disabled.")));
385            self.completed(id, response);
386            return;
387        }
388        let generation = self.next_generation();
389        let queue = self.queue.clone();
390        let Some(req) = self.requests.get_mut(&id) else { return };
391        let (request, responder) = Request::new(move |response: Response| {
392            queue.post(move |core| core.transferred(generation, &response));
393        });
394        req.transfer = Some(generation);
395        self.http_file_source.start(&req.resource, responder);
396        let requests = &self.requests;
397        let resource = &requests[&id].resource;
398        let joined = self
399            .pending_requests
400            .take(|pending| requests.get(&pending).is_some_and(|pending| same_transfer(&pending.resource, resource)));
401        for &pending in &joined {
402            if let Some(req) = self.requests.get_mut(&pending) {
403                req.transfer = Some(generation);
404            }
405        }
406        let mut waiters = vec![id];
407        waiters.extend(joined);
408        self.transfers.insert(generation, Transfer { _request: request, waiters });
409    }
410
411    /// Starts pending requests while the active set has room.
412    fn activate_pending_requests(&mut self) {
413        while self.transfers.len() < self.maximum_concurrent_requests as usize
414            && let Some(id) = self.pending_requests.pop()
415        {
416            if self.requests.contains_key(&id) {
417                self.activate_request(id);
418            }
419        }
420    }
421
422    fn network_is_reachable_again(&mut self) {
423        let mut ids: Vec<u64> = self.requests.keys().copied().collect();
424        // Notify the requests in the order they would start in.
425        sort::sort_by_key(&mut ids, |id| {
426            let resource = &self.requests[id].resource;
427            start_key(resource.priority, &resource.order)
428        });
429        for id in ids {
430            // We need all requests to fail at least once before we are
431            // going to start retrying them, and we only immediately restart
432            // request that failed due to connection issues.
433            if self.requests.get(&id).is_some_and(|req| req.failed_request_reason == Reason::Connection) {
434                self.schedule(id, Some(Duration::ZERO));
435            }
436        }
437    }
438
439    fn activate(&mut self, id: u64) {
440        // With the network forced offline, a request starts again once the
441        // network is back. A requester that shows no copy of the resource
442        // hears at once that it failed to connect; one that does keeps it
443        // meanwhile.
444        if self.network.get() == Status::Offline {
445            let Some(req) = self.requests.get_mut(&id) else { return };
446            req.failed_request_reason = Reason::Connection;
447            req.failed_requests = 1;
448            let resource = &req.resource;
449            let has_copy = resource.prior_data.is_none()
450                && (resource.prior_caching.expires.is_some()
451                    || resource.prior_etag.is_some()
452                    || resource.prior_modified.is_some());
453            if !has_copy {
454                let mut error = Response::new();
455                error.error =
456                    Some(Box::new(ResourceError::new(Reason::Connection, "Online connectivity is disabled.")));
457                req.responder.send(error);
458            }
459            return;
460        }
461        let Some(req) = self.requests.get(&id) else { return };
462        // A copy that is still fresh is revalidated once it expires, and not
463        // before the resource's minimum update interval; anything else at once.
464        let timeout = match req.resource.prior_caching.expires {
465            Some(prior_expires) => until(prior_expires, now()).max(req.resource.minimum_update_interval),
466            None => Duration::ZERO,
467        };
468        self.schedule(id, Some(timeout));
469    }
470
471    /// Requests the resource again after `timeout`, or never for `None`.
472    fn schedule(&mut self, id: u64, timeout: Option<Duration>) {
473        // The time that deadlines go by.
474        #[cfg(all(any(test, feature = "bench"), not(target_family = "wasm")))]
475        let now = self.clock.as_ref().map_or_else(Instant::now, |clock| clock());
476        #[cfg(not(all(any(test, feature = "bench"), not(target_family = "wasm"))))]
477        let now = Instant::now();
478        let pending = self.pending_requests.contains(id);
479        let offline = self.network.get() == Status::Offline;
480        let Some(req) = self.requests.get_mut(&id) else { return };
481        if req.transforming.is_some() || pending || req.transfer.is_some() {
482            // There's already a request in progress; don't start another one.
483            return;
484        }
485
486        let Some(timeout) = timeout else {
487            return;
488        };
489
490        if let Some(timer) = req.timer.take() {
491            self.queue.cancel(timer);
492        }
493
494        // Emulate a Connection error when the Offline mode is forced, and
495        // don't retry: the request will get re-triggered when the
496        // NetworkStatus is set back to Online.
497        if offline {
498            req.failed_request_reason = Reason::Connection;
499            req.failed_requests = 1;
500            return;
501        }
502
503        // A deadline past what `Instant` can hold never comes.
504        if let Some(due) = now.checked_add(timeout) {
505            req.timer = Some(self.queue.post_at(due, move |core| core.deadline_passed(id)));
506        }
507    }
508
509    fn completed(&mut self, id: u64, response: Response) {
510        let Some(req) = self.requests.get_mut(&id) else { return };
511        if let Some(error) = &response.error {
512            if error.reason == Reason::NotFound {
513                tracing::error!(
514                    target: log_target::GENERAL,
515                    url = %sanitize_url(&req.resource.url),
516                    "The resource wasn't found"
517                );
518            }
519            req.failed_requests += 1;
520            req.failed_request_reason = error.reason;
521            req.retry_after = error.retry_after;
522        } else {
523            req.failed_requests = 0;
524            req.failed_request_reason = Reason::Success;
525        }
526        // After an error, the request retries, even while the requester
527        // shows a stale copy.
528        let interval = req.update_interval(&response);
529
530        let resource = &mut req.resource;
531        let response = resource.deliver(response);
532        if response.error.is_none() {
533            // The next revalidation is of this copy.
534            resource.set_prior(&response);
535        }
536
537        self.schedule(id, interval);
538
539        if let Some(req) = self.requests.get(&id) {
540            req.responder.send(response);
541        }
542    }
543}
544
545/// The `Network` file source: HTTP(S) requests, revalidated when they
546/// expire and retried with a backoff after errors, with a bounded number of
547/// transfers in flight. Requests that would send the same transfer at once
548/// share it. Its requests follow the [`NetworkStatus`] it was made with.
549///
550/// Outside the browser its requests run on a thread of its own, which its
551/// drop or [`shut_down`](Self::shut_down) waits for, unless it runs on that
552/// thread. When that thread can't start, the source logs why and fails each
553/// request.
554pub struct OnlineFileSource {
555    #[cfg(test)]
556    maximum_concurrent_requests: AtomicU32,
557    /// The id of the next request.
558    next_request_id: AtomicU64,
559    queue: OnlineQueue,
560    _reachability: Subscription,
561    /// The thread that runs the core, until the source shuts down.
562    #[cfg(not(target_family = "wasm"))]
563    thread: Mutex<Option<std::thread::JoinHandle<()>>>,
564    /// The caller runs the core, rather than a thread
565    /// (`crate::storage::simulated_network`).
566    #[cfg(all(any(test, feature = "bench"), not(target_family = "wasm")))]
567    driven: bool,
568}
569
570#[cfg(target_family = "wasm")]
571impl OnlineCore {
572    /// Sets where the browser's fetch looks for a response that the host
573    /// fetched ahead before it fetches a whole resource: `take(url)`
574    /// returns a promise of the `Response` fetched for exactly `url`, at
575    /// most once for each, or undefined. A promise that rejects is fetched
576    /// again. `None` stops looking.
577    pub fn set_fetch_preloads(&mut self, take: Option<js_sys::Function>) {
578        self.http_file_source.set_fetch_preloads(take);
579    }
580}
581
582impl OnlineFileSource {
583    /// A source whose requests run on a thread of its own and follow
584    /// `network`.
585    #[cfg(not(target_family = "wasm"))]
586    #[must_use]
587    pub fn new(network: Arc<NetworkStatus>) -> Self {
588        let (mut source, core) = Self::with_core(network);
589        let queue = source.queue.clone();
590        // The core, and its HTTP client, are made on the thread.
591        let thread = crate::exec::thread::spawn("OnlineFileSource", move || {
592            let mut core = core();
593            queue.run(&mut core);
594            // What comes once the source has dropped, such as a transfer's
595            // late response, drops at once.
596            queue.close();
597            drop(core);
598        });
599        match thread {
600            Ok(thread) => *source.thread.get_mut() = Some(thread),
601            Err(error) => {
602                source.queue.close();
603                tracing::error!(target: log_target::GENERAL, error = %error, "The online file source's thread didn't start");
604            }
605        }
606        source
607    }
608
609    /// A source whose requests follow `network` and run in the returned
610    /// core, with the returned queue, which the caller runs on this thread
611    /// with [`Queue::run_once`] until the queue
612    /// [`is_stopped`](Queue::is_stopped), then closes. The queue's waker
613    /// tells the caller when it has tasks, and its
614    /// [`next_deadline`](Queue::next_deadline) when a retry or a
615    /// revalidation is due.
616    #[cfg(target_family = "wasm")]
617    #[must_use]
618    pub fn local(network: Arc<NetworkStatus>) -> (Self, OnlineQueue, OnlineCore) {
619        let (source, core) = Self::with_core(network);
620        let queue = source.queue.clone();
621        (source, queue, core())
622    }
623
624    /// The source, and what makes its core.
625    fn with_core(network: Arc<NetworkStatus>) -> (Self, impl FnOnce() -> OnlineCore + Send + 'static) {
626        let queue = OnlineQueue::new();
627        let reachable = Arc::new(AtomicBool::new(false));
628        let reachability = {
629            let (queue, reachable) = (queue.clone(), Arc::clone(&reachable));
630            network.subscribe(move || {
631                if !reachable.swap(true, Ordering::SeqCst) {
632                    queue.post(|core| {
633                        core.reachable.store(false, Ordering::SeqCst);
634                        core.network_is_reachable_again();
635                    });
636                }
637            })
638        };
639        let core_queue = queue.clone();
640        let core = move || OnlineCore {
641            queue: core_queue,
642            requests: VecMap::new(),
643            pending_requests: PendingRequests::default(),
644            transfers: VecMap::new(),
645            generation: 0,
646            online: true,
647            maximum_concurrent_requests: DEFAULT_MAXIMUM_CONCURRENT_REQUESTS,
648            http_file_source: HTTPFileSource::new(),
649            resource_transform: None,
650            network,
651            reachable,
652            #[cfg(all(any(test, feature = "bench"), not(target_family = "wasm")))]
653            clock: None,
654        };
655        let source = OnlineFileSource {
656            #[cfg(test)]
657            maximum_concurrent_requests: AtomicU32::new(DEFAULT_MAXIMUM_CONCURRENT_REQUESTS),
658            next_request_id: AtomicU64::new(1),
659            queue,
660            _reachability: reachability,
661            #[cfg(not(target_family = "wasm"))]
662            thread: Mutex::new(None),
663            #[cfg(all(any(test, feature = "bench"), not(target_family = "wasm")))]
664            driven: false,
665        };
666        (source, core)
667    }
668
669    /// A source whose core the caller runs on its own thread, as
670    /// [`local`](Self::local)'s, whose transfers go to `transport` and
671    /// whose deadlines go by `clock` (`crate::storage::simulated_network`).
672    #[cfg(all(any(test, feature = "bench"), not(target_family = "wasm")))]
673    pub(crate) fn driven(
674        network: Arc<NetworkStatus>,
675        transport: Arc<dyn crate::storage::http_file_source::HttpTransport>,
676        clock: crate::storage::simulated_network::Clock,
677    ) -> (Self, OnlineQueue, OnlineCore) {
678        let (mut source, core) = Self::with_core(network);
679        source.driven = true;
680        let mut core = core();
681        core.http_file_source = HTTPFileSource::with_transport(transport);
682        core.clock = Some(clock);
683        let queue = source.queue.clone();
684        (source, queue, core)
685    }
686
687    /// Sets the most transfers in flight at once.
688    #[cfg(test)]
689    pub(crate) fn set_maximum_concurrent_requests(&self, maximum: u32) {
690        self.maximum_concurrent_requests.store(maximum, Ordering::Relaxed);
691        self.queue.post(move |core| core.maximum_concurrent_requests = maximum);
692    }
693
694    /// Rewrites the URLs of requests before they load, or stops rewriting
695    /// them for `None`.
696    pub fn set_resource_transform(&self, transform: Option<ResourceTransform>) {
697        self.queue.post(move |core| core.resource_transform = transform);
698    }
699
700    /// Sets the headers to add to each transfer.
701    pub fn set_http_header_transform(&self, transform: HttpHeaderTransform) {
702        self.queue.post(move |core| core.http_file_source.set_http_header_transform(transform));
703    }
704
705    /// Whether a thread, or the caller, runs the source's core.
706    #[cfg(not(target_family = "wasm"))]
707    fn is_running(&self) -> bool {
708        #[cfg(all(any(test, feature = "bench"), not(target_family = "wasm")))]
709        if self.driven {
710            return true;
711        }
712        self.thread.lock().is_some()
713    }
714
715    /// Whether a thread runs the source's core: in the browser the host's
716    /// does.
717    #[cfg(target_family = "wasm")]
718    #[expect(clippy::unused_self, reason = "the threads of other builds can fail to start")]
719    fn is_running(&self) -> bool {
720        true
721    }
722
723    /// Stops the source, as its drop does, for an owner that must know its
724    /// thread has ended although the source may be held elsewhere. The first
725    /// call waits for that thread, unless it runs on it; a later call
726    /// returns at once, so one owner shuts it down. Requests in flight end
727    /// without a response, and later ones fail as when the thread didn't
728    /// start.
729    pub fn shut_down(&self) {
730        self.queue.stop();
731        #[cfg(not(target_family = "wasm"))]
732        {
733            // Released before the join, as the thread may load from this
734            // source meanwhile.
735            let thread = self.thread.lock().take();
736            if let Some(thread) = thread
737                && thread.thread().id() != std::thread::current().id()
738            {
739                let _ = thread.join();
740            }
741        }
742    }
743}
744
745impl Drop for OnlineFileSource {
746    fn drop(&mut self) {
747        self.shut_down();
748    }
749}
750
751impl FileSource for OnlineFileSource {
752    fn load(&self, resource: &Resource, responder: Responder) {
753        if !self.is_running() {
754            let mut response = Response::new();
755            response.error =
756                Some(Box::new(ResourceError::new(Reason::Other, "The online file source's thread isn't running.")));
757            responder.send(response);
758            return;
759        }
760        let id = self.next_request_id.fetch_add(1, Ordering::Relaxed);
761        let queue = self.queue.clone();
762        responder.on_cancel(move || queue.post(move |core| core.cancel(id)));
763        let resource = resource.clone();
764        self.queue.post(move |core| core.request(id, resource, responder));
765    }
766
767    fn can_request(&self, resource: &Resource) -> bool {
768        resource.has_loading_method(crate::storage::resource::LoadingMethod::NETWORK)
769            && !resource.url.starts_with(ASSET_PROTOCOL)
770            && !resource.url.starts_with(FILE_PROTOCOL)
771    }
772}
773
774#[cfg(test)]
775mod tests {
776    use std::sync::mpsc;
777
778    use super::*;
779    use crate::storage::http_file_source::{HttpTransport, TransferRequest};
780    use crate::storage::resource::Kind;
781    use crate::storage::resource_transform::FinishedCallback;
782
783    /// Keeps each transfer in flight, unanswered.
784    #[derive(Default)]
785    struct Unanswered(Mutex<Vec<TransferRequest>>);
786
787    impl HttpTransport for Unanswered {
788        fn start(&self, request: TransferRequest) {
789            self.0.lock().push(request);
790        }
791    }
792
793    /// A core that no thread runs, whose tasks the test runs or calls
794    /// itself, whose transfers stay in flight, and the source whose drop
795    /// ends it.
796    fn core(maximum: u32) -> (OnlineFileSource, OnlineCore) {
797        let (source, core) = OnlineFileSource::with_core(Arc::new(NetworkStatus::new()));
798        let mut core = core();
799        core.http_file_source = HTTPFileSource::with_transport(Arc::new(Unanswered::default()));
800        core.maximum_concurrent_requests = maximum;
801        (source, core)
802    }
803
804    /// The URL of `path` on a server that never answers.
805    fn url(path: &str) -> String {
806        format!("http://example.invalid{path}")
807    }
808
809    fn request(core: &mut OnlineCore, id: u64, url: &str) -> Request {
810        let (request, responder) = Request::new(|_| {});
811        core.request(id, Resource::new(Kind::Unknown, url), responder);
812        request
813    }
814
815    /// Passes request `id`'s deadline, as the queue does once it's due: it
816    /// takes the deadline's task and runs it. The test calls this rather
817    /// than running the queue, which would also run the responses of the
818    /// transfers that it starts.
819    fn pass_deadline(core: &mut OnlineCore, id: u64) {
820        let timer = core.requests[&id].timer.expect("a deadline");
821        core.queue.cancel(timer);
822        core.deadline_passed(id);
823    }
824
825    /// The generation of request `id`'s transfer in flight.
826    fn transfer(core: &OnlineCore, id: u64) -> Option<u64> {
827        core.requests[&id].transfer
828    }
829
830    /// A response to a transfer that ended, or that never was, ends
831    /// nothing: it neither starts a waiting request twice nor starts one
832    /// beyond the maximum.
833    #[test]
834    fn a_stale_transfer_response_is_dropped() {
835        let (_source, mut core) = core(1);
836        let _first = request(&mut core, 1, &url("/stale-1"));
837        let _second = request(&mut core, 2, &url("/stale-2"));
838        pass_deadline(&mut core, 1);
839        pass_deadline(&mut core, 2);
840        let first = transfer(&core, 1).expect("the first request's transfer");
841        assert!(core.pending_requests.contains(2));
842
843        core.transferred(first + 1000, &Response::new());
844        assert_eq!(Some(first), transfer(&core, 1));
845        assert!(core.pending_requests.contains(2));
846
847        core.transferred(first, &Response::new());
848        assert_eq!(None, transfer(&core, 1));
849        let second = transfer(&core, 2).expect("the second request's transfer");
850        assert_eq!(1, core.transfers.len());
851
852        core.transferred(first, &Response::new());
853        assert_eq!(Some(second), transfer(&core, 2));
854        assert_eq!(1, core.transfers.len());
855        assert!(!core.pending_requests.contains(2));
856    }
857
858    /// A request whose answers the test counts.
859    fn counted(core: &mut OnlineCore, id: u64, resource: Resource) -> (Request, Arc<AtomicU32>) {
860        let answers = Arc::new(AtomicU32::new(0));
861        let counted = Arc::clone(&answers);
862        let (request, responder) = Request::new(move |_| {
863            counted.fetch_add(1, Ordering::SeqCst);
864        });
865        core.request(id, resource, responder);
866        (request, answers)
867    }
868
869    fn tile(url: &str) -> Resource {
870        Resource::new(Kind::Tile, url)
871    }
872
873    fn data() -> Response {
874        let mut response = Response::new();
875        response.data = Some(Arc::new(b"tile".to_vec()));
876        response
877    }
878
879    /// A shared transfer goes on while a request waits for it, and stops
880    /// with the last.
881    #[test]
882    fn a_shared_transfer_stops_with_its_last_request() {
883        let (_source, mut core) = core(2);
884        let url = url("/shared");
885        let (_first, _) = counted(&mut core, 1, tile(&url));
886        let (_second, second) = counted(&mut core, 2, tile(&url));
887        pass_deadline(&mut core, 1);
888        pass_deadline(&mut core, 2);
889        let generation = transfer(&core, 1).expect("the transfer");
890
891        core.cancel(1);
892        assert!(core.transfers.contains_key(&generation));
893        core.cancel(2);
894        assert!(core.transfers.is_empty());
895        core.transferred(generation, &data());
896        assert_eq!(0, second.load(Ordering::SeqCst));
897    }
898
899    /// Requests that wait for room join the transfer they share when it
900    /// starts, rather than starting another after it.
901    #[test]
902    fn waiting_requests_join_the_transfer_they_share_when_it_starts() {
903        let (_source, mut core) = core(1);
904        let (_other, _) = counted(&mut core, 1, tile(&url("/other")));
905        let shared = url("/shared");
906        let (_first, first) = counted(&mut core, 2, tile(&shared));
907        let (_second, second) = counted(&mut core, 3, tile(&shared));
908        for id in 1..=3 {
909            pass_deadline(&mut core, id);
910        }
911        let other = transfer(&core, 1).expect("the first transfer");
912        assert!(core.pending_requests.contains(2) && core.pending_requests.contains(3));
913
914        core.transferred(other, &data());
915        let generation = transfer(&core, 2).expect("the shared transfer");
916        assert_eq!(Some(generation), transfer(&core, 3));
917        assert!(!core.pending_requests.contains(3));
918        core.transferred(generation, &data());
919        assert_eq!((1, 1), (first.load(Ordering::SeqCst), second.load(Ordering::SeqCst)));
920    }
921
922    /// Requests that would send different validators, or ask for different
923    /// bytes, don't share a transfer.
924    #[test]
925    fn requests_of_other_validators_or_bytes_transfer_apart() {
926        let (_source, mut core) = core(4);
927        let url = url("/apart");
928        let mut validated = tile(&url);
929        validated.prior_etag = Some("\"v1\"".to_owned());
930        let mut ranged = tile(&url);
931        ranged.data_range = Some((0, 99));
932        let _requests =
933            [counted(&mut core, 1, tile(&url)), counted(&mut core, 2, validated), counted(&mut core, 3, ranged)];
934        for id in 1..=3 {
935            pass_deadline(&mut core, id);
936        }
937        assert_eq!(3, core.transfers.len());
938    }
939
940    /// An answer of the resource transform that the request no longer waits
941    /// for changes nothing.
942    #[test]
943    fn a_stale_transform_answer_is_dropped() {
944        let (_source, mut core) = core(1);
945        let answers: Arc<Mutex<Vec<FinishedCallback>>> = Arc::default();
946        let saved = Arc::clone(&answers);
947        core.resource_transform = Some(Arc::new(move |_, _: &str, finished| saved.lock().push(finished)));
948        let original = "http://example.invalid/original";
949        let _request = request(&mut core, 1, original);
950        let generation = core.requests[&1].transforming.expect("a transform");
951
952        core.transformed(1, generation - 1, Ok("stale".to_owned()));
953        assert_eq!(Some(generation), core.requests[&1].transforming);
954        assert_eq!(original, core.requests[&1].resource.url);
955
956        let url = url("/transformed");
957        let finished = answers.lock().pop().expect("the transform's callback");
958        finished(Ok(url.clone()));
959        let queue = core.queue.clone();
960        assert!(queue.run_once(&mut core), "the transform's answer");
961        assert_eq!(None, core.requests[&1].transforming);
962        assert_eq!(url, core.requests[&1].resource.url);
963    }
964
965    /// A response that expires, for a resource whose minimum update
966    /// interval is longer than `Instant` can count, schedules no update.
967    #[test]
968    fn an_update_interval_past_instants_range_never_fires() {
969        let (_source, mut core) = core(1);
970        let mut resource = Resource::new(Kind::Tile, url("/forever"));
971        resource.minimum_update_interval = Duration::MAX;
972        let (_request, responder) = Request::new(|_| {});
973        core.request(1, resource, responder);
974        pass_deadline(&mut core, 1);
975        let generation = transfer(&core, 1).expect("the request's transfer");
976
977        let mut response = Response::new();
978        response.data = Some(Arc::new(b"tile".to_vec()));
979        response.caching.expires = Some(Timestamp::from_secs(now().secs_since_epoch() + 60));
980        core.transferred(generation, &response);
981        assert_eq!(None, core.requests[&1].timer);
982        assert_eq!(None, core.queue.next_deadline());
983    }
984
985    /// Replacing a request's deadline, or cancelling the request, cancels
986    /// the deadline's task, which leaves the queue.
987    #[test]
988    fn a_replaced_or_cancelled_deadline_leaves_the_queue() {
989        let (_source, mut core) = core(1);
990        let _request = request(&mut core, 1, &url("/retry"));
991        pass_deadline(&mut core, 1);
992        let generation = transfer(&core, 1).expect("the request's transfer");
993        let mut response = Response::new();
994        response.error = Some(Box::new(ResourceError::new(Reason::Connection, "refused")));
995        core.transferred(generation, &response);
996        let retry = core.queue.next_deadline().expect("the retry, after its backoff");
997
998        core.network_is_reachable_again();
999        let again = core.queue.next_deadline().expect("the retry, at once");
1000        assert!(again < retry);
1001
1002        core.cancel(1);
1003        assert_eq!(None, core.queue.next_deadline());
1004    }
1005
1006    /// The last owner of a source may drop it on the source's own thread.
1007    #[test]
1008    fn a_source_dropped_on_its_own_thread_ends() {
1009        let source = OnlineFileSource::new(Arc::new(NetworkStatus::new()));
1010        let queue = source.queue.clone();
1011        let (dropped, done) = mpsc::channel();
1012        queue.post(move |_| {
1013            drop(source);
1014            dropped.send(()).unwrap();
1015        });
1016        done.recv().expect("the drop returns");
1017    }
1018
1019    fn resource(priority: Priority, order: u32) -> Resource {
1020        let mut resource = Resource::new(Kind::Tile, "");
1021        resource.set_priority(priority);
1022        resource.order.set(order);
1023        resource
1024    }
1025
1026    fn drain(pending: &mut PendingRequests) -> Vec<u64> {
1027        std::iter::from_fn(|| pending.pop()).collect()
1028    }
1029
1030    /// Waiting requests start by priority, then by order, those without
1031    /// one first, as styles, sources, sprites and glyphs leave it, then by
1032    /// arrival; one removed doesn't start.
1033    #[test]
1034    fn pending_requests_start_by_priority_then_order_then_arrival() {
1035        let unordered = || Resource::new(Kind::Glyphs, "");
1036        let cases = [
1037            (vec![(3, unordered()), (1, unordered()), (2, unordered())], vec![], vec![3, 1, 2]),
1038            (
1039                vec![
1040                    (1, resource(Priority::Low, 0)),
1041                    (2, resource(Priority::Regular, 7)),
1042                    (3, resource(Priority::Regular, 5)),
1043                    (4, resource(Priority::Low, 9)),
1044                    (5, resource(Priority::Regular, 7)),
1045                    (6, resource(Priority::Low, 0)),
1046                ],
1047                vec![],
1048                vec![3, 2, 5, 1, 6, 4],
1049            ),
1050            (
1051                vec![
1052                    (1, resource(Priority::Regular, 999)),
1053                    (2, resource(Priority::Regular, 998)),
1054                    (3, unordered()),
1055                    (4, unordered()),
1056                ],
1057                vec![],
1058                vec![3, 4, 2, 1],
1059            ),
1060            (
1061                vec![
1062                    (1, resource(Priority::Regular, 2)),
1063                    (2, resource(Priority::Regular, 1)),
1064                    (3, resource(Priority::Regular, 3)),
1065                ],
1066                vec![2],
1067                vec![1, 3],
1068            ),
1069        ];
1070        for (inserted, removed, expected) in cases {
1071            let mut pending = PendingRequests::default();
1072            for (id, resource) in &inserted {
1073                pending.insert(*id, resource);
1074            }
1075            for id in &removed {
1076                assert!(pending.contains(*id));
1077                pending.remove(*id);
1078                assert!(!pending.contains(*id));
1079            }
1080            assert_eq!(expected, drain(&mut pending));
1081        }
1082    }
1083
1084    /// A requester changes a waiting request's order through the resource it
1085    /// kept, a clone of the one it requested with.
1086    #[test]
1087    fn pending_request_moves_when_its_order_changes() {
1088        let mut pending = PendingRequests::default();
1089        let resources =
1090            [resource(Priority::Regular, 1), resource(Priority::Regular, 2), resource(Priority::Regular, 3)];
1091        for (id, resource) in (1..).zip(&resources) {
1092            pending.insert(id, &resource.clone());
1093        }
1094
1095        resources[2].order.set(0);
1096        assert_eq!(pending.pop(), Some(3));
1097
1098        resources[0].order.set(u32::MAX);
1099        assert_eq!(drain(&mut pending), [2, 1]);
1100    }
1101
1102    /// A low priority request stays behind every regular one, whatever its
1103    /// order.
1104    #[test]
1105    fn pending_order_does_not_cross_priorities() {
1106        let mut pending = PendingRequests::default();
1107        let low = resource(Priority::Low, 5);
1108        pending.insert(1, &low);
1109        pending.insert(2, &resource(Priority::Regular, u32::MAX));
1110        low.order.set(0);
1111        assert_eq!(drain(&mut pending), [2, 1]);
1112    }
1113}