Skip to main content

script/dom/serviceworker/
serviceworker.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 dom_struct::dom_struct;
8use js::context::JSContext;
9use js::jsapi::{Heap, JSObject};
10use js::rust::{CustomAutoRooter, CustomAutoRooterGuard, HandleValue};
11use script_bindings::cell::DomRefCell;
12use script_bindings::reflector::reflect_dom_object;
13use servo_base::id::ServiceWorkerId;
14use servo_constellation_traits::{DOMMessage, ScriptToConstellationMessage};
15use servo_url::ServoUrl;
16
17use crate::dom::abstractworker::SimpleWorkerErrorHandler;
18use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
19use crate::dom::bindings::codegen::Bindings::ServiceWorkerBinding::{
20    ServiceWorkerMethods, ServiceWorkerState,
21};
22use crate::dom::bindings::error::{Error, ErrorResult};
23use crate::dom::bindings::inheritance::Castable;
24use crate::dom::bindings::refcounted::Trusted;
25use crate::dom::bindings::reflector::DomGlobal;
26use crate::dom::bindings::root::DomRoot;
27use crate::dom::bindings::str::USVString;
28use crate::dom::bindings::structuredclone;
29use crate::dom::bindings::trace::RootedTraceableBox;
30use crate::dom::eventtarget::EventTarget;
31use crate::dom::globalscope::GlobalScope;
32use crate::script_runtime::CanGc;
33use crate::task::TaskOnce;
34
35pub(crate) type TrustedServiceWorkerAddress = Trusted<ServiceWorker>;
36
37#[dom_struct]
38pub(crate) struct ServiceWorker {
39    eventtarget: EventTarget,
40    script_url: DomRefCell<String>,
41    #[no_trace]
42    scope_url: ServoUrl,
43    state: Cell<ServiceWorkerState>,
44    #[no_trace]
45    worker_id: ServiceWorkerId,
46}
47
48impl ServiceWorker {
49    fn new_inherited(
50        script_url: &str,
51        scope_url: ServoUrl,
52        worker_id: ServiceWorkerId,
53    ) -> ServiceWorker {
54        ServiceWorker {
55            eventtarget: EventTarget::new_inherited(),
56            script_url: DomRefCell::new(String::from(script_url)),
57            state: Cell::new(ServiceWorkerState::Installing),
58            scope_url,
59            worker_id,
60        }
61    }
62
63    pub(crate) fn new(
64        global: &GlobalScope,
65        script_url: ServoUrl,
66        scope_url: ServoUrl,
67        worker_id: ServiceWorkerId,
68        can_gc: CanGc,
69    ) -> DomRoot<ServiceWorker> {
70        reflect_dom_object(
71            Box::new(ServiceWorker::new_inherited(
72                script_url.as_str(),
73                scope_url,
74                worker_id,
75            )),
76            global,
77            can_gc,
78        )
79    }
80
81    pub(crate) fn dispatch_simple_error(cx: &mut JSContext, address: TrustedServiceWorkerAddress) {
82        let service_worker = address.root();
83        service_worker.upcast().fire_event(cx, atom!("error"));
84    }
85
86    pub(crate) fn get_script_url(&self) -> ServoUrl {
87        ServoUrl::parse(&self.script_url.borrow().clone()).unwrap()
88    }
89
90    /// <https://w3c.github.io/ServiceWorker/#service-worker-postmessage>
91    fn post_message_impl(
92        &self,
93        cx: &mut JSContext,
94        message: HandleValue,
95        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
96    ) -> ErrorResult {
97        // Step 1
98        if let ServiceWorkerState::Redundant = self.state.get() {
99            return Err(Error::InvalidState(None));
100        }
101        // Step 7
102        let data = structuredclone::write(cx, message, Some(transfer))?;
103        let incumbent = GlobalScope::incumbent().expect("no incumbent global?");
104        let pipeline_id = incumbent.pipeline_id();
105        let msg_vec = DOMMessage {
106            origin: incumbent.origin().immutable().clone(),
107            pipeline_id,
108            data,
109        };
110        let _ = self.global().script_to_constellation_chan().send(
111            ScriptToConstellationMessage::ForwardDOMMessage(msg_vec, self.scope_url.clone()),
112        );
113        Ok(())
114    }
115}
116
117impl ServiceWorkerMethods<crate::DomTypeHolder> for ServiceWorker {
118    /// <https://w3c.github.io/ServiceWorker/#service-worker-state-attribute>
119    fn State(&self) -> ServiceWorkerState {
120        self.state.get()
121    }
122
123    /// <https://w3c.github.io/ServiceWorker/#service-worker-url-attribute>
124    fn ScriptURL(&self) -> USVString {
125        USVString(self.script_url.borrow().clone())
126    }
127
128    /// <https://w3c.github.io/ServiceWorker/#service-worker-postmessage>
129    fn PostMessage(
130        &self,
131        cx: &mut JSContext,
132        message: HandleValue,
133        transfer: CustomAutoRooterGuard<Vec<*mut JSObject>>,
134    ) -> ErrorResult {
135        self.post_message_impl(cx, message, transfer)
136    }
137
138    /// <https://w3c.github.io/ServiceWorker/#service-worker-postmessage>
139    fn PostMessage_(
140        &self,
141        cx: &mut JSContext,
142        message: HandleValue,
143        options: RootedTraceableBox<StructuredSerializeOptions>,
144    ) -> ErrorResult {
145        let mut rooted = CustomAutoRooter::new(
146            options
147                .transfer
148                .iter()
149                .map(|js: &RootedTraceableBox<Heap<*mut JSObject>>| js.get())
150                .collect(),
151        );
152        #[expect(unsafe_code)]
153        let guard = unsafe { CustomAutoRooterGuard::new(cx.raw_cx(), &mut rooted) };
154        self.post_message_impl(cx, message, guard)
155    }
156
157    // https://w3c.github.io/ServiceWorker/#service-worker-container-onerror-attribute
158    event_handler!(error, GetOnerror, SetOnerror);
159
160    // https://w3c.github.io/ServiceWorker/#ref-for-service-worker-onstatechange-attribute-1
161    event_handler!(statechange, GetOnstatechange, SetOnstatechange);
162}
163
164impl TaskOnce for SimpleWorkerErrorHandler<ServiceWorker> {
165    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
166    fn run_once(self, cx: &mut JSContext) {
167        ServiceWorker::dispatch_simple_error(cx, self.addr);
168    }
169}