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