-
Notifications
You must be signed in to change notification settings - Fork 6.6k
/
service_worker_context_wrapper.cc
1901 lines (1674 loc) · 70.9 KB
/
service_worker_context_wrapper.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/browser/service_worker/service_worker_context_wrapper.h"
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/barrier_closure.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/lazy_instance.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/metrics/histogram_functions.h"
#include "base/observer_list.h"
#include "base/run_loop.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/task/thread_pool.h"
#include "base/time/time.h"
#include "components/services/storage/service_worker/service_worker_storage_control_impl.h"
#include "content/browser/blob_storage/chrome_blob_storage_context.h"
#include "content/browser/devtools/devtools_instrumentation.h"
#include "content/browser/loader/navigation_url_loader_impl.h"
#include "content/browser/service_worker/embedded_worker_status.h"
#include "content/browser/service_worker/service_worker_container_host.h"
#include "content/browser/service_worker/service_worker_host.h"
#include "content/browser/service_worker/service_worker_object_host.h"
#include "content/browser/service_worker/service_worker_process_manager.h"
#include "content/browser/service_worker/service_worker_quota_client.h"
#include "content/browser/service_worker/service_worker_version.h"
#include "content/browser/storage_partition_impl.h"
#include "content/browser/webui/web_ui_controller_factory_registry.h"
#include "content/public/browser/browser_context.h"
#include "content/public/browser/browser_task_traits.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/global_routing_id.h"
#include "content/public/browser/service_worker_context_observer.h"
#include "content/public/browser/storage_usage_info.h"
#include "content/public/browser/web_ui_url_loader_factory.h"
#include "content/public/browser/webui_config.h"
#include "content/public/browser/webui_config_map.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/origin_util.h"
#include "content/public/common/url_constants.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/self_owned_receiver.h"
#include "net/base/url_util.h"
#include "services/metrics/public/cpp/ukm_source_id.h"
#include "services/network/public/cpp/is_potentially_trustworthy.h"
#include "services/network/public/mojom/client_security_state.mojom.h"
#include "storage/browser/quota/quota_client_type.h"
#include "storage/browser/quota/quota_manager_proxy.h"
#include "storage/browser/quota/special_storage_policy.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/privacy_budget/identifiability_study_settings.h"
#include "third_party/blink/public/common/service_worker/service_worker_scope_match.h"
#include "third_party/blink/public/common/service_worker/service_worker_status_code.h"
#include "third_party/blink/public/common/storage_key/storage_key.h"
#include "third_party/blink/public/mojom/service_worker/service_worker_registration.mojom.h"
namespace content {
namespace {
#if BUILDFLAG(IS_ANDROID)
// Enables running ServiceWorkerStorageControl on IO thread instead of UI thread
// on Android.
BASE_FEATURE(kServiceWorkerStorageControlOnIOThread,
"ServiceWorkerStorageControlOnIOThread",
base::FEATURE_ENABLED_BY_DEFAULT);
#endif
BASE_FEATURE(kServiceWorkerStorageControlOnThreadPool,
"ServiceWorkerStorageControlOnThreadPool",
base::FEATURE_DISABLED_BY_DEFAULT);
base::LazyInstance<ServiceWorkerContextWrapper::URLLoaderFactoryInterceptor>::
Leaky g_loader_factory_interceptor = LAZY_INSTANCE_INITIALIZER;
void DidFindRegistrationForStartActiveWorker(
ServiceWorkerContextWrapper::StatusCallback callback,
blink::ServiceWorkerStatusCode status,
scoped_refptr<ServiceWorkerRegistration> registration) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (status != blink::ServiceWorkerStatusCode::kOk ||
!registration->active_version()) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback),
blink::ServiceWorkerStatusCode::kErrorNotFound));
return;
}
registration->active_version()->StartWorker(
ServiceWorkerMetrics::EventType::UNKNOWN,
base::BindOnce(
[](ServiceWorkerContextWrapper::StatusCallback callback,
blink::ServiceWorkerStatusCode status) {
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), status));
},
std::move(callback)));
}
void DidStartWorker(scoped_refptr<ServiceWorkerVersion> version,
ServiceWorkerContext::StartWorkerCallback info_callback,
ServiceWorkerContext::StatusCodeCallback failure_callback,
blink::ServiceWorkerStatusCode start_worker_status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (start_worker_status != blink::ServiceWorkerStatusCode::kOk) {
std::move(failure_callback).Run(start_worker_status);
return;
}
EmbeddedWorkerInstance* instance = version->embedded_worker();
std::move(info_callback)
.Run(version->version_id(), instance->process_id(),
instance->thread_id());
}
void FoundRegistrationForStartWorker(
ServiceWorkerContext::StartWorkerCallback info_callback,
ServiceWorkerContext::StatusCodeCallback failure_callback,
blink::ServiceWorkerStatusCode service_worker_status,
scoped_refptr<ServiceWorkerRegistration> registration) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (service_worker_status != blink::ServiceWorkerStatusCode::kOk) {
std::move(failure_callback).Run(service_worker_status);
return;
}
ServiceWorkerVersion* version_ptr = registration->active_version()
? registration->active_version()
: registration->installing_version();
// Since FindRegistrationForScope returned
// blink::ServiceWorkerStatusCode::kOk, there must have been either:
// - an active version, which optionally might have activated from a waiting
// version (as DidFindRegistrationForFindImpl will activate any waiting
// version).
// - or an installing version.
// However, if the installation is rejected, the installing version can go
// away by the time we reach here from DidFindRegistrationForFindImpl.
if (!version_ptr) {
std::move(failure_callback).Run(service_worker_status);
return;
}
// Note: There might be a remote possibility that |registration|'s |version|
// might change between here and DidStartWorker, so bind |version| to
// RunAfterStartWorker.
scoped_refptr<ServiceWorkerVersion> version =
base::WrapRefCounted(version_ptr);
version->RunAfterStartWorker(
ServiceWorkerMetrics::EventType::EXTERNAL_REQUEST,
base::BindOnce(&DidStartWorker, version, std::move(info_callback),
std::move(failure_callback)));
}
void RunOnceClosure(scoped_refptr<ServiceWorkerContextWrapper> ref_holder,
base::OnceClosure task) {
std::move(task).Run();
}
// Helper class to create a callback that takes blink::ServiceWorkerStatusCode
// as the first parameter and calls the original callback with a boolean of
// whether the status is blink::ServiceWorkerStatusCode::kOk or not.
class WrapResultCallbackToTakeStatusCode {
public:
explicit WrapResultCallbackToTakeStatusCode(
ServiceWorkerContext::ResultCallback callback)
: callback_(std::move(callback)) {}
template <typename... Args>
operator base::OnceCallback<void(blink::ServiceWorkerStatusCode, Args...)>() {
return Take<Args...>();
}
private:
template <typename... Args>
base::OnceCallback<void(blink::ServiceWorkerStatusCode, Args...)> Take() {
return base::BindOnce(
[](ServiceWorkerContext::ResultCallback callback,
blink::ServiceWorkerStatusCode status, Args...) {
std::move(callback).Run(status ==
blink::ServiceWorkerStatusCode::kOk);
},
std::move(callback_));
}
ServiceWorkerContext::ResultCallback callback_;
};
void RunOrPostTaskOnUIThread(const base::Location& location,
base::OnceClosure task) {
if (BrowserThread::CurrentlyOn(BrowserThread::UI)) {
std::move(task).Run();
} else {
GetUIThreadTaskRunner({})->PostTask(location, std::move(task));
}
}
} // namespace
// static
bool ServiceWorkerContext::ScopeMatches(const GURL& scope, const GURL& url) {
return blink::ServiceWorkerScopeMatches(scope, url);
}
// static
void ServiceWorkerContext::RunTask(
scoped_refptr<base::SequencedTaskRunner> task_runner,
const base::Location& from_here,
ServiceWorkerContext* service_worker_context,
base::OnceClosure task) {
auto ref = base::WrapRefCounted(
static_cast<ServiceWorkerContextWrapper*>(service_worker_context));
task_runner->PostTask(
from_here,
base::BindOnce(&RunOnceClosure, std::move(ref), std::move(task)));
}
ServiceWorkerContextWrapper::ServiceWorkerContextWrapper(
BrowserContext* browser_context)
: core_observer_list_(
base::MakeRefCounted<ServiceWorkerContextObserverList>()),
process_manager_(
std::make_unique<ServiceWorkerProcessManager>(browser_context)) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Add this object as an observer of the wrapped |context_core_|. This lets us
// forward observer methods to observers outside of content.
core_observer_list_->AddObserver(this);
if (blink::IdentifiabilityStudySettings::Get()->IsActive()) {
identifiability_metrics_ =
std::make_unique<ServiceWorkerIdentifiabilityMetrics>();
core_observer_list_->AddObserver(identifiability_metrics_.get());
}
}
void ServiceWorkerContextWrapper::Init(
const base::FilePath& user_data_directory,
storage::QuotaManagerProxy* quota_manager_proxy,
storage::SpecialStoragePolicy* special_storage_policy,
ChromeBlobStorageContext* blob_context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
DCHECK(storage_partition_);
is_incognito_ = user_data_directory.empty();
user_data_directory_ = user_data_directory;
quota_manager_proxy_ = quota_manager_proxy;
InitInternal(quota_manager_proxy, special_storage_policy, blob_context,
storage_partition_->browser_context());
}
void ServiceWorkerContextWrapper::InitInternal(
storage::QuotaManagerProxy* quota_manager_proxy,
storage::SpecialStoragePolicy* special_storage_policy,
ChromeBlobStorageContext* blob_context,
BrowserContext* browser_context) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
std::unique_ptr<blink::PendingURLLoaderFactoryBundle>
non_network_pending_loader_factory_bundle_for_update_check;
non_network_pending_loader_factory_bundle_for_update_check =
CreateNonNetworkPendingURLLoaderFactoryBundleForUpdateCheck(
browser_context);
context_core_ = std::make_unique<ServiceWorkerContextCore>(
quota_manager_proxy, special_storage_policy,
std::move(non_network_pending_loader_factory_bundle_for_update_check),
core_observer_list_.get(), this);
}
void ServiceWorkerContextWrapper::Shutdown() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
ClearRunningServiceWorkers();
storage_partition_ = nullptr;
process_manager_->Shutdown();
storage_control_.reset();
context_core_.reset();
}
void ServiceWorkerContextWrapper::DeleteAndStartOver() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
// The context could be null due to system shutdown or restart failure. In
// either case, we should not have to recover the system, so just return
// here.
return;
}
context_core_->DeleteAndStartOver(base::BindOnce(
&ServiceWorkerContextWrapper::DidDeleteAndStartOver, this));
}
StoragePartitionImpl* ServiceWorkerContextWrapper::storage_partition() const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return storage_partition_;
}
void ServiceWorkerContextWrapper::set_storage_partition(
StoragePartitionImpl* storage_partition) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
storage_partition_ = storage_partition;
process_manager_->set_storage_partition(storage_partition_);
}
BrowserContext* ServiceWorkerContextWrapper::browser_context() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return process_manager()->browser_context();
}
void ServiceWorkerContextWrapper::OnRegistrationCompleted(
int64_t registration_id,
const GURL& scope,
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnRegistrationCompleted(scope);
}
void ServiceWorkerContextWrapper::OnRegistrationStored(
int64_t registration_id,
const GURL& scope,
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnRegistrationStored(registration_id, scope);
}
void ServiceWorkerContextWrapper::OnAllRegistrationsDeletedForStorageKey(
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
}
void ServiceWorkerContextWrapper::OnErrorReported(
int64_t version_id,
const GURL& scope,
const blink::StorageKey& key,
const ServiceWorkerContextObserver::ErrorInfo& info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnErrorReported(version_id, scope, info);
}
void ServiceWorkerContextWrapper::OnReportConsoleMessage(
int64_t version_id,
const GURL& scope,
const blink::StorageKey& key,
const ConsoleMessage& message) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnReportConsoleMessage(version_id, scope, message);
}
void ServiceWorkerContextWrapper::OnControlleeAdded(
int64_t version_id,
const std::string& client_uuid,
const ServiceWorkerClientInfo& client_info) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnControlleeAdded(version_id, client_uuid, client_info);
}
void ServiceWorkerContextWrapper::OnControlleeRemoved(
int64_t version_id,
const std::string& client_uuid) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnControlleeRemoved(version_id, client_uuid);
}
void ServiceWorkerContextWrapper::OnNoControllees(
int64_t version_id,
const GURL& scope,
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnNoControllees(version_id, scope);
}
void ServiceWorkerContextWrapper::OnControlleeNavigationCommitted(
int64_t version_id,
const std::string& uuid,
GlobalRenderFrameHostId render_frame_host_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
for (auto& observer : observer_list_)
observer.OnControlleeNavigationCommitted(version_id, uuid,
render_frame_host_id);
}
void ServiceWorkerContextWrapper::OnStarted(
int64_t version_id,
const GURL& scope,
int process_id,
const GURL& script_url,
const blink::ServiceWorkerToken& token,
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (is_deleting_and_starting_over_)
return;
auto insertion_result = running_service_workers_.insert(std::make_pair(
version_id,
ServiceWorkerRunningInfo(script_url, scope, key, process_id, token)));
DCHECK(insertion_result.second);
const auto& running_info = insertion_result.first->second;
for (auto& observer : observer_list_)
observer.OnVersionStartedRunning(version_id, running_info);
}
void ServiceWorkerContextWrapper::OnStopped(int64_t version_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
auto it = running_service_workers_.find(version_id);
if (it != running_service_workers_.end()) {
running_service_workers_.erase(it);
for (auto& observer : observer_list_)
observer.OnVersionStoppedRunning(version_id);
}
}
void ServiceWorkerContextWrapper::OnDeleteAndStartOver() {
is_deleting_and_starting_over_ = true;
ClearRunningServiceWorkers();
}
void ServiceWorkerContextWrapper::OnVersionStateChanged(
int64_t version_id,
const GURL& scope,
const blink::StorageKey& key,
ServiceWorkerVersion::Status status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (status == ServiceWorkerVersion::Status::ACTIVATED) {
for (auto& observer : observer_list_)
observer.OnVersionActivated(version_id, scope);
} else if (status == ServiceWorkerVersion::Status::REDUNDANT) {
for (auto& observer : observer_list_)
observer.OnVersionRedundant(version_id, scope);
}
}
void ServiceWorkerContextWrapper::AddObserver(
ServiceWorkerContextObserver* observer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
observer_list_.AddObserver(observer);
}
void ServiceWorkerContextWrapper::RemoveObserver(
ServiceWorkerContextObserver* observer) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
observer_list_.RemoveObserver(observer);
}
void ServiceWorkerContextWrapper::RegisterServiceWorker(
const GURL& script_url,
const blink::StorageKey& key,
const blink::mojom::ServiceWorkerRegistrationOptions& options,
StatusCodeCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE,
base::BindOnce(
std::move(callback),
blink::ServiceWorkerStatusCode::kErrorStartWorkerFailed));
return;
}
blink::mojom::ServiceWorkerRegistrationOptions options_to_pass(
net::SimplifyUrlForRequest(options.scope), options.type,
options.update_via_cache);
// TODO(https://crbug.com/1239551): initialize remaining fields
PolicyContainerPolicies policy_container_policies;
policy_container_policies.is_web_secure_context =
network::IsUrlPotentiallyTrustworthy(script_url);
// TODO(bashi): Pass a valid outside fetch client settings object. Perhaps
// changing this method to take a settings object.
context()->RegisterServiceWorker(
net::SimplifyUrlForRequest(script_url), key, options_to_pass,
blink::mojom::FetchClientSettingsObject::New(
network::mojom::ReferrerPolicy::kDefault,
/*outgoing_referrer=*/script_url,
blink::mojom::InsecureRequestsPolicy::kDoNotUpgrade),
base::BindOnce(
[](StatusCodeCallback callback, blink::ServiceWorkerStatusCode status,
const std::string&, int64_t) { std::move(callback).Run(status); },
std::move(callback)),
/*requesting_frame_id=*/GlobalRenderFrameHostId(),
policy_container_policies);
}
void ServiceWorkerContextWrapper::UnregisterServiceWorker(
const GURL& scope,
const blink::StorageKey& key,
ResultCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), false));
return;
}
context()->UnregisterServiceWorker(
net::SimplifyUrlForRequest(scope), key, /*is_immediate=*/false,
WrapResultCallbackToTakeStatusCode(std::move(callback)));
}
ServiceWorkerExternalRequestResult
ServiceWorkerContextWrapper::StartingExternalRequest(
int64_t service_worker_version_id,
ServiceWorkerExternalRequestTimeoutType timeout_type,
const std::string& request_uuid) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context())
return ServiceWorkerExternalRequestResult::kNullContext;
scoped_refptr<ServiceWorkerVersion> version =
context()->GetLiveVersion(service_worker_version_id);
if (!version)
return ServiceWorkerExternalRequestResult::kWorkerNotFound;
return version->StartExternalRequest(request_uuid, timeout_type);
}
bool ServiceWorkerContextWrapper::ExecuteScriptForTest(
const std::string& script,
int64_t service_worker_version_id,
ServiceWorkerScriptExecutionCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context())
return false;
scoped_refptr<ServiceWorkerVersion> version =
context()->GetLiveVersion(service_worker_version_id);
if (!version)
return false;
version->ExecuteScriptForTest(script, std::move(callback)); // IN-TEST
return true;
}
ServiceWorkerExternalRequestResult
ServiceWorkerContextWrapper::FinishedExternalRequest(
int64_t service_worker_version_id,
const std::string& request_uuid) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context())
return ServiceWorkerExternalRequestResult::kNullContext;
scoped_refptr<ServiceWorkerVersion> version =
context()->GetLiveVersion(service_worker_version_id);
if (!version)
return ServiceWorkerExternalRequestResult::kWorkerNotFound;
return version->FinishExternalRequest(request_uuid);
}
size_t ServiceWorkerContextWrapper::CountExternalRequestsForTest(
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
std::vector<ServiceWorkerVersionInfo> live_version_info =
GetAllLiveVersionInfo();
for (const ServiceWorkerVersionInfo& info : live_version_info) {
ServiceWorkerVersion* version = GetLiveVersion(info.version_id);
if (version && version->key() == key) {
return version->GetExternalRequestCountForTest(); // IN-TEST
}
}
return 0u;
}
bool ServiceWorkerContextWrapper::MaybeHasRegistrationForStorageKey(
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return context() ? context()->MaybeHasRegistrationForStorageKey(key) : true;
}
void ServiceWorkerContextWrapper::GetAllStorageKeysInfo(
GetUsageInfoCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), std::vector<StorageUsageInfo>()));
return;
}
context()->registry()->GetAllRegistrationsInfos(base::BindOnce(
&ServiceWorkerContextWrapper::DidGetAllRegistrationsForGetAllStorageKeys,
this, std::move(callback)));
}
void ServiceWorkerContextWrapper::DeleteForStorageKey(
const blink::StorageKey& key,
ResultCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Ensure the callback is called asynchronously.
scoped_refptr<base::TaskRunner> callback_runner = GetUIThreadTaskRunner({});
if (!context_core_) {
callback_runner->PostTask(FROM_HERE,
base::BindOnce(std::move(callback), false));
return;
}
context()->DeleteForStorageKey(
key,
base::BindOnce(
[](ResultCallback callback,
scoped_refptr<base::TaskRunner> callback_runner,
blink::ServiceWorkerStatusCode status) {
callback_runner->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback),
status == blink::ServiceWorkerStatusCode::kOk));
},
std::move(callback), std::move(callback_runner)));
}
void ServiceWorkerContextWrapper::CheckHasServiceWorker(
const GURL& url,
const blink::StorageKey& key,
CheckHasServiceWorkerCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// Checking OriginCanAccessServiceWorkers() is for performance optimization.
// Without this check, following FindRegistrationForClientUrl() can detect if
// the given URL has service worker registration or not. But
// FindRegistrationForClientUrl() takes time to compute. Hence avoid calling
// it when the given URL clearly doesn't register service workers.
if (!context_core_ || !OriginCanAccessServiceWorkers(url)) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback),
ServiceWorkerCapability::NO_SERVICE_WORKER));
return;
}
DCHECK(url.is_valid());
TRACE_EVENT1("ServiceWorker",
"ServiceWorkerContextWrapper::CheckHasServiceWorker", "url",
url.spec());
context()->CheckHasServiceWorker(net::SimplifyUrlForRequest(url), key,
std::move(callback));
}
void ServiceWorkerContextWrapper::CheckOfflineCapability(
const GURL& url,
const blink::StorageKey& key,
CheckOfflineCapabilityCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), OfflineCapability::kUnsupported,
blink::mojom::kInvalidServiceWorkerRegistrationId));
return;
}
context()->CheckOfflineCapability(net::SimplifyUrlForRequest(url), key,
std::move(callback));
}
void ServiceWorkerContextWrapper::ClearAllServiceWorkersForTest(
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(callback));
return;
}
context_core_->ClearAllServiceWorkersForTest(std::move(callback));
}
void ServiceWorkerContextWrapper::StartWorkerForScope(
const GURL& scope,
const blink::StorageKey& key,
StartWorkerCallback info_callback,
StatusCodeCallback failure_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
FindRegistrationForScopeImpl(
scope, key,
/*include_installing_version=*/true,
base::BindOnce(&FoundRegistrationForStartWorker, std::move(info_callback),
std::move(failure_callback)));
}
void ServiceWorkerContextWrapper::StartServiceWorkerAndDispatchMessage(
const GURL& scope,
const blink::StorageKey& key,
blink::TransferableMessage message,
ResultCallback result_callback) {
// Ensure the callback is called asynchronously.
auto wrapped_callback = base::BindOnce(
[](ResultCallback callback, bool success) {
GetUIThreadTaskRunner({})->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), success));
},
std::move(result_callback));
// As we don't track tasks between workers and renderers, we can nullify the
// message's parent task ID.
message.parent_task_id = absl::nullopt;
// TODO(https://crbug.com/1295029): Don't post task to the UI thread. Instead,
// make all call sites run on the UI thread.
RunOrPostTaskOnUIThread(
FROM_HERE,
base::BindOnce(&ServiceWorkerContextWrapper::
StartServiceWorkerAndDispatchMessageOnUIThread,
this, scope, key, std::move(message),
base::BindOnce(
[](ResultCallback callback,
scoped_refptr<base::TaskRunner> callback_runner,
bool success) {
callback_runner->PostTask(
FROM_HERE,
base::BindOnce(std::move(callback), success));
},
std::move(wrapped_callback),
base::SingleThreadTaskRunner::GetCurrentDefault())));
}
void ServiceWorkerContextWrapper::
StartServiceWorkerAndDispatchMessageOnUIThread(
const GURL& scope,
const blink::StorageKey& key,
blink::TransferableMessage message,
ResultCallback result_callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
std::move(result_callback).Run(/*success=*/false);
return;
}
FindRegistrationForScopeImpl(
net::SimplifyUrlForRequest(scope), key,
/*include_installing_version=*/false,
base::BindOnce(
&ServiceWorkerContextWrapper::DidFindRegistrationForMessageDispatch,
this, std::move(message), scope, std::move(result_callback)));
}
void ServiceWorkerContextWrapper::DidFindRegistrationForMessageDispatch(
blink::TransferableMessage message,
const GURL& source_origin,
ResultCallback result_callback,
blink::ServiceWorkerStatusCode service_worker_status,
scoped_refptr<ServiceWorkerRegistration> registration) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (service_worker_status != blink::ServiceWorkerStatusCode::kOk) {
LOG(WARNING) << "No registration available, status: "
<< static_cast<int>(service_worker_status);
std::move(result_callback).Run(/*success=*/false);
return;
}
registration->active_version()->StartWorker(
ServiceWorkerMetrics::EventType::MESSAGE,
base::BindOnce(
&ServiceWorkerContextWrapper::DidStartServiceWorkerForMessageDispatch,
this, std::move(message), source_origin, registration,
std::move(result_callback)));
}
void ServiceWorkerContextWrapper::DidStartServiceWorkerForMessageDispatch(
blink::TransferableMessage message,
const GURL& source_origin,
scoped_refptr<ServiceWorkerRegistration> registration,
ResultCallback result_callback,
blink::ServiceWorkerStatusCode status) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (status != blink::ServiceWorkerStatusCode::kOk) {
std::move(result_callback).Run(/*success=*/false);
return;
}
scoped_refptr<ServiceWorkerVersion> version = registration->active_version();
blink::mojom::ExtendableMessageEventPtr event =
blink::mojom::ExtendableMessageEvent::New();
event->message = std::move(message);
event->source_origin = url::Origin::Create(source_origin);
event->source_info_for_service_worker =
version->worker_host()
->container_host()
->GetOrCreateServiceWorkerObjectHost(version)
->CreateCompleteObjectInfoToSend();
int request_id = version->StartRequest(
ServiceWorkerMetrics::EventType::MESSAGE,
WrapResultCallbackToTakeStatusCode(std::move(result_callback)));
version->endpoint()->DispatchExtendableMessageEvent(
std::move(event), version->CreateSimpleEventCallback(request_id));
}
void ServiceWorkerContextWrapper::StartServiceWorkerForNavigationHint(
const GURL& document_url,
const blink::StorageKey& key,
StartServiceWorkerForNavigationHintCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
std::move(callback).Run(StartServiceWorkerForNavigationHintResult::FAILED);
return;
}
// Checking this is for performance optimization. Without this check,
// following FindRegistrationForClientUrl() can detect if the given URL has
// service worker registration or not. But FindRegistrationForClientUrl()
// takes time to compute. Hence avoid calling it when the given URL clearly
// doesn't register service workers.
if (!OriginCanAccessServiceWorkers(document_url)) {
std::move(callback).Run(StartServiceWorkerForNavigationHintResult::
NO_SERVICE_WORKER_REGISTRATION);
return;
}
DCHECK(document_url.is_valid());
TRACE_EVENT1("ServiceWorker", "StartServiceWorkerForNavigationHint",
"document_url", document_url.spec());
context_core_->registry()->FindRegistrationForClientUrl(
ServiceWorkerRegistry::Purpose::kNotForNavigation,
net::SimplifyUrlForRequest(document_url), key,
base::BindOnce(
&ServiceWorkerContextWrapper::DidFindRegistrationForNavigationHint,
this, std::move(callback)));
}
void ServiceWorkerContextWrapper::WarmUpServiceWorker(
const GURL& document_url,
const blink::StorageKey& key,
ServiceWorkerContextCore::WarmUpServiceWorkerCallback callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
std::move(callback).Run();
return;
}
// Checking this is for performance optimization. Without this check,
// following FindRegistrationForClientUrl() can detect if the given URL has
// service worker registration or not. But FindRegistrationForClientUrl()
// takes time to compute. Hence avoid calling it when the given URL clearly
// doesn't register service workers.
if (!OriginCanAccessServiceWorkers(document_url)) {
std::move(callback).Run();
return;
}
context_core_->AddWarmUpRequest(document_url, key, std::move(callback));
// If a service worker warm-up process is already running, do not call
// `MaybeProcessPendingWarmUpRequest()` here. Instead, expect that
// `MaybeProcessPendingWarmUpRequest()` will be called at the end of the
// current warm-up process.
if (!context_core_->IsProcessingWarmingUp()) {
MaybeProcessPendingWarmUpRequest();
}
}
void ServiceWorkerContextWrapper::StopAllServiceWorkersForStorageKey(
const blink::StorageKey& key) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_.get()) {
return;
}
std::vector<ServiceWorkerVersionInfo> live_versions = GetAllLiveVersionInfo();
for (const ServiceWorkerVersionInfo& info : live_versions) {
ServiceWorkerVersion* version = GetLiveVersion(info.version_id);
if (version && version->key() == key)
version->StopWorker(base::DoNothing());
}
}
void ServiceWorkerContextWrapper::StopAllServiceWorkers(
base::OnceClosure callback) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_.get()) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(callback));
return;
}
std::vector<ServiceWorkerVersionInfo> live_versions = GetAllLiveVersionInfo();
base::RepeatingClosure barrier =
base::BarrierClosure(live_versions.size(), std::move(callback));
for (const ServiceWorkerVersionInfo& info : live_versions) {
ServiceWorkerVersion* version = GetLiveVersion(info.version_id);
DCHECK(version);
version->StopWorker(barrier);
}
}
const base::flat_map<int64_t, ServiceWorkerRunningInfo>&
ServiceWorkerContextWrapper::GetRunningServiceWorkerInfos() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
return running_service_workers_;
}
bool ServiceWorkerContextWrapper::IsLiveRunningServiceWorker(
int64_t service_worker_version_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
// We might be shutting down.
if (!context())
return false;
auto* version = context()->GetLiveVersion(service_worker_version_id);
if (!version)
return false;
auto running_status = version->running_status();
if (running_status != EmbeddedWorkerStatus::STARTING &&
running_status != EmbeddedWorkerStatus::RUNNING) {
return false;
}
return true;
}
service_manager::InterfaceProvider&
ServiceWorkerContextWrapper::GetRemoteInterfaces(
int64_t service_worker_version_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
CHECK(IsLiveRunningServiceWorker(service_worker_version_id));
// This function should only be called on live running service workers
// so it should be safe to dereference the returned pointer without
// checking it first.
auto& version = *context()->GetLiveVersion(service_worker_version_id);
return version.worker_host()->remote_interfaces();
}
scoped_refptr<ServiceWorkerRegistration>
ServiceWorkerContextWrapper::GetLiveRegistration(int64_t registration_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_)
return nullptr;
return context_core_->GetLiveRegistration(registration_id);
}
ServiceWorkerVersion* ServiceWorkerContextWrapper::GetLiveVersion(
int64_t version_id) {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_)
return nullptr;
return context_core_->GetLiveVersion(version_id);
}
std::vector<ServiceWorkerRegistrationInfo>
ServiceWorkerContextWrapper::GetAllLiveRegistrationInfo() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_)
return std::vector<ServiceWorkerRegistrationInfo>();
return context_core_->GetAllLiveRegistrationInfo();
}
std::vector<ServiceWorkerVersionInfo>
ServiceWorkerContextWrapper::GetAllLiveVersionInfo() {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_)
return std::vector<ServiceWorkerVersionInfo>();
return context_core_->GetAllLiveVersionInfo();
}
void ServiceWorkerContextWrapper::HasMainFrameWindowClient(
const blink::StorageKey& key,
BoolCallback callback) const {
DCHECK_CURRENTLY_ON(BrowserThread::UI);
if (!context_core_) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), false));
return;
}
context_core_->HasMainFrameWindowClient(key, std::move(callback));
}