Skip to main content

script/fetch/
network_listener.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
5use std::sync::{Arc, Mutex};
6
7use bytes::Bytes;
8use content_security_policy::Violation;
9use js::context::JSContext;
10use net_traits::request::RequestId;
11use net_traits::{
12    BoxedFetchCallback, FetchMetadata, FetchResponseMsg, Metadata, NetworkError,
13    ResourceFetchTiming, ResourceTimingType,
14};
15use servo_url::ServoUrl;
16
17use crate::dom::bindings::inheritance::Castable;
18use crate::dom::globalscope::GlobalScope;
19use crate::dom::performance::performanceentry::PerformanceEntry;
20use crate::dom::performance::performanceresourcetiming::{
21    InitiatorType, PerformanceResourceTiming,
22};
23use crate::tasks::task_source::SendableTaskSource;
24
25pub(crate) trait ResourceTimingListener {
26    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl);
27}
28
29pub(crate) fn submit_timing<T: ResourceTimingListener>(
30    cx: &mut JSContext,
31    global: &GlobalScope,
32    listener: &T,
33    result: &Result<(), NetworkError>,
34    resource_timing: &ResourceFetchTiming,
35) {
36    // https://www.w3.org/TR/resource-timing/#resources-included-in-the-performanceresourcetiming-interface
37    // If a resource fetch is aborted because it failed a fetch precondition
38    // (e.g. mixed content, CORS restriction, CSP policy, etc), then this resource
39    // will not be included as a PerformanceResourceTiming object in
40    // the Performance Timeline.
41    if let Err(error) = &result &&
42        error.is_permanent_failure()
43    {
44        return;
45    }
46
47    // Resource timings should only be submitted for the initial preload request,
48    // not for the request that consumes the preload: https://github.com/whatwg/html/issues/12047
49    if resource_timing.preloaded {
50        return;
51    }
52    // TODO Resources for which the fetch was initiated, but was later aborted
53    // (e.g. due to a network error) MAY be included as PerformanceResourceTiming
54    // objects in the Performance Timeline and MUST contain initialized attribute
55    // values for processed substeps of the processing model.
56    if resource_timing.timing_type != ResourceTimingType::Resource &&
57        resource_timing.timing_type != ResourceTimingType::Error
58    {
59        warn!(
60            "Submitting non-resource ({:?}) timing as resource",
61            resource_timing.timing_type
62        );
63        return;
64    }
65
66    let (initiator_type, url) = listener.resource_timing_information();
67    if initiator_type == InitiatorType::Other {
68        warn!("Ignoring InitiatorType::Other resource {:?}", url);
69        return;
70    }
71
72    submit_timing_data(cx, global, url, initiator_type, resource_timing);
73}
74
75pub(crate) fn submit_timing_data(
76    cx: &mut JSContext,
77    global: &GlobalScope,
78    url: ServoUrl,
79    initiator_type: InitiatorType,
80    resource_timing: &ResourceFetchTiming,
81) {
82    let performance_entry =
83        PerformanceResourceTiming::new(cx, global, url, initiator_type, resource_timing);
84    global
85        .performance(cx)
86        .queue_entry(performance_entry.upcast::<PerformanceEntry>());
87}
88
89/// Check status from the optional response metadata, treating a
90/// missing status as a resource load error.
91pub(crate) fn check_response_status(metadata: Option<&Metadata>) -> Result<(), NetworkError> {
92    let Some(status) = metadata.map(|metadata| &metadata.status) else {
93        return Err(NetworkError::ResourceLoadError(
94            "No http status code received".to_owned(),
95        ));
96    };
97    if status.is_success() {
98        Ok(())
99    } else {
100        Err(NetworkError::ResourceLoadError(format!(
101            "HTTP error code {}",
102            status.code()
103        )))
104    }
105}
106
107pub(crate) trait FetchResponseListener: Send + 'static {
108    /// A gating mechanism that runs before invoking the listener methods on the target
109    /// thread. If the `should_invoke` method returns false, the listener does not receive
110    /// the notification.
111    fn should_invoke(&self) -> bool {
112        true
113    }
114
115    fn process_request_body(&mut self, global: &GlobalScope, request_id: RequestId);
116    fn process_response(
117        &mut self,
118        cx: &mut JSContext,
119        global: &GlobalScope,
120        request_id: RequestId,
121        metadata: Result<FetchMetadata, NetworkError>,
122    );
123    fn process_response_chunk(
124        &mut self,
125        cx: &mut JSContext,
126        global: &GlobalScope,
127        request_id: RequestId,
128        chunk: Bytes,
129    );
130    fn process_response_eof(
131        self,
132        cx: &mut JSContext,
133        global: &GlobalScope,
134        request_id: RequestId,
135        response: Result<(), NetworkError>,
136        timing: ResourceFetchTiming,
137    );
138    fn process_csp_violations(
139        &mut self,
140        cx: &mut js::context::JSContext,
141        global: &GlobalScope,
142        request_id: RequestId,
143        violations: Vec<Violation>,
144    );
145
146    fn process_content_length(&mut self, _request_id: RequestId, _size: usize) {}
147}
148
149/// An off-thread sink for async network event tasks. All such events are forwarded to
150/// a target thread, where they are invoked on the provided context object.
151pub(crate) struct NetworkListener<Listener: FetchResponseListener> {
152    pub(crate) context: Arc<Mutex<Option<Listener>>>,
153    pub(crate) task_source: SendableTaskSource,
154}
155
156impl<Listener: FetchResponseListener> NetworkListener<Listener> {
157    pub(crate) fn new(context: Listener, task_source: SendableTaskSource) -> Self {
158        Self {
159            context: Arc::new(Mutex::new(Some(context))),
160            task_source,
161        }
162    }
163
164    pub(crate) fn notify(&mut self, message: FetchResponseMsg) {
165        let context = self.context.clone();
166
167        self.task_source
168            .queue(task!(network_listener_response: move |cx| {
169                let mut context = context.lock().unwrap();
170                let Some(fetch_listener) = &mut *context else {
171                    return;
172                };
173
174                // Note: This relies on the task queue to properly enter the realm of the global
175                // scope of a task before running it.
176                let Some(global) = GlobalScope::current() else {
177                    return;
178                };
179
180                let is_eof = matches!(message, FetchResponseMsg::ProcessResponseEOF(..));
181                let request_id = message.request_id();
182
183                if fetch_listener.should_invoke() {
184                    match message {
185                        FetchResponseMsg::ProcessRequestBody(request_id) => {
186                            fetch_listener.process_request_body(&global, request_id)
187                        },
188                        FetchResponseMsg::ProcessResponse(request_id, meta) => {
189                            fetch_listener.process_response(cx, &global, request_id, meta)
190                        },
191                        FetchResponseMsg::ProcessResponseChunk(request_id, data) => {
192                            fetch_listener.process_response_chunk(cx, &global, request_id, data)
193                        },
194                        FetchResponseMsg::ProcessResponseEOF(request_id, result, timing) => {
195                            if let Some(fetch_listener) = context.take() {
196                                fetch_listener.process_response_eof(cx, &global, request_id, result, timing);
197                            };
198                        },
199                        FetchResponseMsg::ProcessCspViolations(request_id, violations) => {
200                            fetch_listener.process_csp_violations(cx, &global, request_id, violations)
201                        },
202                        FetchResponseMsg::ProcessContentLength(request_id, size) => { fetch_listener.process_content_length(request_id, size) },
203                    }
204                }
205
206                if is_eof {
207                    global
208                        .fetch_group_mut()
209                        .mark_fetch_request_as_done(&request_id);
210                }
211            }));
212    }
213
214    pub(crate) fn into_callback(mut self) -> BoxedFetchCallback {
215        Box::new(move |response_msg| self.notify(response_msg))
216    }
217}