Skip to main content

script/dom/serviceworker/
serviceworker_manager.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//! The service worker manager persists the descriptor of any registered service workers.
6//! It also stores an active workers map, which holds descriptors of running service workers.
7//! If an active service worker timeouts, then it removes the descriptor entry from its
8//! active_workers map
9
10use std::collections::HashMap;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::thread::{self, JoinHandle};
14
15use crossbeam_channel::{Sender, select, unbounded};
16use fonts::FontContext;
17use net_traits::{CoreResourceMsg, CustomResponseMediator};
18use servo_base::generic_channel::{self, GenericCallback, GenericSender, RoutedReceiver};
19use servo_base::id::{PipelineNamespace, ServiceWorkerId, ServiceWorkerRegistrationId};
20use servo_config::pref;
21use servo_constellation_traits::{
22    DOMMessage, Job, JobError, JobResult, JobResultValue, JobType, SWManagerSenders, ScopeThings,
23    ServiceWorkerAlgorithm, ServiceWorkerAlgorithmResult, ServiceWorkerManagerFactory,
24    ServiceWorkerManagerMsg, ServiceWorkerMsg, ServiceWorkerRegistrationInfo, ServiceWorkerState,
25};
26use servo_url::{ImmutableOrigin, ServoUrl};
27
28use crate::dom::abstractworker::{MessageData, WorkerScriptMsg};
29use crate::dom::serviceworkerglobalscope::{
30    ServiceWorkerControlMsg, ServiceWorkerGlobalScope, ServiceWorkerScriptMsg,
31};
32use crate::dom::serviceworkerregistration::longest_prefix_match;
33use crate::runtime::script_runtime::ThreadSafeJSContext;
34
35enum Message {
36    FromResource(CustomResponseMediator),
37    FromConstellation(Box<ServiceWorkerMsg>),
38}
39
40/// <https://w3c.github.io/ServiceWorker/#dfn-service-worker>
41#[derive(Clone)]
42pub(crate) struct ServiceWorker {
43    /// A unique identifer.
44    pub(crate) id: ServiceWorkerId,
45    /// <https://w3c.github.io/ServiceWorker/#dfn-script-url>
46    pub(crate) script_url: ServoUrl,
47    /// A sender to the running service worker scope.
48    pub(crate) sender: Sender<ServiceWorkerScriptMsg>,
49    /// <https://w3c.github.io/ServiceWorker/#dfn-state>
50    pub(crate) state: ServiceWorkerState,
51}
52
53impl ServiceWorker {
54    fn new(
55        script_url: ServoUrl,
56        sender: Sender<ServiceWorkerScriptMsg>,
57        id: ServiceWorkerId,
58    ) -> ServiceWorker {
59        ServiceWorker {
60            id,
61            script_url,
62            sender,
63            state: ServiceWorkerState::Parsed,
64        }
65    }
66
67    /// Forward a DOM message to the running service worker scope.
68    fn forward_dom_message(&self, msg: DOMMessage) {
69        let DOMMessage {
70            origin,
71            data,
72            pipeline_id,
73        } = msg;
74        let _ = self.sender.send(ServiceWorkerScriptMsg::CommonWorker(
75            WorkerScriptMsg::DOMMessage(MessageData {
76                origin,
77                pipeline_id,
78                data: Box::new(data),
79            }),
80        ));
81    }
82
83    /// Send a message to the running service worker scope.
84    fn send_message(&self, msg: ServiceWorkerScriptMsg) {
85        let _ = self.sender.send(msg);
86    }
87}
88
89/// When updating a registration, which worker are we targetting?
90#[expect(dead_code)]
91enum RegistrationUpdateTarget {
92    Installing,
93    Waiting,
94    Active,
95}
96
97impl Drop for ServiceWorkerRegistration {
98    /// <https://html.spec.whatwg.org/multipage/#terminate-a-worker>
99    fn drop(&mut self) {
100        // Drop the channel to signal shutdown.
101        if self
102            .control_sender
103            .take()
104            .expect("No control sender to worker thread.")
105            .send(ServiceWorkerControlMsg::Exit)
106            .is_err()
107        {
108            warn!("Failed to send exit message to service worker scope.");
109        }
110
111        self.closing
112            .take()
113            .expect("No close flag for worker")
114            .store(true, Ordering::SeqCst);
115        self.context
116            .take()
117            .expect("No context to request interrupt.")
118            .request_interrupt_callback();
119
120        // TODO: Step 1, 2 and 3.
121        if self
122            .join_handle
123            .take()
124            .expect("No handle to join on worker.")
125            .join()
126            .is_err()
127        {
128            warn!("Failed to join on service worker thread.");
129        }
130    }
131}
132
133/// <https://w3c.github.io/ServiceWorker/#service-worker-registration-concept>
134struct ServiceWorkerRegistration {
135    /// A unique identifer.
136    id: ServiceWorkerRegistrationId,
137    /// <https://w3c.github.io/ServiceWorker/#dfn-active-worker>
138    active_worker: Option<ServiceWorker>,
139    /// <https://w3c.github.io/ServiceWorker/#dfn-waiting-worker>
140    waiting_worker: Option<ServiceWorker>,
141    /// <https://w3c.github.io/ServiceWorker/#dfn-installing-worker>
142    installing_worker: Option<ServiceWorker>,
143    /// A channel to send control message to the worker,
144    /// currently only used to signal shutdown.
145    control_sender: Option<Sender<ServiceWorkerControlMsg>>,
146    /// A handle to join on the worker thread.
147    join_handle: Option<JoinHandle<()>>,
148    /// A context to request an interrupt.
149    context: Option<ThreadSafeJSContext>,
150    /// The closing flag for the worker.
151    closing: Option<Arc<AtomicBool>>,
152    /// <https://w3c.github.io/ServiceWorker/#serviceworkercontainer-service-worker-client>
153    /// The client of the container to which this registration belongs.
154    client: GenericCallback<ServiceWorkerAlgorithmResult>,
155}
156
157impl ServiceWorkerRegistration {
158    pub(crate) fn new(
159        client: GenericCallback<ServiceWorkerAlgorithmResult>,
160    ) -> ServiceWorkerRegistration {
161        ServiceWorkerRegistration {
162            id: ServiceWorkerRegistrationId::new(),
163            active_worker: None,
164            waiting_worker: None,
165            installing_worker: None,
166            join_handle: None,
167            control_sender: None,
168            context: None,
169            closing: None,
170            client,
171        }
172    }
173
174    fn note_worker_thread(
175        &mut self,
176        join_handle: JoinHandle<()>,
177        control_sender: Sender<ServiceWorkerControlMsg>,
178        context: ThreadSafeJSContext,
179        closing: Arc<AtomicBool>,
180    ) {
181        assert!(self.join_handle.is_none());
182        self.join_handle = Some(join_handle);
183
184        assert!(self.control_sender.is_none());
185        self.control_sender = Some(control_sender);
186
187        assert!(self.context.is_none());
188        self.context = Some(context);
189
190        assert!(self.closing.is_none());
191        self.closing = Some(closing);
192    }
193
194    /// <https://w3c.github.io/ServiceWorker/#get-newest-worker>
195    fn get_newest_worker(&self) -> Option<ServiceWorker> {
196        if let Some(worker) = self.active_worker.as_ref() {
197            return Some(worker.clone());
198        }
199        if let Some(worker) = self.waiting_worker.as_ref() {
200            return Some(worker.clone());
201        }
202        if let Some(worker) = self.installing_worker.as_ref() {
203            return Some(worker.clone());
204        }
205        None
206    }
207
208    /// <https://w3c.github.io/ServiceWorker/#update-registration-state>
209    fn update_registration_state(
210        &mut self,
211        target: RegistrationUpdateTarget,
212        worker: Option<ServiceWorker>,
213    ) {
214        match target {
215            RegistrationUpdateTarget::Active => {
216                self.active_worker = worker;
217            },
218            RegistrationUpdateTarget::Waiting => {
219                self.waiting_worker = worker;
220            },
221            RegistrationUpdateTarget::Installing => {
222                self.installing_worker = worker;
223            },
224        }
225    }
226}
227
228/// A structure managing all registrations and workers for a given origin.
229pub struct ServiceWorkerManager {
230    /// <https://w3c.github.io/ServiceWorker/#dfn-scope-to-registration-map>
231    registrations: HashMap<ServoUrl, ServiceWorkerRegistration>,
232    // own sender to send messages here
233    own_sender: GenericSender<ServiceWorkerMsg>,
234    /// Sender of messages to the constellation.
235    constellation_sender: GenericSender<ServiceWorkerManagerMsg>,
236    // receiver to receive messages from constellation
237    own_port: RoutedReceiver<ServiceWorkerMsg>,
238    // to receive resource messages
239    resource_receiver: RoutedReceiver<CustomResponseMediator>,
240    /// A shared [`FontContext`] to use for all service workers spawned by this [`ServiceWorkerManager`].
241    font_context: Arc<FontContext>,
242}
243
244impl ServiceWorkerManager {
245    fn new(
246        own_sender: GenericSender<ServiceWorkerMsg>,
247        constellation_sender: GenericSender<ServiceWorkerManagerMsg>,
248        from_constellation_receiver: RoutedReceiver<ServiceWorkerMsg>,
249        resource_port: RoutedReceiver<CustomResponseMediator>,
250        font_context: Arc<FontContext>,
251    ) -> ServiceWorkerManager {
252        // Install a pipeline-namespace in the current thread.
253        PipelineNamespace::auto_install();
254
255        ServiceWorkerManager {
256            registrations: HashMap::new(),
257            own_sender,
258            constellation_sender,
259            own_port: from_constellation_receiver,
260            resource_receiver: resource_port,
261            font_context,
262        }
263    }
264
265    pub(crate) fn get_matching_scope(&self, load_url: &ServoUrl) -> Option<ServoUrl> {
266        for scope in self.registrations.keys() {
267            if longest_prefix_match(scope, load_url) {
268                return Some(scope.clone());
269            }
270        }
271        None
272    }
273
274    fn handle_message(&mut self) {
275        while let Ok(message) = self.receive_message() {
276            let should_continue = match message {
277                Message::FromConstellation(msg) => self.handle_message_from_constellation(*msg),
278                Message::FromResource(msg) => self.handle_message_from_resource(msg),
279            };
280            if !should_continue {
281                for registration in self.registrations.drain() {
282                    // Signal shut-down, and join on the thread.
283                    drop(registration);
284                }
285                break;
286            }
287        }
288    }
289
290    fn handle_message_from_resource(&mut self, mediator: CustomResponseMediator) -> bool {
291        if serviceworker_enabled() &&
292            let Some(scope) = self.get_matching_scope(&mediator.load_url) &&
293            let Some(registration) = self.registrations.get(&scope) &&
294            let Some(ref worker) = registration.active_worker
295        {
296            worker.send_message(ServiceWorkerScriptMsg::Response(mediator));
297            return true;
298        }
299        let _ = mediator.response_chan.send(None);
300        true
301    }
302
303    fn receive_message(&mut self) -> generic_channel::ReceiveResult<Message> {
304        select! {
305            recv(self.own_port) -> result_msg => generic_channel::to_receive_result::<ServiceWorkerMsg>(result_msg).map(|msg| Message::FromConstellation(Box::new(msg))),
306            recv(self.resource_receiver) -> result_msg => generic_channel::to_receive_result::<CustomResponseMediator>(result_msg).map(Message::FromResource),
307        }
308    }
309
310    fn handle_message_from_constellation(&mut self, msg: ServiceWorkerMsg) -> bool {
311        match msg {
312            ServiceWorkerMsg::Timeout(_scope) => {
313                // TODO: https://w3c.github.io/ServiceWorker/#terminate-service-worker
314            },
315            ServiceWorkerMsg::ForwardDOMMessage(msg, scope_url) => {
316                if let Some(registration) = self.registrations.get_mut(&scope_url) {
317                    if let Some(ref worker) = registration.active_worker {
318                        worker.forward_dom_message(msg);
319                    } else if let Some(ref worker) = registration.waiting_worker {
320                        worker.forward_dom_message(msg);
321                    } else if let Some(ref worker) = registration.installing_worker {
322                        worker.forward_dom_message(msg);
323                    }
324                }
325            },
326            ServiceWorkerMsg::FinishInstall(worker_id) => {
327                // Find the relevant worker in the registration map.
328                let mut url = None;
329                for (scope_url, registration) in self.registrations.iter() {
330                    if let Some(worker) = &registration.installing_worker &&
331                        worker.id == worker_id
332                    {
333                        url = Some(scope_url.clone());
334                        break;
335                    }
336                }
337                if let Some(url) = url {
338                    // <https://w3c.github.io/ServiceWorker/#install>
339                    // Now that the waiting condition of step 21 has been met,
340                    // we can continue.
341                    // Step 22: Invoke Try Activate with registration.
342                    self.try_activate_registration(url);
343                }
344            },
345            ServiceWorkerMsg::ForwardWorkerMessage {
346                data,
347                url,
348                source,
349                origin,
350            } => {
351                let Some(registration) = self.registrations.get(&url) else {
352                    warn!("No registration found for scope URL when forwarding message to worker.");
353                    return true;
354                };
355                let script_url = if let Some(worker) = registration.active_worker.as_ref() {
356                    worker.script_url.clone()
357                } else if let Some(worker) = registration.waiting_worker.as_ref() {
358                    worker.script_url.clone()
359                } else if let Some(worker) = registration.installing_worker.as_ref() {
360                    worker.script_url.clone()
361                } else {
362                    warn!("No worker found for scope URL when forwarding message to worker.");
363                    return true;
364                };
365                if registration
366                    .client
367                    .send(ServiceWorkerAlgorithmResult::MessageFromWorker {
368                        message: data,
369                        source,
370                        scope_url: url,
371                        script_url,
372                        origin,
373                    })
374                    .is_err()
375                {
376                    warn!("Failed to forward message from worker to script.");
377                }
378            },
379            ServiceWorkerMsg::HandleAlgorithm(algorithm) => match algorithm {
380                ServiceWorkerAlgorithm::StartRegister(job) => {
381                    self.handle_register_job(job);
382                },
383                ServiceWorkerAlgorithm::Unregister(job) => {
384                    self.handle_unregister_job(job);
385                },
386                ServiceWorkerAlgorithm::MatchServiceWorkerRegistration {
387                    storage_key,
388                    client_url,
389                    result_handler,
390                } => {
391                    self.handle_match_registration(storage_key, client_url, result_handler);
392                },
393            },
394            ServiceWorkerMsg::Exit => return false,
395            ServiceWorkerMsg::SetNetworkOnlineState(online) => {
396                for registration in self.registrations.values() {
397                    for worker in [
398                        &registration.active_worker,
399                        &registration.waiting_worker,
400                        &registration.installing_worker,
401                    ] {
402                        let Some(worker) = worker else { continue };
403                        worker.send_message(ServiceWorkerScriptMsg::SetNetworkOnlineState(online));
404                    }
405                }
406            },
407        }
408        true
409    }
410
411    /// <https://w3c.github.io/ServiceWorker/#try-activate>
412    fn try_activate_registration(&mut self, _url: ServoUrl) {
413        // TODO: implement.
414    }
415
416    /// <https://w3c.github.io/ServiceWorker/#unregister>
417    fn handle_unregister_job(&mut self, job: Job) {
418        // Step 1: Let registration be the result of running Get Registration given job’s storage key and job’s scope url.
419        if self.registrations.remove(&job.scope_url).is_none() {
420            // Step 2: If registration is null, then:
421            // Step 2.1: Invoke Resolve Job Promise with job and false.
422            if job
423                .client
424                .send(ServiceWorkerAlgorithmResult::Job(
425                    JobResult::ResolvePromise(JobResultValue::Unregister(false)),
426                ))
427                .is_err()
428            {
429                warn!("Failed to send unregister result to script.");
430            }
431            // Step 2.2: Invoke Finish Job with job and abort these steps.
432            // TODO: Finish Job.
433            return;
434        };
435
436        // Step 3: Remove registration map[(registration’s storage key, job’s scope url)].
437        // Note: done by removing the registration from the map above.
438
439        // Step 4: Invoke Resolve Job Promise with job and true.
440        if job
441            .client
442            .send(ServiceWorkerAlgorithmResult::Job(
443                JobResult::ResolvePromise(JobResultValue::Unregister(true)),
444            ))
445            .is_err()
446        {
447            warn!("Failed to send unregister result to script.");
448        }
449
450        // Step 5: Invoke Try Clear Registration with registration.
451        // TODO: Try Clear Registration.
452
453        // Step 6: Invoke Finish Job with job.
454        // TODO: Finish Job.
455    }
456
457    /// <https://w3c.github.io/ServiceWorker/#match-service-worker-registration>
458    fn handle_match_registration(
459        &self,
460        storage_key: ImmutableOrigin,
461        client_url: ServoUrl,
462        result_handler: GenericCallback<ServiceWorkerAlgorithmResult>,
463    ) {
464        // Step 1: Run the following steps atomically.
465        // Note: done using the channel from which this message was received.
466
467        // Step 2: Let clientURLString be serialized clientURL.
468        let client_url_string = client_url.as_str();
469
470        // Step 3: Let matchingScopeString be the empty string.
471        let mut matching_scope_string = String::new();
472
473        // Step 4: Let scopeStringSet be an empty list.
474        let mut scope_string_set = Vec::new();
475
476        // Step 5: For each (entry storage key, entry scope) of registration map’s keys:
477        for (entry_storage_key, entry_scope) in self.registrations.keys().map(|k| (k.origin(), k)) {
478            // Step 5.1. If storage key equals entry storage key, then append entry scope to the end of scopeStringSet.
479            if storage_key == entry_storage_key {
480                scope_string_set.push(entry_scope.as_str());
481            }
482        }
483
484        // Step 6: Set matchingScopeString to the longest value in scopeStringSet which the value of clientURLString starts with, if it exists.
485        for scope in scope_string_set {
486            if client_url_string.starts_with(scope) && scope.len() > matching_scope_string.len() {
487                matching_scope_string = scope.to_owned();
488            }
489        }
490
491        // Step 7: Let matchingScope be null.
492        let mut matching_scope = None;
493
494        // Step 8: If matchingScopeString is not the empty string, then:
495        if !matching_scope_string.is_empty() {
496            // Step 8.1. Set matchingScope to the result of parsing matchingScopeString.
497            let Ok(parsed_matching_scope) = ServoUrl::parse(&matching_scope_string) else {
498                error!("Failed to parse matching scope string as URL.");
499                if result_handler
500                    .send(ServiceWorkerAlgorithmResult::MatchServiceWorkerRegistration(None))
501                    .is_err()
502                {
503                    warn!("Failed to send match registration result to script.");
504                }
505                return;
506            };
507            matching_scope = Some(parsed_matching_scope);
508
509            // Step 8.2: Assert: matchingScope’s origin and clientURL’s origin are same origin.
510            debug_assert_eq!(
511                matching_scope.as_ref().unwrap().origin(),
512                client_url.origin()
513            );
514        }
515
516        let Some(matching_scope) = matching_scope else {
517            if result_handler
518                .send(ServiceWorkerAlgorithmResult::MatchServiceWorkerRegistration(None))
519                .is_err()
520            {
521                warn!("Failed to send match registration result to script.");
522            }
523            return;
524        };
525
526        // Step 9: Return the result of running Get Registration given storage key and matchingScope.
527        let registration = self.registrations.get(&matching_scope);
528        let info = registration
529            .as_ref()
530            .map(|registration| ServiceWorkerRegistrationInfo {
531                scope_url: matching_scope,
532                script_url: registration
533                    .get_newest_worker()
534                    .expect("Registration should have a worker.")
535                    .script_url,
536                storage_key,
537                id: registration.id,
538                installing_worker: registration
539                    .installing_worker
540                    .as_ref()
541                    .map(|worker| worker.id),
542                waiting_worker: registration.waiting_worker.as_ref().map(|worker| worker.id),
543                active_worker: registration.active_worker.as_ref().map(|worker| worker.id),
544            });
545        if result_handler
546            .send(ServiceWorkerAlgorithmResult::MatchServiceWorkerRegistration(info))
547            .is_err()
548        {
549            warn!("Failed to send match registration result to script.");
550        }
551    }
552
553    /// <https://w3c.github.io/ServiceWorker/#register-algorithm>
554    fn handle_register_job(&mut self, mut job: Job) {
555        // Step 1: If the result of running potentially trustworthy origin with the origin of job’s script url as the argument is Not Trusted, then:
556        if !job.script_url.origin().is_potentially_trustworthy() {
557            // Step 1.1: Invoke Reject Job Promise with job and "SecurityError" DOMException.
558            if job
559                .client
560                .send(ServiceWorkerAlgorithmResult::Job(JobResult::RejectPromise(
561                    JobError::SecurityError,
562                )))
563                .is_err()
564            {
565                warn!("Failed to send reject job promise result to script.");
566            }
567
568            // TODO Step 1.2: Invoke Finish Job with job and abort these steps.
569            // TODO: Finish Job.
570            return;
571        }
572
573        // Step 2: If job’s script url’s origin and job’s referrer’s origin are not same origin, then:
574        // Step 3: If job’s scope url’s origin and job’s referrer’s origin are not same origin, then:
575        // Note: both steps done in one conditional.
576        if job.script_url.origin() != job.referrer.origin() ||
577            job.scope_url.origin() != job.referrer.origin()
578        {
579            // Step 2.1: Invoke Reject Job Promise with job and "SecurityError" DOMException
580            if job
581                .client
582                .send(ServiceWorkerAlgorithmResult::Job(JobResult::RejectPromise(
583                    JobError::SecurityError,
584                )))
585                .is_err()
586            {
587                warn!("Failed to send reject job promise result to script.");
588            }
589
590            // TODO Step 2.2: Invoke Finish Job with job and abort these steps.
591            return;
592        }
593
594        // Step 4: Let registration be the result of running Get Registration given job’s storage key and job’s scope url.
595        if let Some(registration) = self.registrations.get(&job.scope_url) {
596            // Step 5: If registration is not null, then:
597
598            // Step 5.1: Let newestWorker be the result of running the Get Newest Worker algorithm passing registration as the argument.
599            let newest_worker = registration.get_newest_worker();
600
601            // step 5.2: If newestWorker is not null, job’s script url equals newestWorker’s script url, job’s worker type equals newestWorker’s type, and job’s update via cache mode’s value equals registration’s update via cache mode, then:
602            if newest_worker.is_some() {
603                // TODO: the various checks of job versus worker.
604
605                // Step 5.2.1: Invoke Resolve Job Promise with job and registration.
606                // Step 5.2.2: Invoke Finish Job with job and abort these steps.
607                // TODO: Finish Job.
608                let client = job.client.clone();
609                let _ = client.send(ServiceWorkerAlgorithmResult::Job(
610                    JobResult::ResolvePromise(JobResultValue::Register(
611                        ServiceWorkerRegistrationInfo {
612                            scope_url: job.scope_url.clone(),
613                            script_url: job.script_url.clone(),
614                            storage_key: job.storage_key.clone(),
615                            id: registration.id,
616                            installing_worker: registration
617                                .installing_worker
618                                .as_ref()
619                                .map(|worker| worker.id),
620                            waiting_worker: registration
621                                .waiting_worker
622                                .as_ref()
623                                .map(|worker| worker.id),
624                            active_worker: registration
625                                .active_worker
626                                .as_ref()
627                                .map(|worker| worker.id),
628                        },
629                    )),
630                ));
631            }
632        } else {
633            // Step 6: Else
634            // Step 6.1: Invoke Set Registration algorithm with job’s storage key, job’s scope url, and job’s update via cache mode.
635            let new_registration = ServiceWorkerRegistration::new(job.client.clone());
636            self.registrations
637                .insert(job.scope_url.clone(), new_registration);
638
639            // Step 7: Invoke Update algorithm passing job as the argument.
640            job.job_type = JobType::Update;
641            self.handle_update_job(job);
642        }
643    }
644
645    /// <https://w3c.github.io/ServiceWorker/#update-worker-state>
646    fn update_worker_state(&mut self, worker: &mut ServiceWorker, state: ServiceWorkerState) {
647        // Step 1: Assert: state is not "parsed".
648        debug_assert!(!matches!(state, ServiceWorkerState::Parsed));
649
650        // Step 2: Set worker’s state to state.
651        worker.state = state.clone();
652
653        // Step 3: Let settingsObjects be all environment settings objects whose origin is worker’s script url’s origin.
654        // Step 4: For each settingsObject of settingsObjects, queue a task on settingsObject’s responsible event loop.
655        // Note: task will be queued to all pipelines for the script origin by the constellation.
656        let origin = worker.script_url.origin();
657        if self
658            .constellation_sender
659            .send(ServiceWorkerManagerMsg::UpdateWorkerState {
660                worker_id: worker.id,
661                state,
662                origin,
663            })
664            .is_err()
665        {
666            error!("Failed to send UpdateWorkerState message to constellation.");
667        }
668    }
669
670    /// <https://www.w3.org/TR/service-workers/#install>
671    fn install(&mut self, job: Job, mut new_worker: ServiceWorker) {
672        // Step 5: Run the Update Worker State algorithm
673        // passing registration’s installing worker and "installing" as the arguments.
674        // Note: running now so that the worker passed to the registration below is in the right state.
675        // TODO: review how workers are passed around and mutated in this module.
676        self.update_worker_state(&mut new_worker, ServiceWorkerState::Installing);
677
678        let (registration_id, installing_worker_id, waiting_worker_id, active_worker_id) = {
679            let Some(registration) = self.registrations.get_mut(&job.scope_url) else {
680                error!("Registration should exist when installing a worker.");
681                return;
682            };
683
684            // Step 4: Run the Update Registration State algorithm passing registration, "installing" and worker as the arguments.
685            registration.update_registration_state(
686                RegistrationUpdateTarget::Installing,
687                Some(new_worker.clone()),
688            );
689            (
690                registration.id,
691                registration
692                    .installing_worker
693                    .as_ref()
694                    .map(|worker| worker.id),
695                registration.waiting_worker.as_ref().map(|worker| worker.id),
696                registration.active_worker.as_ref().map(|worker| worker.id),
697            )
698        };
699
700        // Step 7: Invoke Resolve Job Promise with job and registration
701        let client = job.client.clone();
702        if client
703            .send(ServiceWorkerAlgorithmResult::Job(
704                JobResult::ResolvePromise(JobResultValue::Register(
705                    ServiceWorkerRegistrationInfo {
706                        scope_url: job.scope_url.clone(),
707                        storage_key: job.storage_key.clone(),
708                        script_url: job.script_url.clone(),
709                        id: registration_id,
710                        installing_worker: installing_worker_id,
711                        waiting_worker: waiting_worker_id,
712                        active_worker: active_worker_id,
713                    },
714                )),
715            ))
716            .is_err()
717        {
718            warn!("Failed to send resolve job promise result to script.");
719        }
720
721        // Step 19: Run the Update Worker State algorithm
722        // passing registration’s waiting worker and "installed" as the arguments.
723        // Note: running here so the worker passed to the registration below is in the right state.
724        self.update_worker_state(&mut new_worker, ServiceWorkerState::Installed);
725
726        let Some(registration) = self.registrations.get_mut(&job.scope_url) else {
727            error!("Registration should exist when installing a worker.");
728            return;
729        };
730
731        // Step 17: Run the Update Registration State algorithm passing registration,
732        // "waiting" and registration’s installing worker as the arguments.
733        registration.update_registration_state(RegistrationUpdateTarget::Waiting, Some(new_worker));
734
735        // Step 18: Run the Update Registration State algorithm passing registration, "installing" and null as the arguments.
736        // TODO: registration.update_registration_state(RegistrationUpdateTarget::Installing, None);
737        // Note: commenting out for now, because it causes errors in tests,
738        // probably because we are still lacking functionality elsewhere.
739
740        // Step 21: Wait for all the tasks queued by Update Worker State invoked in this algorithm to have executed.
741        // Note: the algorithm will continue in the handler for the ServiceWorkerMsg::FinishInstall message.
742    }
743
744    /// <https://w3c.github.io/ServiceWorker/#update>
745    fn handle_update_job(&mut self, job: Job) {
746        // Step 1: Get registation
747        let (job, new_worker) =
748            if let Some(registration) = self.registrations.get_mut(&job.scope_url) {
749                // Step 3.
750                let newest_worker = registration.get_newest_worker();
751
752                // Step 4.
753                if let Some(worker) = newest_worker &&
754                    worker.script_url != job.script_url
755                {
756                    let _ = job.client.send(ServiceWorkerAlgorithmResult::Job(
757                        JobResult::RejectPromise(JobError::TypeError),
758                    ));
759                    return;
760                }
761
762                let scope_things = job
763                    .scope_things
764                    .clone()
765                    .expect("Update job should have scope things.");
766
767                // Very roughly steps 5 to 18.
768                // TODO: implement all steps precisely.
769                let (new_worker, join_handle, control_sender, context, closing) =
770                    update_serviceworker(
771                        self.own_sender.clone(),
772                        job.scope_url.clone(),
773                        scope_things,
774                        self.font_context.clone(),
775                    );
776
777                // Since we've just started the worker thread, ensure we can shut it down later.
778                registration.note_worker_thread(join_handle, control_sender, context, closing);
779
780                (job, new_worker)
781            } else {
782                // Step 2
783                let _ =
784                    job.client
785                        .send(ServiceWorkerAlgorithmResult::Job(JobResult::RejectPromise(
786                            JobError::TypeError,
787                        )));
788                return;
789            };
790        // Step 17: Else, invoke Install algorithm with job, worker, and registration as its arguments.
791        self.install(job, new_worker);
792    }
793}
794
795/// <https://w3c.github.io/ServiceWorker/#update-algorithm>
796fn update_serviceworker(
797    own_sender: GenericSender<ServiceWorkerMsg>,
798    scope_url: ServoUrl,
799    mut scope_things: ScopeThings,
800    font_context: Arc<FontContext>,
801) -> (
802    ServiceWorker,
803    JoinHandle<()>,
804    Sender<ServiceWorkerControlMsg>,
805    ThreadSafeJSContext,
806    Arc<AtomicBool>,
807) {
808    let (sender, receiver) = unbounded();
809    #[cfg(feature = "devtools")]
810    let devtools_receiver = {
811        use devtools_traits::{DevtoolsPageInfo, ScriptToDevtoolsControlMsg};
812
813        let (devtools_sender, devtools_receiver) = generic_channel::channel().unwrap();
814
815        scope_things.init.from_devtools_sender = Some(devtools_sender);
816
817        if let Some(ref chan) = scope_things.devtools_chan &&
818            let Some(ref sender) = scope_things.init.from_devtools_sender
819        {
820            let page_info = DevtoolsPageInfo {
821                title: format!("Service Worker for {}", scope_things.script_url),
822                url: scope_things.script_url.clone(),
823                is_top_level_global: false,
824                is_service_worker: true,
825            };
826            let _ = chan.send(ScriptToDevtoolsControlMsg::NewGlobal(
827                (
828                    scope_things.browsing_context_id,
829                    scope_things.init.pipeline_id,
830                    Some(scope_things.worker_id),
831                    scope_things.webview_id,
832                ),
833                sender.clone(),
834                page_info,
835            ));
836        }
837
838        Some(devtools_receiver)
839    };
840
841    #[cfg(not(feature = "devtools"))]
842    let devtools_receiver = None;
843
844    let worker_id = ServiceWorkerId::new();
845
846    let (control_sender, control_receiver) = unbounded();
847    let (context_sender, context_receiver) = unbounded();
848    let closing = Arc::new(AtomicBool::new(false));
849
850    let join_handle = ServiceWorkerGlobalScope::run_serviceworker_scope(
851        scope_things.clone(),
852        sender.clone(),
853        receiver,
854        devtools_receiver,
855        own_sender,
856        scope_url,
857        control_receiver,
858        context_sender,
859        closing.clone(),
860        font_context,
861        worker_id,
862    );
863
864    let context = context_receiver
865        .recv()
866        .expect("Couldn't receive a context for worker.");
867
868    (
869        ServiceWorker::new(scope_things.script_url, sender, worker_id),
870        join_handle,
871        control_sender,
872        context,
873        closing,
874    )
875}
876
877impl ServiceWorkerManagerFactory for ServiceWorkerManager {
878    fn create(sw_senders: SWManagerSenders, origin: ImmutableOrigin) {
879        let (resource_chan, resource_port) = generic_channel::channel().unwrap();
880
881        let SWManagerSenders {
882            constellation_sender,
883            resource_threads,
884            own_sender,
885            receiver,
886            system_font_service_sender,
887            paint_api,
888        } = sw_senders;
889
890        let from_constellation = receiver.route_preserving_errors();
891        let resource_port = resource_port.route_preserving_errors();
892        let _ = resource_threads
893            .core_thread
894            .send(CoreResourceMsg::NetworkMediator(resource_chan, origin));
895
896        let font_context = Arc::new(FontContext::new(
897            Arc::new(system_font_service_sender.to_proxy()),
898            paint_api,
899            resource_threads,
900        ));
901
902        let swmanager_thread = move || {
903            ServiceWorkerManager::new(
904                own_sender,
905                constellation_sender,
906                from_constellation,
907                resource_port,
908                font_context,
909            )
910            .handle_message()
911        };
912        if thread::Builder::new()
913            .name("SvcWorkerManager".to_owned())
914            .spawn(swmanager_thread)
915            .is_err()
916        {
917            warn!("ServiceWorkerManager thread spawning failed");
918        }
919    }
920}
921
922pub(crate) fn serviceworker_enabled() -> bool {
923    pref!(dom_serviceworker_enabled)
924}