script/
document_loader.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Tracking of pending loads in a document.
6//!
7//! <https://html.spec.whatwg.org/multipage/#the-end>
8
9use net_traits::request::RequestBuilder;
10use net_traits::{BoxedFetchCallback, ResourceThreads, fetch_async};
11use servo_url::ServoUrl;
12
13use crate::dom::bindings::cell::DomRefCell;
14use crate::dom::bindings::root::Dom;
15use crate::dom::document::Document;
16use crate::fetch::FetchCanceller;
17use crate::script_runtime::CanGc;
18
19#[derive(Clone, Debug, JSTraceable, MallocSizeOf, PartialEq)]
20pub(crate) enum LoadType {
21    Image(#[no_trace] ServoUrl),
22    Script(#[no_trace] ServoUrl),
23    Subframe(#[no_trace] ServoUrl),
24    Stylesheet(#[no_trace] ServoUrl),
25    PageSource(#[no_trace] ServoUrl),
26    Media,
27}
28
29/// Canary value ensuring that manually added blocking loads (ie. ones that weren't
30/// created via DocumentLoader::fetch_async) are always removed by the time
31/// that the owner is destroyed.
32#[derive(JSTraceable, MallocSizeOf)]
33#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
34pub(crate) struct LoadBlocker {
35    /// The document whose load event is blocked by this object existing.
36    doc: Dom<Document>,
37    /// The load that is blocking the document's load event.
38    load: Option<LoadType>,
39}
40
41impl LoadBlocker {
42    /// Mark the document's load event as blocked on this new load.
43    pub(crate) fn new(doc: &Document, load: LoadType) -> LoadBlocker {
44        doc.loader_mut().add_blocking_load(load.clone());
45        LoadBlocker {
46            doc: Dom::from_ref(doc),
47            load: Some(load),
48        }
49    }
50
51    /// Remove this load from the associated document's list of blocking loads.
52    pub(crate) fn terminate(blocker: &DomRefCell<Option<LoadBlocker>>, can_gc: CanGc) {
53        let Some(load) = blocker
54            .borrow_mut()
55            .as_mut()
56            .and_then(|blocker| blocker.load.take())
57        else {
58            return;
59        };
60
61        if let Some(blocker) = blocker.borrow().as_ref() {
62            blocker.doc.finish_load(load, can_gc);
63        }
64
65        *blocker.borrow_mut() = None;
66    }
67}
68
69impl Drop for LoadBlocker {
70    fn drop(&mut self) {
71        if let Some(load) = self.load.take() {
72            self.doc.finish_load(load, CanGc::note());
73        }
74    }
75}
76
77#[derive(JSTraceable, MallocSizeOf)]
78pub(crate) struct DocumentLoader {
79    #[no_trace]
80    resource_threads: ResourceThreads,
81    blocking_loads: Vec<LoadType>,
82    events_inhibited: bool,
83    cancellers: Vec<FetchCanceller>,
84}
85
86impl DocumentLoader {
87    pub(crate) fn new(existing: &DocumentLoader) -> DocumentLoader {
88        DocumentLoader::new_with_threads(existing.resource_threads.clone(), None)
89    }
90
91    pub(crate) fn new_with_threads(
92        resource_threads: ResourceThreads,
93        initial_load: Option<ServoUrl>,
94    ) -> DocumentLoader {
95        debug!("Initial blocking load {:?}.", initial_load);
96        let initial_loads = initial_load.into_iter().map(LoadType::PageSource).collect();
97
98        DocumentLoader {
99            resource_threads,
100            blocking_loads: initial_loads,
101            events_inhibited: false,
102            cancellers: Vec::new(),
103        }
104    }
105
106    /// <https://fetch.spec.whatwg.org/#concept-fetch-group-terminate>
107    pub(crate) fn cancel_all_loads(&mut self) -> Vec<FetchCanceller> {
108        self.cancellers.drain(..).collect()
109    }
110
111    /// Add a load to the list of blocking loads.
112    fn add_blocking_load(&mut self, load: LoadType) {
113        debug!(
114            "Adding blocking load {:?} ({}).",
115            load,
116            self.blocking_loads.len()
117        );
118        self.blocking_loads.push(load);
119    }
120
121    /// Initiate a new fetch given a response callback.
122    pub(crate) fn fetch_async_with_callback(
123        &mut self,
124        load: LoadType,
125        request: RequestBuilder,
126        callback: BoxedFetchCallback,
127    ) {
128        self.add_blocking_load(load);
129        self.fetch_async_background(request, callback);
130    }
131
132    /// Initiate a new fetch that does not block the document load event.
133    pub(crate) fn fetch_async_background(
134        &mut self,
135        request: RequestBuilder,
136        callback: BoxedFetchCallback,
137    ) {
138        self.cancellers.push(FetchCanceller::new(
139            request.id,
140            request.keep_alive,
141            self.resource_threads.core_thread.clone(),
142        ));
143        fetch_async(&self.resource_threads.core_thread, request, None, callback);
144    }
145
146    /// Mark an in-progress network request complete.
147    pub(crate) fn finish_load(&mut self, load: &LoadType) {
148        debug!(
149            "Removing blocking load {:?} ({}).",
150            load,
151            self.blocking_loads.len()
152        );
153        let idx = self
154            .blocking_loads
155            .iter()
156            .position(|unfinished| *unfinished == *load);
157        match idx {
158            Some(i) => {
159                self.blocking_loads.remove(i);
160            },
161            None => warn!("unknown completed load {:?}", load),
162        }
163    }
164
165    pub(crate) fn is_blocked(&self) -> bool {
166        // TODO: Ensure that we report blocked if parsing is still ongoing.
167        !self.blocking_loads.is_empty()
168    }
169
170    pub(crate) fn is_only_blocked_by_iframes(&self) -> bool {
171        self.blocking_loads
172            .iter()
173            .all(|load| matches!(*load, LoadType::Subframe(_)))
174    }
175
176    pub(crate) fn inhibit_events(&mut self) {
177        self.events_inhibited = true;
178    }
179
180    pub(crate) fn events_inhibited(&self) -> bool {
181        self.events_inhibited
182    }
183
184    pub(crate) fn resource_threads(&self) -> &ResourceThreads {
185        &self.resource_threads
186    }
187}