Skip to main content

net_traits/
resource_fetch_timing.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 malloc_size_of_derive::MallocSizeOf;
6use parking_lot::{Mutex, MutexGuard};
7use serde::{Deserialize, Serialize};
8use servo_arc::Arc;
9use servo_base::cross_process_instant::CrossProcessInstant;
10
11/// <https://fetch.spec.whatwg.org/#connection-timing-info>
12#[derive(Clone, Debug, Default, Deserialize, MallocSizeOf, Serialize)]
13pub struct ConnectionTimingInfo {
14    /// <https://fetch.spec.whatwg.org/#connection-timing-info-domain-lookup-start-time>
15    pub domain_lookup_start_time: Option<CrossProcessInstant>,
16    /// <https://fetch.spec.whatwg.org/#connection-timing-info-connection-start-time>
17    pub connection_start_time: Option<CrossProcessInstant>,
18    /// <https://fetch.spec.whatwg.org/#connection-timing-info-connection-end-time>
19    pub connection_end_time: Option<CrossProcessInstant>,
20    /// <https://fetch.spec.whatwg.org/#connection-timing-info-secure-connection-start-time>
21    pub secure_connection_start_time: Option<CrossProcessInstant>,
22}
23
24#[derive(Clone, Debug, Deserialize, MallocSizeOf, Serialize)]
25pub struct ResourceFetchTiming {
26    pub timing_check_passed: bool,
27    pub timing_type: ResourceTimingType,
28    /// Number of redirects until final resource (currently limited to 20)
29    pub redirect_count: u16,
30    /// <https://fetch.spec.whatwg.org/#fetch-timing-info-start-time>
31    pub request_start: Option<CrossProcessInstant>,
32    pub response_start: Option<CrossProcessInstant>,
33    pub fetch_start: Option<CrossProcessInstant>,
34    /// <https://fetch.spec.whatwg.org/#fetch-timing-info-end-time>
35    pub response_end: Option<CrossProcessInstant>,
36    /// <https://fetch.spec.whatwg.org/#fetch-timing-info-redirect-start-time>
37    pub redirect_start: Option<CrossProcessInstant>,
38    /// <https://fetch.spec.whatwg.org/#fetch-timing-info-redirect-end-time>
39    pub redirect_end: Option<CrossProcessInstant>,
40    pub start_time: Option<CrossProcessInstant>,
41    /// <https://fetch.spec.whatwg.org/#fetch-timing-info-final-service-worker-start-time>
42    pub final_service_worker_start_time: Option<CrossProcessInstant>,
43    /// <https://fetch.spec.whatwg.org/#fetch-timing-info-final-connection-timing-info>
44    pub final_connection_timing_info: Option<ConnectionTimingInfo>,
45    pub preloaded: bool,
46}
47
48#[derive(Clone)]
49pub enum RedirectStartValue {
50    Zero,
51    FetchStart,
52}
53
54#[derive(Clone)]
55pub enum RedirectEndValue {
56    Zero,
57    ResponseEnd,
58}
59
60// TODO: refactor existing code to use this enum for setting time attributes
61// suggest using this with all time attributes in the future
62#[derive(Clone)]
63pub enum ResourceTimeValue {
64    Zero,
65    Now,
66    FetchStart,
67    RedirectStart,
68}
69
70#[derive(Clone)]
71pub enum ResourceAttribute {
72    RedirectCount(u16),
73    DomainLookupStart,
74    RequestStart,
75    ResponseStart,
76    RedirectStart(RedirectStartValue),
77    RedirectEnd(RedirectEndValue),
78    FetchStart,
79    ConnectStart(CrossProcessInstant),
80    ConnectEnd(CrossProcessInstant),
81    SecureConnectionStart,
82    ResponseEnd,
83    StartTime(ResourceTimeValue),
84    FinalServiceWorkerStartTime,
85}
86
87#[derive(Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize)]
88pub enum ResourceTimingType {
89    Resource,
90    Navigation,
91    Error,
92    None,
93}
94
95impl ResourceFetchTiming {
96    pub fn new(timing_type: ResourceTimingType) -> ResourceFetchTiming {
97        ResourceFetchTiming {
98            timing_type,
99            timing_check_passed: true,
100            redirect_count: 0,
101            request_start: None,
102            response_start: None,
103            fetch_start: None,
104            redirect_start: None,
105            redirect_end: None,
106            response_end: None,
107            start_time: None,
108            final_service_worker_start_time: None,
109            final_connection_timing_info: None,
110            preloaded: false,
111        }
112    }
113
114    // TODO currently this is being set with precise time ns when it should be time since
115    // time origin (as described in Performance::now)
116    pub fn set_attribute(&mut self, attribute: ResourceAttribute) {
117        let should_attribute_always_be_updated = matches!(
118            attribute,
119            ResourceAttribute::FetchStart |
120                ResourceAttribute::ResponseEnd |
121                ResourceAttribute::StartTime(_)
122        );
123        if !self.timing_check_passed && !should_attribute_always_be_updated {
124            return;
125        }
126        let now = Some(CrossProcessInstant::now());
127        match attribute {
128            ResourceAttribute::DomainLookupStart => {
129                self.connection_timing_info_mut().domain_lookup_start_time = now
130            },
131            ResourceAttribute::RedirectCount(count) => self.redirect_count = count,
132            ResourceAttribute::RequestStart => self.request_start = now,
133            ResourceAttribute::ResponseStart => self.response_start = now,
134            ResourceAttribute::RedirectStart(val) => match val {
135                RedirectStartValue::Zero => self.redirect_start = None,
136                RedirectStartValue::FetchStart => {
137                    if self.redirect_start.is_none() {
138                        self.redirect_start = self.fetch_start
139                    }
140                },
141            },
142            ResourceAttribute::RedirectEnd(val) => match val {
143                RedirectEndValue::Zero => self.redirect_end = None,
144                RedirectEndValue::ResponseEnd => self.redirect_end = self.response_end,
145            },
146            ResourceAttribute::FetchStart => self.fetch_start = now,
147            ResourceAttribute::ConnectStart(instant) => {
148                self.connection_timing_info_mut().connection_start_time = Some(instant)
149            },
150            ResourceAttribute::ConnectEnd(instant) => {
151                self.connection_timing_info_mut().connection_end_time = Some(instant)
152            },
153            ResourceAttribute::SecureConnectionStart => {
154                self.connection_timing_info_mut()
155                    .secure_connection_start_time = now
156            },
157            ResourceAttribute::ResponseEnd => self.response_end = now,
158            ResourceAttribute::StartTime(val) => match val {
159                ResourceTimeValue::RedirectStart
160                    if self.redirect_start.is_none() || !self.timing_check_passed => {},
161                _ => self.start_time = self.get_time_value(val),
162            },
163            ResourceAttribute::FinalServiceWorkerStartTime => {
164                self.final_service_worker_start_time = now
165            },
166        }
167    }
168
169    fn connection_timing_info_mut(&mut self) -> &mut ConnectionTimingInfo {
170        self.final_connection_timing_info
171            .get_or_insert_with(ConnectionTimingInfo::default)
172    }
173
174    fn get_time_value(&self, time: ResourceTimeValue) -> Option<CrossProcessInstant> {
175        match time {
176            ResourceTimeValue::Zero => None,
177            ResourceTimeValue::Now => Some(CrossProcessInstant::now()),
178            ResourceTimeValue::FetchStart => self.fetch_start,
179            ResourceTimeValue::RedirectStart => self.redirect_start,
180        }
181    }
182
183    pub fn mark_timing_check_failed(&mut self) {
184        self.timing_check_passed = false;
185        if let Some(connection_timing_info) = &mut self.final_connection_timing_info {
186            connection_timing_info.domain_lookup_start_time = None;
187            connection_timing_info.connection_start_time = None;
188            connection_timing_info.connection_end_time = None;
189        }
190        self.redirect_count = 0;
191        self.request_start = None;
192        self.response_start = None;
193        self.redirect_start = None;
194    }
195}
196
197#[derive(Clone, Debug, Serialize, Deserialize, MallocSizeOf)]
198/// A simple container of [`ResourceFetchTiming`] to allow easy sharing between threads and allow to set multiple attributes in sequence.
199pub struct ResourceFetchTimingContainer(
200    #[conditional_malloc_size_of] Arc<Mutex<ResourceFetchTiming>>,
201);
202
203impl ResourceFetchTimingContainer {
204    pub fn set_attribute(&self, attribute: ResourceAttribute) {
205        self.0.lock().set_attribute(attribute);
206    }
207
208    /// Set multiple attributes in sequence.
209    pub fn set_attributes(&self, attributes: &[ResourceAttribute]) {
210        let mut inner = self.0.lock();
211        for attribute in attributes {
212            inner.set_attribute(attribute.clone());
213        }
214    }
215
216    pub fn inner(&self) -> MutexGuard<'_, ResourceFetchTiming> {
217        self.0.lock()
218    }
219}
220
221impl From<ResourceFetchTiming> for ResourceFetchTimingContainer {
222    fn from(value: ResourceFetchTiming) -> Self {
223        ResourceFetchTimingContainer(Arc::new(Mutex::new(value)))
224    }
225}