Skip to main content

script/dom/serviceworker/
serviceworkerregistration.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::cell::Cell;
6
7use devtools_traits::WorkerId;
8use dom_struct::dom_struct;
9use js::context::JSContext;
10use net_traits::request::Referrer;
11use script_bindings::cell::DomRefCell;
12use script_bindings::codegen::GenericBindings::NavigatorBinding::NavigatorMethods;
13use script_bindings::codegen::GenericBindings::WindowBinding::WindowMethods;
14use script_bindings::reflector::reflect_dom_object;
15use servo_base::id::ServiceWorkerRegistrationId;
16use servo_constellation_traits::{ScopeThings, WorkerScriptLoadOrigin};
17use servo_url::ServoUrl;
18use uuid::Uuid;
19
20use crate::dom::RootedPromise;
21use crate::dom::bindings::codegen::Bindings::ServiceWorkerRegistrationBinding::{
22    ServiceWorkerRegistrationMethods, ServiceWorkerUpdateViaCache,
23};
24use crate::dom::bindings::error::Error;
25use crate::dom::bindings::inheritance::Castable;
26use crate::dom::bindings::reflector::DomGlobal;
27use crate::dom::bindings::root::{DomRoot, MutNullableDom};
28use crate::dom::bindings::str::{ByteString, USVString};
29use crate::dom::cookiestoremanager::CookieStoreManager;
30use crate::dom::eventtarget::EventTarget;
31use crate::dom::globalscope::GlobalScope;
32use crate::dom::navigationpreloadmanager::NavigationPreloadManager;
33use crate::dom::promise::Promise;
34use crate::dom::serviceworker::ServiceWorker;
35use crate::dom::window::Window;
36use crate::dom::workerglobalscope::prepare_workerscope_init;
37
38#[dom_struct]
39pub(crate) struct ServiceWorkerRegistration {
40    eventtarget: EventTarget,
41    active: MutNullableDom<ServiceWorker>,
42    installing: MutNullableDom<ServiceWorker>,
43    waiting: MutNullableDom<ServiceWorker>,
44    navigation_preload: MutNullableDom<NavigationPreloadManager>,
45    // Each ServiceWorkerRegistration has an associated CookieStoreManager object.
46    // https://cookiestore.spec.whatwg.org/#dom-serviceworkerregistration-cookies
47    cookie_manager: MutNullableDom<CookieStoreManager>,
48    #[no_trace]
49    scope: ServoUrl,
50    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-navigation-preload-enabled>
51    navigation_preload_enabled: Cell<bool>,
52    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-navigation-preload-header-value>
53    navigation_preload_header_value: DomRefCell<ByteString>,
54    update_via_cache: ServiceWorkerUpdateViaCache,
55    uninstalling: Cell<bool>,
56    #[no_trace]
57    registration_id: ServiceWorkerRegistrationId,
58}
59
60impl ServiceWorkerRegistration {
61    fn new_inherited(
62        scope: ServoUrl,
63        registration_id: ServiceWorkerRegistrationId,
64    ) -> ServiceWorkerRegistration {
65        ServiceWorkerRegistration {
66            eventtarget: EventTarget::new_inherited(),
67            active: MutNullableDom::new(None),
68            installing: MutNullableDom::new(None),
69            waiting: MutNullableDom::new(None),
70            navigation_preload: MutNullableDom::new(None),
71            cookie_manager: MutNullableDom::new(None),
72            scope,
73            // https://w3c.github.io/ServiceWorker/#service-worker-registration-navigation-preload-enabled
74            // A service worker registration has an associated navigation preload enabled,
75            // which is a boolean. It is initially set to false.
76            navigation_preload_enabled: Cell::new(false),
77            // https://w3c.github.io/ServiceWorker/#service-worker-registration-navigation-preload-header-value
78            // A service worker registration has an associated navigation preload header value,
79            // which is a byte sequence. It is initially set to `true`.
80            navigation_preload_header_value: DomRefCell::new(ByteString::new(b"true".to_vec())),
81            update_via_cache: ServiceWorkerUpdateViaCache::Imports,
82            uninstalling: Cell::new(false),
83            registration_id,
84        }
85    }
86
87    pub(crate) fn new(
88        cx: &mut JSContext,
89        global: &GlobalScope,
90        scope: ServoUrl,
91        registration_id: ServiceWorkerRegistrationId,
92    ) -> DomRoot<ServiceWorkerRegistration> {
93        reflect_dom_object(
94            cx,
95            Box::new(ServiceWorkerRegistration::new_inherited(
96                scope,
97                registration_id,
98            )),
99            global,
100        )
101    }
102
103    /// <https://cookiestore.spec.whatwg.org/#subscribe>
104    pub(crate) fn scope_url(&self) -> &ServoUrl {
105        // Let url be registration's scope URL.
106        &self.scope
107    }
108
109    /// Does this registration have an active worker?
110    pub(crate) fn is_active(&self) -> bool {
111        self.active.get().is_some()
112    }
113
114    pub(crate) fn set_installing(&self, worker: &ServiceWorker) {
115        self.installing.set(Some(worker));
116    }
117
118    pub(crate) fn get_navigation_preload_header_value(&self) -> ByteString {
119        self.navigation_preload_header_value.borrow().clone()
120    }
121
122    pub(crate) fn set_navigation_preload_header_value(&self, value: ByteString) {
123        let mut header_value = self.navigation_preload_header_value.borrow_mut();
124        *header_value = value;
125    }
126
127    pub(crate) fn get_navigation_preload_enabled(&self) -> bool {
128        self.navigation_preload_enabled.get()
129    }
130
131    pub(crate) fn set_navigation_preload_enabled(&self, flag: bool) {
132        self.navigation_preload_enabled.set(flag)
133    }
134
135    pub(crate) fn create_scope_things(global: &GlobalScope, script_url: ServoUrl) -> ScopeThings {
136        let worker_load_origin = WorkerScriptLoadOrigin {
137            referrer_url: match global.get_referrer() {
138                Referrer::Client(url) => Some(url),
139                Referrer::ReferrerUrl(url) => Some(url),
140                _ => None,
141            },
142            referrer_policy: global.get_referrer_policy(),
143            pipeline_id: global.pipeline_id(),
144        };
145
146        #[cfg(feature = "webgl")]
147        let webgl_chan = global
148            .downcast::<Window>()
149            .and_then(|window| window.webgl_chan_value());
150        let worker_id = WorkerId(Uuid::new_v4());
151        let devtools_chan = global.devtools_chan().cloned();
152        let init = prepare_workerscope_init(
153            global,
154            None,
155            Some(worker_id),
156            #[cfg(feature = "webgl")]
157            webgl_chan,
158        );
159        let browsing_context_id = global
160            .downcast::<Window>()
161            .map(|w: &Window| w.window_proxy().browsing_context_id())
162            .expect("Service worker must be registered from a Window global");
163        let webview_id = global
164            .webview_id()
165            .expect("Service worker must have a WebViewId");
166        ScopeThings {
167            script_url,
168            init,
169            worker_load_origin,
170            devtools_chan,
171            worker_id,
172            browsing_context_id,
173            webview_id,
174        }
175    }
176
177    /// <https://w3c.github.io/ServiceWorker/#get-newest-worker-algorithm>
178    pub(crate) fn get_newest_worker(&self) -> Option<DomRoot<ServiceWorker>> {
179        self.installing
180            .get()
181            .or_else(|| self.waiting.get())
182            .or_else(|| self.active.get())
183    }
184}
185
186pub(crate) fn longest_prefix_match(stored_scope: &ServoUrl, potential_match: &ServoUrl) -> bool {
187    if stored_scope.origin() != potential_match.origin() {
188        return false;
189    }
190    let scope_chars = stored_scope.path().chars();
191    let matching_chars = potential_match.path().chars();
192    if scope_chars.count() > matching_chars.count() {
193        return false;
194    }
195
196    stored_scope
197        .path()
198        .chars()
199        .zip(potential_match.path().chars())
200        .all(|(scope, matched)| scope == matched)
201}
202
203impl ServiceWorkerRegistrationMethods<crate::DomTypeHolder> for ServiceWorkerRegistration {
204    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-installing-attribute>
205    fn GetInstalling(&self) -> Option<DomRoot<ServiceWorker>> {
206        self.installing.get()
207    }
208
209    /// <https://w3c.github.io/ServiceWorker/#dom-serviceworkerregistration-unregister>
210    fn Unregister(&self, cx: &mut JSContext) -> RootedPromise {
211        // Step 1: Let registration be the service worker registration.
212        // Note: `self` is the registration.
213
214        // Step 2: Let promise be a new promise.
215        let promise = Promise::new(cx, &self.global());
216
217        let Some(worker) = self.get_newest_worker() else {
218            promise.resolve_native(cx, &true);
219            return promise;
220        };
221
222        let global = self.global();
223        let Some(window) = global.downcast::<Window>() else {
224            // Worker navigator does not have a service woker container yet.
225            promise.resolve_native(cx, &false);
226            return promise;
227        };
228        let service_worker_container = window.Navigator(cx).ServiceWorker(cx);
229
230        // Step 3: Let job be the result of running Create Job with unregister,
231        // registration’s storage key, registration’s scope url, null, promise,
232        // and this’s relevant settings object.
233        // Step 4: Invoke Schedule Job with job.
234        // Note: done in the container.
235        let Some(storage_key) = global.obtain_storage_key() else {
236            promise.reject_error(
237                cx,
238                Error::Type(c"Failed to obtain a storage key".to_owned()),
239            );
240            return promise;
241        };
242        service_worker_container.create_and_schedule_unregister_job(
243            cx,
244            storage_key,
245            self.scope.clone(),
246            worker.get_script_url(),
247            &promise,
248        );
249
250        // Set all workers to none.
251        // Note: not clear where the spec does this.
252        self.installing.set(None);
253        self.waiting.set(None);
254        self.active.set(None);
255
256        // Step 5: Return promise.
257        promise
258    }
259
260    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-active-attribute>
261    fn GetActive(&self) -> Option<DomRoot<ServiceWorker>> {
262        self.active.get()
263    }
264
265    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-waiting-attribute>
266    fn GetWaiting(&self) -> Option<DomRoot<ServiceWorker>> {
267        self.waiting.get()
268    }
269
270    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-scope-attribute>
271    fn Scope(&self) -> USVString {
272        USVString(self.scope.as_str().to_owned())
273    }
274
275    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-updateviacache>
276    fn UpdateViaCache(&self) -> ServiceWorkerUpdateViaCache {
277        self.update_via_cache
278    }
279
280    /// <https://w3c.github.io/ServiceWorker/#service-worker-registration-navigationpreload>
281    fn NavigationPreload(&self, cx: &mut JSContext) -> DomRoot<NavigationPreloadManager> {
282        self.navigation_preload
283            .or_init(|| NavigationPreloadManager::new(cx, &self.global(), self))
284    }
285
286    /// <https://cookiestore.spec.whatwg.org/#dom-serviceworkerregistration-cookies>
287    fn Cookies(&self, cx: &mut JSContext) -> DomRoot<CookieStoreManager> {
288        // The cookies getter steps are to return this's associated
289        // CookieStoreManager object.
290        self.cookie_manager
291            .or_init(|| CookieStoreManager::new(cx, &self.global(), self))
292    }
293}