summaryrefslogtreecommitdiff
path: root/chromium/third_party/blink/renderer/core/workers
diff options
context:
space:
mode:
Diffstat (limited to 'chromium/third_party/blink/renderer/core/workers')
-rw-r--r--chromium/third_party/blink/renderer/core/workers/BUILD.gn11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/abstract_worker.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc134
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker.h20
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc14
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h19
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc37
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc26
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h3
-rw-r--r--chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc55
-rw-r--r--chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h42
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/README.md8
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.cc478
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.h178
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc121
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h49
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc115
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h38
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc80
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h46
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc69
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h65
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h23
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc27
-rw-r--r--chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h16
-rw-r--r--chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc11
-rw-r--r--chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h8
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc3
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl2
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h1
-rw-r--r--chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc92
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h4
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h1
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc15
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h5
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker.idl6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h13
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc78
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h27
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_clients.h7
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc171
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.h48
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl3
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc164
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h72
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_location.h6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_location.idl10
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc5
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_navigator.h6
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc81
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h44
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread.cc112
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread.h46
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc16
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h17
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet.cc9
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet.h19
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc13
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h12
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc1
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc17
-rw-r--r--chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc3
87 files changed, 1781 insertions, 1220 deletions
diff --git a/chromium/third_party/blink/renderer/core/workers/BUILD.gn b/chromium/third_party/blink/renderer/core/workers/BUILD.gn
index 3c36f4d8f1e..eef62db95d7 100644
--- a/chromium/third_party/blink/renderer/core/workers/BUILD.gn
+++ b/chromium/third_party/blink/renderer/core/workers/BUILD.gn
@@ -18,12 +18,17 @@ blink_core_sources("workers") {
"dedicated_worker_object_proxy.h",
"dedicated_worker_thread.cc",
"dedicated_worker_thread.h",
- "execution_context_worker_registry.cc",
- "execution_context_worker_registry.h",
"experimental/task.cc",
"experimental/task.h",
+ "experimental/task_worklet.cc",
+ "experimental/task_worklet.h",
+ "experimental/task_worklet_global_scope.cc",
+ "experimental/task_worklet_global_scope.h",
"experimental/thread_pool.cc",
"experimental/thread_pool.h",
+ "experimental/thread_pool_thread.cc",
+ "experimental/thread_pool_thread.h",
+ "experimental/window_task_worklet.h",
"experimental/worker_task_queue.cc",
"experimental/worker_task_queue.h",
"global_scope_creation_params.cc",
@@ -66,8 +71,6 @@ blink_core_sources("workers") {
"worker_content_settings_client.h",
"worker_global_scope.cc",
"worker_global_scope.h",
- "worker_inspector_proxy.cc",
- "worker_inspector_proxy.h",
"worker_location.h",
"worker_module_tree_client.cc",
"worker_module_tree_client.h",
diff --git a/chromium/third_party/blink/renderer/core/workers/abstract_worker.h b/chromium/third_party/blink/renderer/core/workers/abstract_worker.h
index baa93fa0c87..0806f823087 100644
--- a/chromium/third_party/blink/renderer/core/workers/abstract_worker.h
+++ b/chromium/third_party/blink/renderer/core/workers/abstract_worker.h
@@ -57,7 +57,7 @@ class CORE_EXPORT AbstractWorker : public EventTargetWithInlineData,
return ContextLifecycleObserver::GetExecutionContext();
}
- DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error);
+ DEFINE_STATIC_ATTRIBUTE_EVENT_LISTENER(error, kError);
AbstractWorker(ExecutionContext*);
~AbstractWorker() override;
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
index a058c4ba3d8..9a26e641af3 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.cc
@@ -8,6 +8,7 @@
#include "services/network/public/mojom/fetch_api.mojom-blink.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/dedicated_worker_factory.mojom-blink.h"
#include "third_party/blink/public/platform/web_content_settings_client.h"
#include "third_party/blink/public/platform/web_layer_tree_view.h"
@@ -20,6 +21,7 @@
#include "third_party/blink/renderer/core/frame/local_frame_client.h"
#include "third_party/blink/renderer/core/frame/use_counter.h"
#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h"
+#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/messaging/post_message_options.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/page/page.h"
@@ -33,6 +35,7 @@
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/script_state.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
+#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
namespace blink {
@@ -56,7 +59,7 @@ ConnectToWorkerInterfaceProvider(
DedicatedWorker* DedicatedWorker::Create(ExecutionContext* context,
const String& url,
- const WorkerOptions& options,
+ const WorkerOptions* options,
ExceptionState& exception_state) {
DCHECK(context->IsContextThread());
UseCounter::Count(context, WebFeature::kWorkerStart);
@@ -76,7 +79,7 @@ DedicatedWorker* DedicatedWorker::Create(ExecutionContext* context,
// TODO(nhiroki): Remove this flag check once module loading for
// DedicatedWorker is enabled by default (https://crbug.com/680046).
- if (options.type() == "module" &&
+ if (options->type() == "module" &&
!RuntimeEnabledFeatures::ModuleDedicatedWorkerEnabled()) {
exception_state.ThrowTypeError(
"Module scripts are not supported on DedicatedWorker yet. You can try "
@@ -88,19 +91,20 @@ DedicatedWorker* DedicatedWorker::Create(ExecutionContext* context,
if (context->IsWorkerGlobalScope())
UseCounter::Count(context, WebFeature::kNestedDedicatedWorker);
- DedicatedWorker* worker =
- new DedicatedWorker(context, script_request_url, options);
+ DedicatedWorker* worker = MakeGarbageCollected<DedicatedWorker>(
+ context, script_request_url, options);
worker->Start();
return worker;
}
DedicatedWorker::DedicatedWorker(ExecutionContext* context,
const KURL& script_request_url,
- const WorkerOptions& options)
+ const WorkerOptions* options)
: AbstractWorker(context),
script_request_url_(script_request_url),
options_(options),
- context_proxy_(new DedicatedWorkerMessagingProxy(context, this)) {
+ context_proxy_(
+ MakeGarbageCollected<DedicatedWorkerMessagingProxy>(context, this)) {
DCHECK(context->IsContextThread());
DCHECK(script_request_url_.IsValid());
DCHECK(context_proxy_);
@@ -115,15 +119,15 @@ void DedicatedWorker::postMessage(ScriptState* script_state,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- PostMessageOptions options;
+ PostMessageOptions* options = PostMessageOptions::Create();
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(script_state, message, options, exception_state);
}
void DedicatedWorker::postMessage(ScriptState* script_state,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
ExceptionState& exception_state) {
DCHECK(GetExecutionContext()->IsContextThread());
@@ -163,43 +167,37 @@ void DedicatedWorker::Start() {
ThreadDebugger::From(ToIsolate(GetExecutionContext()))
->StoreCurrentStackTrace("Worker Created");
- // Step 13: "Obtain script by switching on the value of options's type
- // member:"
- if (options_.type() == "classic") {
- // "classic: Fetch a classic worker script given url, outside settings,
- // destination, and inside settings."
- network::mojom::FetchRequestMode fetch_request_mode =
- network::mojom::FetchRequestMode::kSameOrigin;
- network::mojom::FetchCredentialsMode fetch_credentials_mode =
- network::mojom::FetchCredentialsMode::kSameOrigin;
- classic_script_loader_ = WorkerClassicScriptLoader::Create();
+ if (RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled() ||
+ options_->type() == "module") {
+ // Specify empty source code here because scripts will be fetched on the
+ // worker thread.
+ auto* outside_settings_object =
+ GetExecutionContext()->CreateFetchClientSettingsObjectSnapshot();
+ context_proxy_->StartWorkerGlobalScope(
+ CreateGlobalScopeCreationParams(
+ script_request_url_, network::mojom::ReferrerPolicy::kDefault),
+ options_, script_request_url_, outside_settings_object, stack_id,
+ String() /* source_code */);
+ return;
+ }
+ if (options_->type() == "classic") {
+ // Legacy code path (to be deprecated, see https://crbug.com/835717):
+ // A worker thread will start after scripts are fetched on the current
+ // thread.
+ classic_script_loader_ = MakeGarbageCollected<WorkerClassicScriptLoader>();
classic_script_loader_->LoadTopLevelScriptAsynchronously(
*GetExecutionContext(), script_request_url_,
- mojom::RequestContextType::WORKER, fetch_request_mode,
- fetch_credentials_mode,
+ mojom::RequestContextType::WORKER,
+ network::mojom::FetchRequestMode::kSameOrigin,
+ network::mojom::FetchCredentialsMode::kSameOrigin,
GetExecutionContext()->GetSecurityContext().AddressSpace(),
+ GetExecutionContext()->IsWorkerGlobalScope(),
WTF::Bind(&DedicatedWorker::OnResponse, WrapPersistent(this)),
WTF::Bind(&DedicatedWorker::OnFinished, WrapPersistent(this),
stack_id));
return;
}
- if (options_.type() == "module") {
- // "module: Fetch a module worker script graph given url, outside settings,
- // destination, the value of the credentials member of options, and inside
- // settings."
- //
- // Specify empty source code here because module scripts will be fetched on
- // the worker thread as opposed to classic scripts that are fetched on the
- // main thread.
- auto* outside_settings_object =
- GetExecutionContext()->CreateFetchClientSettingsObjectSnapshot();
- context_proxy_->StartWorkerGlobalScope(
- CreateGlobalScopeCreationParams(script_request_url_), options_,
- script_request_url_, outside_settings_object, stack_id,
- String() /* source_code */);
- return;
- }
- NOTREACHED() << "Invalid type: " << options_.type();
+ NOTREACHED() << "Invalid type: " << options_->type();
}
void DedicatedWorker::terminate() {
@@ -245,7 +243,7 @@ bool DedicatedWorker::HasPendingActivity() const {
}
const String DedicatedWorker::Name() const {
- return options_.name();
+ return options_->name();
}
WorkerClients* DedicatedWorker::CreateWorkerClients() {
@@ -282,9 +280,10 @@ void DedicatedWorker::OnFinished(const v8_inspector::V8StackTraceId& stack_id) {
if (classic_script_loader_->Canceled()) {
// Do nothing.
} else if (classic_script_loader_->Failed()) {
- DispatchEvent(*Event::CreateCancelable(EventTypeNames::error));
+ DispatchEvent(*Event::CreateCancelable(event_type_names::kError));
} else {
- ReferrerPolicy referrer_policy = kReferrerPolicyDefault;
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
if (!classic_script_loader_->GetReferrerPolicy().IsNull()) {
SecurityPolicy::ReferrerPolicyFromHeaderValue(
classic_script_loader_->GetReferrerPolicy(),
@@ -294,14 +293,11 @@ void DedicatedWorker::OnFinished(const v8_inspector::V8StackTraceId& stack_id) {
DCHECK(script_request_url_ == script_response_url ||
SecurityOrigin::AreSameSchemeHostPort(script_request_url_,
script_response_url));
- std::unique_ptr<GlobalScopeCreationParams> creation_params =
- CreateGlobalScopeCreationParams(script_response_url);
- creation_params->referrer_policy = referrer_policy;
auto* outside_settings_object =
GetExecutionContext()->CreateFetchClientSettingsObjectSnapshot();
context_proxy_->StartWorkerGlobalScope(
- std::move(creation_params), options_, script_response_url,
- outside_settings_object, stack_id,
+ CreateGlobalScopeCreationParams(script_response_url, referrer_policy),
+ options_, script_response_url, outside_settings_object, stack_id,
classic_script_loader_->SourceText());
probe::scriptImported(GetExecutionContext(),
classic_script_loader_->Identifier(),
@@ -311,32 +307,52 @@ void DedicatedWorker::OnFinished(const v8_inspector::V8StackTraceId& stack_id) {
}
std::unique_ptr<GlobalScopeCreationParams>
-DedicatedWorker::CreateGlobalScopeCreationParams(const KURL& script_url) {
- base::UnguessableToken devtools_worker_token;
+DedicatedWorker::CreateGlobalScopeCreationParams(
+ const KURL& script_url,
+ network::mojom::ReferrerPolicy referrer_policy) {
+ base::UnguessableToken parent_devtools_token;
std::unique_ptr<WorkerSettings> settings;
if (auto* document = DynamicTo<Document>(GetExecutionContext())) {
- devtools_worker_token = document->GetFrame()
- ? document->GetFrame()->GetDevToolsFrameToken()
- : base::UnguessableToken::Create();
+ if (document->GetFrame())
+ parent_devtools_token = document->GetFrame()->GetDevToolsFrameToken();
settings = std::make_unique<WorkerSettings>(document->GetSettings());
} else {
WorkerGlobalScope* worker_global_scope =
- ToWorkerGlobalScope(GetExecutionContext());
- devtools_worker_token = worker_global_scope->GetParentDevToolsToken();
+ To<WorkerGlobalScope>(GetExecutionContext());
+ parent_devtools_token =
+ worker_global_scope->GetThread()->GetDevToolsWorkerToken();
settings = WorkerSettings::Copy(worker_global_scope->GetWorkerSettings());
}
- ScriptType script_type = (options_.type() == "classic") ? ScriptType::kClassic
- : ScriptType::kModule;
+ mojom::ScriptType script_type = (options_->type() == "classic")
+ ? mojom::ScriptType::kClassic
+ : mojom::ScriptType::kModule;
+
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context;
+ if (auto* document = DynamicTo<Document>(GetExecutionContext())) {
+ LocalFrame* frame = document->GetFrame();
+ web_worker_fetch_context = frame->Client()->CreateWorkerFetchContext();
+ web_worker_fetch_context->SetApplicationCacheHostID(
+ GetExecutionContext()->Fetcher()->Context().ApplicationCacheHostID());
+ web_worker_fetch_context->SetIsOnSubframe(!frame->IsMainFrame());
+ } else if (auto* scope =
+ DynamicTo<WorkerGlobalScope>(GetExecutionContext())) {
+ web_worker_fetch_context =
+ static_cast<WorkerFetchContext&>(scope->Fetcher()->Context())
+ .GetWebWorkerFetchContext()
+ ->CloneForNestedWorker();
+ }
+
return std::make_unique<GlobalScopeCreationParams>(
script_url, script_type, GetExecutionContext()->UserAgent(),
+ std::move(web_worker_fetch_context),
GetExecutionContext()->GetContentSecurityPolicy()->Headers(),
- kReferrerPolicyDefault, GetExecutionContext()->GetSecurityOrigin(),
+ referrer_policy, GetExecutionContext()->GetSecurityOrigin(),
GetExecutionContext()->IsSecureContext(),
GetExecutionContext()->GetHttpsState(), CreateWorkerClients(),
GetExecutionContext()->GetSecurityContext().AddressSpace(),
OriginTrialContext::GetTokens(GetExecutionContext()).get(),
- devtools_worker_token, std::move(settings), kV8CacheOptionsDefault,
+ parent_devtools_token, std::move(settings), kV8CacheOptionsDefault,
nullptr /* worklet_module_responses_map */,
ConnectToWorkerInterfaceProvider(GetExecutionContext(),
SecurityOrigin::Create(script_url)),
@@ -346,11 +362,13 @@ DedicatedWorker::CreateGlobalScopeCreationParams(const KURL& script_url) {
}
const AtomicString& DedicatedWorker::InterfaceName() const {
- return EventTargetNames::Worker;
+ return event_target_names::kWorker;
}
void DedicatedWorker::Trace(blink::Visitor* visitor) {
visitor->Trace(context_proxy_);
+ visitor->Trace(options_);
+ visitor->Trace(classic_script_loader_);
AbstractWorker::Trace(visitor);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
index 042df39af3d..294f9bf904b 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker.h
@@ -50,9 +50,12 @@ class CORE_EXPORT DedicatedWorker final
public:
static DedicatedWorker* Create(ExecutionContext*,
const String& url,
- const WorkerOptions&,
+ const WorkerOptions*,
ExceptionState&);
+ DedicatedWorker(ExecutionContext*,
+ const KURL& script_request_url,
+ const WorkerOptions*);
~DedicatedWorker() override;
void postMessage(ScriptState*,
@@ -61,7 +64,7 @@ class CORE_EXPORT DedicatedWorker final
ExceptionState&);
void postMessage(ScriptState*,
const ScriptValue& message,
- const PostMessageOptions&,
+ const PostMessageOptions*,
ExceptionState&);
void terminate();
BeginFrameProviderParams CreateBeginFrameProviderParams();
@@ -76,20 +79,17 @@ class CORE_EXPORT DedicatedWorker final
// Returns the name specified by WorkerOptions.
const String Name() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
void Trace(blink::Visitor*) override;
private:
- DedicatedWorker(ExecutionContext*,
- const KURL& script_request_url,
- const WorkerOptions&);
-
// Starts the worker.
void Start();
std::unique_ptr<GlobalScopeCreationParams> CreateGlobalScopeCreationParams(
- const KURL& script_url);
+ const KURL& script_url,
+ network::mojom::ReferrerPolicy);
WorkerClients* CreateWorkerClients();
@@ -101,10 +101,10 @@ class CORE_EXPORT DedicatedWorker final
const AtomicString& InterfaceName() const final;
const KURL script_request_url_;
- const WorkerOptions options_;
+ Member<const WorkerOptions> options_;
const Member<DedicatedWorkerMessagingProxy> context_proxy_;
- scoped_refptr<WorkerClassicScriptLoader> classic_script_loader_;
+ Member<WorkerClassicScriptLoader> classic_script_loader_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc
index 99558a9791d..08de75ba6b2 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.cc
@@ -62,7 +62,11 @@ DedicatedWorkerGlobalScope::DedicatedWorkerGlobalScope(
DedicatedWorkerGlobalScope::~DedicatedWorkerGlobalScope() = default;
const AtomicString& DedicatedWorkerGlobalScope::InterfaceName() const {
- return EventTargetNames::DedicatedWorkerGlobalScope;
+ return event_target_names::kDedicatedWorkerGlobalScope;
+}
+
+bool DedicatedWorkerGlobalScope::IsNestedWorker() const {
+ return static_cast<DedicatedWorkerThread*>(GetThread())->IsNestedWorker();
}
// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
@@ -82,7 +86,7 @@ void DedicatedWorkerGlobalScope::ImportModuleScript(
FetchModuleScript(module_url_record, outside_settings_object, destination,
credentials_mode,
ModuleScriptCustomFetchType::kWorkerConstructor,
- new WorkerModuleTreeClient(modulator));
+ MakeGarbageCollected<WorkerModuleTreeClient>(modulator));
}
const String DedicatedWorkerGlobalScope::name() const {
@@ -93,15 +97,15 @@ void DedicatedWorkerGlobalScope::postMessage(ScriptState* script_state,
const ScriptValue& message,
Vector<ScriptValue>& transfer,
ExceptionState& exception_state) {
- PostMessageOptions options;
+ PostMessageOptions* options = PostMessageOptions::Create();
if (!transfer.IsEmpty())
- options.setTransfer(transfer);
+ options->setTransfer(transfer);
postMessage(script_state, message, options, exception_state);
}
void DedicatedWorkerGlobalScope::postMessage(ScriptState* script_state,
const ScriptValue& message,
- const PostMessageOptions& options,
+ const PostMessageOptions* options,
ExceptionState& exception_state) {
Transferables transferables;
scoped_refptr<SerializedScriptValue> serialized_message =
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h
index 02be7b949de..c73d796d278 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.h
@@ -36,6 +36,7 @@
#include "third_party/blink/renderer/core/messaging/message_port.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/platform/heap/visitor.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -61,6 +62,7 @@ class CORE_EXPORT DedicatedWorkerGlobalScope final : public WorkerGlobalScope {
const AtomicString& InterfaceName() const override;
// WorkerGlobalScope
+ bool IsNestedWorker() const override;
void ImportModuleScript(
const KURL& module_url_record,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -74,11 +76,11 @@ class CORE_EXPORT DedicatedWorkerGlobalScope final : public WorkerGlobalScope {
ExceptionState&);
void postMessage(ScriptState*,
const ScriptValue& message,
- const PostMessageOptions&,
+ const PostMessageOptions*,
ExceptionState&);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(messageerror);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(message, kMessage);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(messageerror, kMessageerror);
void Trace(blink::Visitor*) override;
@@ -88,11 +90,12 @@ class CORE_EXPORT DedicatedWorkerGlobalScope final : public WorkerGlobalScope {
const String name_;
};
-DEFINE_TYPE_CASTS(DedicatedWorkerGlobalScope,
- ExecutionContext,
- context,
- context->IsDedicatedWorkerGlobalScope(),
- context.IsDedicatedWorkerGlobalScope());
+template <>
+struct DowncastTraits<DedicatedWorkerGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsDedicatedWorkerGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl
index 3e8c7eb18de..f6ce7838b35 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_global_scope.idl
@@ -36,8 +36,8 @@
] interface DedicatedWorkerGlobalScope : WorkerGlobalScope {
[Replaceable] readonly attribute DOMString name;
- [CallWith=ScriptState, RaisesException] void postMessage(any message, optional sequence<object> transfer = []);
- [RuntimeEnabled=PostMessageOptions, CallWith=ScriptState, RaisesException] void postMessage(any message, PostMessageOptions options);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, sequence<object> transfer);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, optional PostMessageOptions options);
void close();
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc
index 532011572fc..f849cbac796 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.cc
@@ -7,6 +7,7 @@
#include <memory>
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/events/error_event.h"
@@ -18,10 +19,9 @@
#include "third_party/blink/renderer/core/workers/dedicated_worker.h"
#include "third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.h"
#include "third_party/blink/renderer/core/workers/dedicated_worker_thread.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_options.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/wtf.h"
namespace blink {
@@ -39,7 +39,7 @@ DedicatedWorkerMessagingProxy::~DedicatedWorkerMessagingProxy() = default;
void DedicatedWorkerMessagingProxy::StartWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
- const WorkerOptions& options,
+ const WorkerOptions* options,
const KURL& script_url,
FetchClientSettingsObjectSnapshot* outside_settings_object,
const v8_inspector::V8StackTraceId& stack_id,
@@ -55,15 +55,26 @@ void DedicatedWorkerMessagingProxy::StartWorkerGlobalScope(
std::move(creation_params),
CreateBackingThreadStartupData(ToIsolate(GetExecutionContext())));
- if (options.type() == "classic") {
- // Dedicated worker is origin-bound, so use kSharableCrossOrigin.
- GetWorkerThread()->EvaluateClassicScript(
- script_url, kSharableCrossOrigin, source_code,
- nullptr /* cached_meta_data */, stack_id);
- } else if (options.type() == "module") {
+ // Step 13: "Obtain script by switching on the value of options's type
+ // member:"
+ if (options->type() == "classic") {
+ // "classic: Fetch a classic worker script given url, outside settings,
+ // destination, and inside settings."
+ if (RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled()) {
+ GetWorkerThread()->ImportClassicScript(script_url,
+ outside_settings_object, stack_id);
+ } else {
+ // Legacy code path (to be deprecated, see https://crbug.com/835717):
+ GetWorkerThread()->EvaluateClassicScript(
+ script_url, source_code, nullptr /* cached_meta_data */, stack_id);
+ }
+ } else if (options->type() == "module") {
+ // "module: Fetch a module worker script graph given url, outside settings,
+ // destination, the value of the credentials member of options, and inside
+ // settings."
network::mojom::FetchCredentialsMode credentials_mode;
- bool result =
- Request::ParseCredentialsMode(options.credentials(), &credentials_mode);
+ bool result = Request::ParseCredentialsMode(options->credentials(),
+ &credentials_mode);
DCHECK(result);
GetWorkerThread()->ImportModuleScript(script_url, outside_settings_object,
credentials_mode);
@@ -174,6 +185,10 @@ void DedicatedWorkerMessagingProxy::DispatchErrorEvent(
CrossThreadBind(&DedicatedWorkerObjectProxy::ProcessUnhandledException,
CrossThreadUnretained(worker_object_proxy_.get()),
exception_id, CrossThreadUnretained(GetWorkerThread())));
+
+ // Propagate an unhandled error to the parent context.
+ const auto mute_script_errors = SanitizeScriptErrors::kDoNotSanitize;
+ GetExecutionContext()->DispatchErrorEvent(event, mute_script_errors);
}
void DedicatedWorkerMessagingProxy::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h
index 70416fe869a..4c1627943bc 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h
@@ -9,6 +9,7 @@
#include "base/macros.h"
#include "base/memory/scoped_refptr.h"
#include "base/optional.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "third_party/blink/public/mojom/messaging/transferable_message.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/messaging/message_port.h"
@@ -16,7 +17,6 @@
#include "third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
namespace blink {
@@ -37,7 +37,7 @@ class CORE_EXPORT DedicatedWorkerMessagingProxy
// These methods should only be used on the parent context thread.
void StartWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams>,
- const WorkerOptions&,
+ const WorkerOptions*,
const KURL& script_url,
FetchClientSettingsObjectSnapshot* outside_settings_object,
const v8_inspector::V8StackTraceId&,
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc
index 88aa262cfa1..84d3d4a0b12 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_object_proxy.cc
@@ -48,7 +48,7 @@
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -76,7 +76,7 @@ void DedicatedWorkerObjectProxy::PostMessageToWorkerObject(
void DedicatedWorkerObjectProxy::ProcessMessageFromWorkerObject(
BlinkTransferableMessage message,
WorkerThread* worker_thread) {
- ToWorkerGlobalScope(worker_thread->GlobalScope())
+ To<WorkerGlobalScope>(worker_thread->GlobalScope())
->ReceiveMessagePausable(std::move(message));
}
@@ -84,7 +84,7 @@ void DedicatedWorkerObjectProxy::ProcessUnhandledException(
int exception_id,
WorkerThread* worker_thread) {
WorkerGlobalScope* global_scope =
- ToWorkerGlobalScope(worker_thread->GlobalScope());
+ To<WorkerGlobalScope>(worker_thread->GlobalScope());
global_scope->ExceptionUnhandled(exception_id);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
index a833d26cbcc..ab02737ead1 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_test.cc
@@ -7,6 +7,7 @@
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/renderer/bindings/core/v8/sanitize_script_errors.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/events/message_event.h"
#include "third_party/blink/renderer/core/inspector/console_message_storage.h"
@@ -22,7 +23,6 @@
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/core/workers/worker_thread_test_helper.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/testing/unit_test_helpers.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
@@ -30,9 +30,10 @@ namespace blink {
class DedicatedWorkerThreadForTest final : public DedicatedWorkerThread {
public:
- DedicatedWorkerThreadForTest(DedicatedWorkerObjectProxy& worker_object_proxy)
+ DedicatedWorkerThreadForTest(ExecutionContext* parent_execution_context,
+ DedicatedWorkerObjectProxy& worker_object_proxy)
: DedicatedWorkerThread("fake worker name",
- nullptr /* parent_execution_context*/,
+ parent_execution_context,
worker_object_proxy) {
worker_backing_thread_ = WorkerBackingThread::Create(
ThreadCreationParams(WebThreadType::kTestThread));
@@ -40,7 +41,7 @@ class DedicatedWorkerThreadForTest final : public DedicatedWorkerThread {
WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) override {
- auto* global_scope = new DedicatedWorkerGlobalScope(
+ auto* global_scope = MakeGarbageCollected<DedicatedWorkerGlobalScope>(
"fake worker name", std::move(creation_params), this, time_origin_);
// Initializing a global scope with a dummy creation params may emit warning
// messages (e.g., invalid CSP directives). Clear them here for tests that
@@ -133,8 +134,9 @@ class DedicatedWorkerMessagingProxyForTest
To<Document>(GetExecutionContext())->GetSettings());
InitializeWorkerThread(
std::make_unique<GlobalScopeCreationParams>(
- script_url, ScriptType::kClassic, "fake user agent", headers,
- kReferrerPolicyDefault, security_origin_.get(),
+ script_url, mojom::ScriptType::kClassic, "fake user agent",
+ nullptr /* web_worker_fetch_context */, headers,
+ network::mojom::ReferrerPolicy::kDefault, security_origin_.get(),
false /* starter_secure_context */,
CalculateHttpsState(security_origin_.get()),
nullptr /* worker_clients */, mojom::IPAddressSpace::kLocal,
@@ -144,9 +146,9 @@ class DedicatedWorkerMessagingProxyForTest
WorkerBackingThreadStartupData(
WorkerBackingThreadStartupData::HeapLimitMode::kDefault,
WorkerBackingThreadStartupData::AtomicsWaitMode::kAllow));
- GetWorkerThread()->EvaluateClassicScript(
- script_url, kOpaqueResource, source, nullptr /* cached_meta_data */,
- v8_inspector::V8StackTraceId());
+ GetWorkerThread()->EvaluateClassicScript(script_url, source,
+ nullptr /* cached_meta_data */,
+ v8_inspector::V8StackTraceId());
}
DedicatedWorkerThreadForTest* GetDedicatedWorkerThread() {
@@ -159,7 +161,8 @@ class DedicatedWorkerMessagingProxyForTest
private:
std::unique_ptr<WorkerThread> CreateWorkerThread() override {
- return std::make_unique<DedicatedWorkerThreadForTest>(WorkerObjectProxy());
+ return std::make_unique<DedicatedWorkerThreadForTest>(GetExecutionContext(),
+ WorkerObjectProxy());
}
scoped_refptr<const SecurityOrigin> security_origin_;
@@ -172,7 +175,8 @@ class DedicatedWorkerTest : public PageTestBase {
void SetUp() override {
PageTestBase::SetUp(IntSize());
worker_messaging_proxy_ =
- new DedicatedWorkerMessagingProxyForTest(&GetDocument());
+ MakeGarbageCollected<DedicatedWorkerMessagingProxyForTest>(
+ &GetDocument());
}
void TearDown() override {
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc
index 4bd6088f898..273c6da15f0 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.cc
@@ -59,7 +59,8 @@ DedicatedWorkerThread::DedicatedWorkerThread(
DedicatedWorkerObjectProxy& worker_object_proxy)
: WorkerThread(worker_object_proxy),
name_(name.IsolatedCopy()),
- worker_object_proxy_(worker_object_proxy) {
+ worker_object_proxy_(worker_object_proxy),
+ is_nested_worker_(parent_execution_context->IsWorkerGlobalScope()) {
FrameOrWorkerScheduler* scheduler =
parent_execution_context ? parent_execution_context->GetScheduler()
: nullptr;
@@ -76,8 +77,8 @@ void DedicatedWorkerThread::ClearWorkerBackingThread() {
WorkerOrWorkletGlobalScope* DedicatedWorkerThread::CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- return new DedicatedWorkerGlobalScope(name_, std::move(creation_params), this,
- time_origin_);
+ return MakeGarbageCollected<DedicatedWorkerGlobalScope>(
+ name_, std::move(creation_params), this, time_origin_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h
index 01466db33d7..b506d3f6802 100644
--- a/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h
+++ b/chromium/third_party/blink/renderer/core/workers/dedicated_worker_thread.h
@@ -54,6 +54,8 @@ class CORE_EXPORT DedicatedWorkerThread : public WorkerThread {
return worker_object_proxy_;
}
+ bool IsNestedWorker() const { return is_nested_worker_; }
+
private:
friend class DedicatedWorkerThreadForTest;
@@ -70,6 +72,7 @@ class CORE_EXPORT DedicatedWorkerThread : public WorkerThread {
std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
const String name_;
DedicatedWorkerObjectProxy& worker_object_proxy_;
+ const bool is_nested_worker_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc b/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc
deleted file mode 100644
index af294e7f63b..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.cc
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/workers/execution_context_worker_registry.h"
-
-#include "third_party/blink/renderer/core/dom/document.h"
-#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
-
-namespace blink {
-
-const char ExecutionContextWorkerRegistry::kSupplementName[] =
- "ExecutionContextWorkerRegistry";
-
-ExecutionContextWorkerRegistry::ExecutionContextWorkerRegistry(
- ExecutionContext& context)
- : Supplement<ExecutionContext>(context) {}
-
-ExecutionContextWorkerRegistry::~ExecutionContextWorkerRegistry() {
-}
-
-ExecutionContextWorkerRegistry* ExecutionContextWorkerRegistry::From(
- ExecutionContext& context) {
- DCHECK(context.IsContextThread());
- ExecutionContextWorkerRegistry* worker_registry =
- Supplement<ExecutionContext>::From<ExecutionContextWorkerRegistry>(
- context);
- if (!worker_registry) {
- worker_registry = new ExecutionContextWorkerRegistry(context);
- Supplement<ExecutionContext>::ProvideTo(context, worker_registry);
- }
- return worker_registry;
-}
-
-void ExecutionContextWorkerRegistry::AddWorkerInspectorProxy(
- WorkerInspectorProxy* proxy) {
- proxies_.insert(proxy);
-}
-
-void ExecutionContextWorkerRegistry::RemoveWorkerInspectorProxy(
- WorkerInspectorProxy* proxy) {
- proxies_.erase(proxy);
-}
-
-const HeapHashSet<Member<WorkerInspectorProxy>>&
-ExecutionContextWorkerRegistry::GetWorkerInspectorProxies() {
- return proxies_;
-}
-
-void ExecutionContextWorkerRegistry::Trace(Visitor* visitor) {
- visitor->Trace(proxies_);
- Supplement<ExecutionContext>::Trace(visitor);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h b/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h
deleted file mode 100644
index 391d9b786ac..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/execution_context_worker_registry.h
+++ /dev/null
@@ -1,42 +0,0 @@
-// Copyright 2018 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXECUTION_CONTEXT_WORKER_REGISTRY_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXECUTION_CONTEXT_WORKER_REGISTRY_H_
-
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
-#include "third_party/blink/renderer/platform/supplementable.h"
-#include "third_party/blink/renderer/platform/wtf/hash_set.h"
-
-namespace blink {
-
-// Tracks the WorkerInspectorProxy objects created by a given ExecutionContext.
-class ExecutionContextWorkerRegistry final
- : public GarbageCollectedFinalized<ExecutionContextWorkerRegistry>,
- public Supplement<ExecutionContext> {
- USING_GARBAGE_COLLECTED_MIXIN(ExecutionContextWorkerRegistry);
-
- public:
- static const char kSupplementName[];
-
- static ExecutionContextWorkerRegistry* From(ExecutionContext& context);
-
- ~ExecutionContextWorkerRegistry();
-
- void AddWorkerInspectorProxy(WorkerInspectorProxy* proxy);
- void RemoveWorkerInspectorProxy(WorkerInspectorProxy* proxy);
- const HeapHashSet<Member<WorkerInspectorProxy>>& GetWorkerInspectorProxies();
-
- void Trace(Visitor* visitor) override;
-
- private:
- explicit ExecutionContextWorkerRegistry(ExecutionContext& context);
-
- HeapHashSet<Member<WorkerInspectorProxy>> proxies_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXECUTION_CONTEXT_WORKER_REGISTRY_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/README.md b/chromium/third_party/blink/renderer/core/workers/experimental/README.md
index b6855f9f0e5..fbc340eb14b 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/README.md
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/README.md
@@ -1,9 +1,17 @@
This directory contains experimental APIs for farming tasks out to a pool of worker threads. Everything in this directory is still highly in flux, and is not anywhere near ready to ship.
thread_pool.{h,cc} contain a class that manages a pool of worker threads and can distribute work to them.
+thread_pool_thread.{h,cc} is a subclass of WorkerThread that these distirubted tasks run on.
worker_task_queue.{h,cc,idl} exposes two APIs:
* postFunction - a simple API for posting a task to a worker.
* postTask - an API for posting tasks that can specify other tasks as prerequisites and coordinates the transfer of return values of prerequisite tasks to dependent tasks
+task_worklet.{h,cc,idl}, task_worklet_global_scope.{h,cc,idl}, and window_task_worklet.{h,idl} exposes a similar API to
+WorkerTaskQueue, built on top of the Worklet API. In addition to implementing postTask() just like WorkerTaskQueue, it
+includes addModule() (inherited from Worklet) and a second variant of postTask(). Modules loaded via addModule() can call
+registerTask() to specify a name and class with a process() function, and this second variant of postTask() takes a task name
+instead of a function. If a task is registered with that given task name, its process() function will be called with the given
+parameters.
+
task.{h,cc,idl} exposes the simple wrapper object returned by postTask and provides the backend that runs tasks on the worker thread (for both postFunction and postTask) and tracks the relationships between tasks (for postTask).
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task.cc b/chromium/third_party/blink/renderer/core/workers/experimental/task.cc
index bed0ed56c7c..45d838463b1 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.cc
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task.cc
@@ -4,61 +4,92 @@
#include "third_party/blink/renderer/core/workers/experimental/task.h"
+#include "third_party/blink/renderer/bindings/core/v8/script_function.h"
#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_function.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_task.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/experimental/thread_pool.h"
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
namespace blink {
-ThreadPoolTask::ThreadPoolTask(ThreadPool* thread_pool,
- v8::Isolate* isolate,
- const ScriptValue& function,
- const Vector<ScriptValue>& arguments,
- TaskType task_type)
+// worker_thread_ only.
+class TaskBase::AsyncFunctionCompleted : public ScriptFunction {
+ public:
+ static v8::Local<v8::Function> CreateFunction(ScriptState* script_state,
+ TaskBase* task,
+ State state) {
+ return (new AsyncFunctionCompleted(script_state, task, state))
+ ->BindToV8Function();
+ }
+
+ ScriptValue Call(ScriptValue v) override {
+ task_->TaskCompletedOnWorkerThread(v.V8Value(), state_);
+ return ScriptValue();
+ }
+
+ private:
+ AsyncFunctionCompleted(ScriptState* script_state, TaskBase* task, State state)
+ : ScriptFunction(script_state), task_(task), state_(state) {}
+ CrossThreadPersistent<TaskBase> task_;
+ const State state_;
+};
+
+TaskBase::TaskBase(TaskType task_type,
+ ScriptState* script_state,
+ const ScriptValue& function,
+ const String& function_name)
: task_type_(task_type),
- self_keep_alive_(base::AdoptRef(this)),
- arguments_(arguments.size()),
- weak_factory_(this) {
+ self_keep_alive_(this),
+ function_name_(function_name.IsolatedCopy()) {
DCHECK(IsMainThread());
DCHECK(task_type_ == TaskType::kUserInteraction ||
task_type_ == TaskType::kIdleTask);
-
// TODO(japhet): Handle serialization failures
- function_ = SerializedScriptValue::SerializeAndSwallowExceptions(
- isolate, function.V8Value()->ToString(isolate));
+ v8::Isolate* isolate = script_state->GetIsolate();
+ if (!function.IsEmpty()) {
+ function_ = SerializedScriptValue::SerializeAndSwallowExceptions(
+ isolate, function.V8Value()->ToString(isolate));
+ }
+}
- Vector<ThreadPoolTask*> prerequisites;
+void TaskBase::InitializeArgumentsOnMainThread(
+ ThreadPoolThreadProvider* thread_provider,
+ ScriptState* script_state,
+ const Vector<ScriptValue>& arguments) {
+ v8::Isolate* isolate = script_state->GetIsolate();
+ arguments_.resize(arguments.size());
+ HeapVector<Member<TaskBase>> prerequisites;
Vector<size_t> prerequisites_indices;
for (size_t i = 0; i < arguments_.size(); i++) {
// Normal case: if the argument isn't a Task, just serialize it.
- if (!V8Task::hasInstance(arguments[i].V8Value(), isolate)) {
+ if (!V8Task::HasInstance(arguments[i].V8Value(), isolate)) {
arguments_[i].serialized_value =
SerializedScriptValue::SerializeAndSwallowExceptions(
isolate, arguments[i].V8Value());
continue;
}
- ThreadPoolTask* prerequisite =
+ TaskBase* prerequisite =
ToScriptWrappable(arguments[i].V8Value().As<v8::Object>())
- ->ToImpl<Task>()
- ->GetThreadPoolTask();
+ ->ToImpl<Task>();
prerequisites.push_back(prerequisite);
prerequisites_indices.push_back(i);
}
- worker_thread_ = SelectThread(prerequisites, thread_pool);
+ worker_thread_ = SelectThread(prerequisites, thread_provider);
worker_thread_->IncrementTasksInProgressCount();
if (prerequisites.IsEmpty()) {
+ MutexLocker lock(mutex_);
MaybeStartTask();
return;
}
- // Prior to this point, other ThreadPoolTask instances don't have a reference
+ // Prior to this point, other Task instances don't have a reference
// to |this| yet, so no need to lock mutex_. RegisterDependencies() populates
// those references, so RegisterDependencies() and any logic thereafter must
// consider the potential for data races.
@@ -66,41 +97,32 @@ ThreadPoolTask::ThreadPoolTask(ThreadPool* thread_pool,
}
// static
-ThreadPoolThread* ThreadPoolTask::SelectThread(
- const Vector<ThreadPoolTask*>& prerequisites,
- ThreadPool* thread_pool) {
+ThreadPoolThread* TaskBase::SelectThread(
+ const HeapVector<Member<TaskBase>>& prerequisites,
+ ThreadPoolThreadProvider* thread_provider) {
DCHECK(IsMainThread());
- HashCountedSet<WorkerThread*> prerequisite_location_counts;
+ HashCountedSet<ThreadPoolThread*> prerequisite_location_counts;
size_t max_prerequisite_location_count = 0;
ThreadPoolThread* max_prerequisite_thread = nullptr;
- for (ThreadPoolTask* prerequisite : prerequisites) {
- // For prerequisites that are not yet complete, track which thread the task
- // will run on. Put this task on the thread where the most prerequisites
- // reside. This is slightly imprecise, because a task may complete before
- // registering dependent tasks below.
- if (ThreadPoolThread* thread = prerequisite->GetScheduledThread()) {
- prerequisite_location_counts.insert(thread);
- unsigned thread_count = prerequisite_location_counts.count(thread);
- if (thread_count > max_prerequisite_location_count) {
- max_prerequisite_location_count = thread_count;
- max_prerequisite_thread = thread;
- }
+ for (TaskBase* prerequisite : prerequisites) {
+ // Track which thread the prerequisites will run on. Put this task on the
+ // thread where the most prerequisites reside.
+ ThreadPoolThread* thread = prerequisite->worker_thread_;
+ prerequisite_location_counts.insert(thread);
+ unsigned thread_count = prerequisite_location_counts.count(thread);
+ if (thread_count > max_prerequisite_location_count) {
+ max_prerequisite_location_count = thread_count;
+ max_prerequisite_thread = thread;
}
}
return max_prerequisite_thread ? max_prerequisite_thread
- : thread_pool->GetLeastBusyThread();
-}
-
-ThreadPoolThread* ThreadPoolTask::GetScheduledThread() {
- DCHECK(IsMainThread());
- MutexLocker lock(mutex_);
- return HasFinished() ? nullptr : worker_thread_;
+ : thread_provider->GetLeastBusyThread();
}
// Should only be called from constructor. Split out in to a helper because
// clang appears to exempt constructors from thread safety analysis.
-void ThreadPoolTask::RegisterDependencies(
- const Vector<ThreadPoolTask*>& prerequisites,
+void TaskBase::RegisterDependencies(
+ const HeapVector<Member<TaskBase>>& prerequisites,
const Vector<size_t>& prerequisites_indices) {
DCHECK(IsMainThread());
{
@@ -109,35 +131,28 @@ void ThreadPoolTask::RegisterDependencies(
}
for (size_t i = 0; i < prerequisites.size(); i++) {
- ThreadPoolTask* prerequisite = prerequisites[i];
+ TaskBase* prerequisite = prerequisites[i];
size_t prerequisite_index = prerequisites_indices[i];
- scoped_refptr<SerializedScriptValue> result;
- State prerequisite_state = State::kPending;
{
MutexLocker lock(prerequisite->mutex_);
- prerequisite_state = prerequisite->state_;
- if (prerequisite->HasFinished()) {
- result = prerequisite->serialized_result_;
- } else {
- prerequisite->dependents_.insert(
- std::make_unique<Dependent>(this, prerequisite_index));
+ if (!prerequisite->HasFinished()) {
+ prerequisite->dependents_.emplace_back(
+ MakeGarbageCollected<Dependent>(this, prerequisite_index));
+ continue;
}
}
- // TODO(japhet): if a prerequisite failed, this task will be cancelled.
- // Should that throw an exception?
- if (prerequisite_state == State::kCompleted ||
- prerequisite_state == State::kFailed) {
- PrerequisiteFinished(prerequisite_index, v8::Local<v8::Value>(), result,
- prerequisite_state);
- }
+ PostCrossThreadTask(
+ *prerequisite->worker_thread_->GetTaskRunner(task_type_), FROM_HERE,
+ CrossThreadBind(&TaskBase::PassResultToDependentOnWorkerThread,
+ WrapCrossThreadPersistent(prerequisite),
+ prerequisite_index, WrapCrossThreadPersistent(this)));
}
}
-ThreadPoolTask::~ThreadPoolTask() {
+TaskBase::~TaskBase() {
DCHECK(IsMainThread());
- DCHECK(!resolver_);
DCHECK(HasFinished());
DCHECK(!function_);
DCHECK(arguments_.IsEmpty());
@@ -145,44 +160,71 @@ ThreadPoolTask::~ThreadPoolTask() {
DCHECK(dependents_.IsEmpty());
}
-void ThreadPoolTask::PrerequisiteFinished(
- size_t prerequisite_index,
- v8::Local<v8::Value> v8_result,
- scoped_refptr<SerializedScriptValue> result,
- State prerequisite_state) {
+scoped_refptr<SerializedScriptValue> TaskBase::GetSerializedResult() {
+ DCHECK(IsMainThread() || worker_thread_->IsCurrentThread());
+ MutexLocker lock(mutex_);
+ DCHECK(HasFinished());
+ if (!serialized_result_ && worker_thread_->IsCurrentThread()) {
+ DCHECK(v8_result_);
+ ScriptState::Scope scope(
+ worker_thread_->GlobalScope()->ScriptController()->GetScriptState());
+ v8::Isolate* isolate = ToIsolate(worker_thread_->GlobalScope());
+ serialized_result_ = SerializedScriptValue::SerializeAndSwallowExceptions(
+ isolate, v8_result_->GetResult(isolate));
+ }
+ return serialized_result_;
+}
+
+void TaskBase::PassResultToDependentOnWorkerThread(size_t dependent_index,
+ TaskBase* dependent) {
+ DCHECK(worker_thread_->IsCurrentThread());
+ bool failed = false;
+ {
+ MutexLocker lock(mutex_);
+ DCHECK(HasFinished());
+ failed = state_ == State::kFailed;
+ }
+
+ // Only serialize if the dependent needs the result on a different thread.
+ // Otherwise, use the unserialized result from v8.
+ scoped_refptr<SerializedScriptValue> serialized_result =
+ dependent->IsTargetThreadForArguments() ? nullptr : GetSerializedResult();
+ V8ResultHolder* v8_result =
+ dependent->IsTargetThreadForArguments() ? v8_result_.Get() : nullptr;
+ dependent->PrerequisiteFinished(dependent_index, v8_result, serialized_result,
+ failed);
+}
+
+void TaskBase::PrerequisiteFinished(
+ size_t index,
+ V8ResultHolder* v8_result,
+ scoped_refptr<SerializedScriptValue> serialized_result,
+ bool failed) {
+ DCHECK(v8_result || serialized_result);
+ DCHECK(!v8_result || !serialized_result);
+
MutexLocker lock(mutex_);
DCHECK(state_ == State::kPending || state_ == State::kCancelPending);
- DCHECK(prerequisite_state == State::kCompleted ||
- prerequisite_state == State::kFailed);
DCHECK_GT(prerequisites_remaining_, 0u);
prerequisites_remaining_--;
- // If the result of the prerequisite doesn't need to move between threads,
- // save the deserialized v8::Value for later use.
- if (prerequisite_state == State::kFailed) {
+ if (failed)
AdvanceState(State::kCancelPending);
- } else if (worker_thread_->IsCurrentThread() && !v8_result.IsEmpty()) {
- arguments_[prerequisite_index].v8_value =
- std::make_unique<ScopedPersistent<v8::Value>>(
- ToIsolate(worker_thread_->GlobalScope()), v8_result);
- } else {
- arguments_[prerequisite_index].serialized_value = result;
- }
+ arguments_[index].v8_value = v8_result;
+ arguments_[index].serialized_value = serialized_result;
MaybeStartTask();
}
-void ThreadPoolTask::MaybeStartTask() {
+void TaskBase::MaybeStartTask() {
if (prerequisites_remaining_)
return;
DCHECK(state_ == State::kPending || state_ == State::kCancelPending);
PostCrossThreadTask(*worker_thread_->GetTaskRunner(task_type_), FROM_HERE,
- CrossThreadBind(&ThreadPoolTask::StartTaskOnWorkerThread,
- CrossThreadUnretained(this)));
+ CrossThreadBind(&TaskBase::StartTaskOnWorkerThread,
+ WrapCrossThreadPersistent(this)));
}
-void ThreadPoolTask::StartTaskOnWorkerThread() {
+bool TaskBase::WillStartTaskOnWorkerThread() {
DCHECK(worker_thread_->IsCurrentThread());
-
- bool was_cancelled = false;
{
MutexLocker lock(mutex_);
DCHECK(!prerequisites_remaining_);
@@ -191,8 +233,7 @@ void ThreadPoolTask::StartTaskOnWorkerThread() {
AdvanceState(State::kStarted);
break;
case State::kCancelPending:
- was_cancelled = true;
- break;
+ return false;
case State::kStarted:
case State::kCompleted:
case State::kFailed:
@@ -200,66 +241,71 @@ void ThreadPoolTask::StartTaskOnWorkerThread() {
break;
}
}
+ return true;
+}
- WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope();
- v8::Isolate* isolate = ToIsolate(global_scope);
- ScriptState::Scope scope(global_scope->ScriptController()->GetScriptState());
-
- v8::TryCatch block(isolate);
- v8::Local<v8::Value> return_value;
- if (was_cancelled) {
- return_value = V8String(isolate, "Task aborted");
- } else {
- return_value = RunTaskOnWorkerThread(isolate);
- DCHECK_EQ(return_value.IsEmpty(), block.HasCaught());
- if (block.HasCaught())
- return_value = block.Exception()->ToString(isolate);
- }
-
- scoped_refptr<SerializedScriptValue> local_result =
- SerializedScriptValue::SerializeAndSwallowExceptions(isolate,
- return_value);
- State local_state =
- block.HasCaught() || was_cancelled ? State::kFailed : State::kCompleted;
-
+void TaskBase::TaskCompletedOnWorkerThread(v8::Local<v8::Value> v8_result,
+ State state) {
+ DCHECK(worker_thread_->IsCurrentThread());
+ v8_result_ =
+ new V8ResultHolder(ToIsolate(worker_thread_->GlobalScope()), v8_result);
function_ = nullptr;
arguments_.clear();
- HashSet<std::unique_ptr<Dependent>> dependents_to_notify;
+ Vector<CrossThreadPersistent<Dependent>> dependents_to_notify;
{
MutexLocker lock(mutex_);
- serialized_result_ = local_result;
- AdvanceState(local_state);
+ AdvanceState(state);
dependents_to_notify.swap(dependents_);
}
- for (auto& dependent : dependents_to_notify) {
- dependent->task->PrerequisiteFinished(dependent->index, return_value,
- local_result, local_state);
- }
+ for (auto& dependent : dependents_to_notify)
+ PassResultToDependentOnWorkerThread(dependent->index, dependent->task);
PostCrossThreadTask(
*worker_thread_->GetParentExecutionContextTaskRunners()->Get(
TaskType::kInternalWorker),
FROM_HERE,
- CrossThreadBind(&ThreadPoolTask::TaskCompleted,
- CrossThreadUnretained(this)));
- // TaskCompleted may delete |this| at any time after this point.
+ CrossThreadBind(&TaskBase::TaskCompleted, WrapCrossThreadPersistent(this),
+ state == State::kCompleted));
}
-v8::Local<v8::Value> ThreadPoolTask::RunTaskOnWorkerThread(
- v8::Isolate* isolate) {
+void TaskBase::RunTaskOnWorkerThread() {
DCHECK(worker_thread_->IsCurrentThread());
// No other thread should be touching function_ or arguments_ at this point,
// so no mutex needed while actually running the task.
+ WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope();
+ ScriptState::Scope scope(global_scope->ScriptController()->GetScriptState());
+ v8::Isolate* isolate = ToIsolate(global_scope);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
- String core_script =
- "(" + ToCoreString(function_->Deserialize(isolate).As<v8::String>()) +
- ")";
- v8::MaybeLocal<v8::Script> script = v8::Script::Compile(
- isolate->GetCurrentContext(), V8String(isolate, core_script));
- v8::Local<v8::Function> script_function =
- script.ToLocalChecked()->Run(context).ToLocalChecked().As<v8::Function>();
+
+ v8::Local<v8::Function> script_function;
+ v8::Local<v8::Value> receiver;
+ if (function_) {
+ String core_script =
+ "(" + ToCoreString(function_->Deserialize(isolate).As<v8::String>()) +
+ ")";
+ v8::MaybeLocal<v8::Script> script =
+ v8::Script::Compile(context, V8String(isolate, core_script));
+ script_function = script.ToLocalChecked()
+ ->Run(context)
+ .ToLocalChecked()
+ .As<v8::Function>();
+ receiver = script_function;
+ } else if (worker_thread_->IsWorklet()) {
+ TaskWorkletGlobalScope* task_worklet_global_scope =
+ static_cast<TaskWorkletGlobalScope*>(global_scope);
+ script_function = task_worklet_global_scope->GetProcessFunctionForName(
+ function_name_, isolate);
+ receiver =
+ task_worklet_global_scope->GetInstanceForName(function_name_, isolate);
+ }
+
+ if (script_function.IsEmpty()) {
+ TaskCompletedOnWorkerThread(V8String(isolate, "Invalid task"),
+ State::kFailed);
+ return;
+ }
Vector<v8::Local<v8::Value>> params(arguments_.size());
for (size_t i = 0; i < arguments_.size(); i++) {
@@ -267,78 +313,55 @@ v8::Local<v8::Value> ThreadPoolTask::RunTaskOnWorkerThread(
if (arguments_[i].serialized_value)
params[i] = arguments_[i].serialized_value->Deserialize(isolate);
else
- params[i] = arguments_[i].v8_value->NewLocal(isolate);
- }
-
- v8::MaybeLocal<v8::Value> ret = script_function->Call(
- context, script_function, params.size(), params.data());
-
- v8::Local<v8::Value> return_value;
- if (!ret.IsEmpty()) {
- return_value = ret.ToLocalChecked();
- if (return_value->IsPromise())
- return_value = return_value.As<v8::Promise>()->Result();
+ params[i] = arguments_[i].v8_value->GetResult(isolate);
}
- return return_value;
-}
-void ThreadPoolTask::TaskCompleted() {
- DCHECK(IsMainThread());
- bool rejected = false;
- {
- MutexLocker lock(mutex_);
- DCHECK(HasFinished());
- rejected = state_ == State::kFailed;
- }
- if (resolver_ && resolver_->GetScriptState()->ContextIsValid()) {
- ScriptState::Scope scope(resolver_->GetScriptState());
- ScriptValue value = GetResult(resolver_->GetScriptState());
- if (rejected)
- resolver_->Reject(v8::Exception::Error(value.V8Value().As<v8::String>()));
- else
- resolver_->Resolve(value);
+ v8::TryCatch block(isolate);
+ v8::MaybeLocal<v8::Value> ret =
+ script_function->Call(context, receiver, params.size(), params.data());
+ if (block.HasCaught()) {
+ TaskCompletedOnWorkerThread(block.Exception()->ToString(isolate),
+ State::kFailed);
+ return;
}
- resolver_ = nullptr;
- worker_thread_->DecrementTasksInProgressCount();
- self_keep_alive_.reset();
- // |this| may be deleted here.
-}
-ScriptValue ThreadPoolTask::GetResult(ScriptState* script_state) {
- DCHECK(IsMainThread());
- MutexLocker lock(mutex_);
- if (!HasFinished()) {
- DCHECK(!serialized_result_);
- DCHECK(deserialized_result_.IsEmpty());
- if (!resolver_)
- resolver_ = ScriptPromiseResolver::Create(script_state);
- return resolver_->Promise().GetScriptValue();
- }
- if (deserialized_result_.IsEmpty()) {
- ScriptState::Scope scope(script_state);
- deserialized_result_ = ScriptValue(
- script_state,
- serialized_result_->Deserialize(script_state->GetIsolate()));
+ DCHECK(!ret.IsEmpty());
+ v8::Local<v8::Value> return_value = ret.ToLocalChecked();
+ if (return_value->IsPromise()) {
+ v8::Local<v8::Promise> promise = return_value.As<v8::Promise>();
+ if (promise->State() == v8::Promise::kPending) {
+ // Wait for the promise to resolve before calling
+ // TaskCompletedOnWorkerThread.
+ ScriptState* script_state = ScriptState::Current(isolate);
+ ScriptPromise(script_state, promise)
+ .Then(AsyncFunctionCompleted::CreateFunction(script_state, this,
+ State::kCompleted),
+ AsyncFunctionCompleted::CreateFunction(script_state, this,
+ State::kFailed));
+ return;
+ }
+ return_value = promise->Result();
}
- return deserialized_result_;
+ TaskCompletedOnWorkerThread(return_value, State::kCompleted);
}
-void ThreadPoolTask::Cancel() {
+void TaskBase::TaskCompleted(bool was_successful) {
DCHECK(IsMainThread());
- MutexLocker lock(mutex_);
- if (state_ == State::kPending)
- AdvanceState(State::kCancelPending);
+ worker_thread_->DecrementTasksInProgressCount();
+ self_keep_alive_.Clear();
}
-void ThreadPoolTask::AdvanceState(State new_state) {
+void TaskBase::AdvanceState(State new_state) {
switch (new_state) {
case State::kPending:
- NOTREACHED() << "kPending should only be set via initialiation";
+ NOTREACHED() << "kPending should only be set via initialization";
break;
- case State::kCancelPending:
case State::kStarted:
DCHECK_EQ(State::kPending, state_);
break;
+ case State::kCancelPending:
+ DCHECK(state_ == State::kPending || state_ == State::kCancelPending);
+ break;
case State::kCompleted:
DCHECK_EQ(State::kStarted, state_);
break;
@@ -349,4 +372,95 @@ void ThreadPoolTask::AdvanceState(State new_state) {
state_ = new_state;
}
+Vector<ScriptValue> GetResolverArgument(ScriptState* script_state, Task* task) {
+ v8::Isolate* isolate = script_state->GetIsolate();
+ return Vector<ScriptValue>({ScriptValue(
+ script_state,
+ ToV8(task, isolate->GetCurrentContext()->Global(), isolate))});
+}
+
+ScriptPromise Task::result(ScriptState* script_state) {
+ DCHECK(IsMainThread());
+ if (!resolve_task_) {
+ resolve_task_ =
+ MakeGarbageCollected<ResolveTask>(script_state, task_type_, this);
+ }
+ return resolve_task_->GetPromise();
+}
+
+void Task::cancel() {
+ DCHECK(IsMainThread());
+ MutexLocker lock(mutex_);
+ if (state_ == State::kPending)
+ AdvanceState(State::kCancelPending);
+}
+
+void Task::StartTaskOnWorkerThread() {
+ DCHECK(worker_thread_->IsCurrentThread());
+ if (!WillStartTaskOnWorkerThread()) {
+ WorkerOrWorkletGlobalScope* global_scope = worker_thread_->GlobalScope();
+ v8::Isolate* isolate = ToIsolate(global_scope);
+ ScriptState::Scope scope(
+ global_scope->ScriptController()->GetScriptState());
+ TaskCompletedOnWorkerThread(V8String(isolate, "Task aborted"),
+ State::kFailed);
+ return;
+ }
+
+ RunTaskOnWorkerThread();
+}
+
+void Task::Trace(Visitor* visitor) {
+ ScriptWrappable::Trace(visitor);
+ TaskBase::Trace(visitor);
+ visitor->Trace(resolve_task_);
+}
+
+ResolveTask::ResolveTask(ScriptState* script_state,
+ TaskType task_type,
+ Task* prerequisite)
+ : TaskBase(task_type, script_state, ScriptValue(), String()),
+ resolver_(ScriptPromiseResolver::Create(script_state)) {
+ DCHECK(IsMainThread());
+ // It's safe to pass a nullptr ThreadPoolThreadProivder here because it
+ // is only used to select a thread if there are no prerequisites, but a
+ // ResolveTask always has exactly one prerequisite.
+ InitializeArgumentsOnMainThread(
+ nullptr, script_state, GetResolverArgument(script_state, prerequisite));
+}
+
+void ResolveTask::StartTaskOnWorkerThread() {
+ // Just take the sole argument and use it as the return value that will be
+ // given to the promise resolver.
+ {
+ MutexLocker lock(mutex_);
+ serialized_result_ = arguments_[0].serialized_value;
+ }
+ TaskCompletedOnWorkerThread(
+ v8::Local<v8::Value>(),
+ WillStartTaskOnWorkerThread() ? State::kCompleted : State::kFailed);
+}
+
+void ResolveTask::TaskCompleted(bool was_successful) {
+ DCHECK(IsMainThread());
+
+ ScriptState* script_state = resolver_->GetScriptState();
+ if (!script_state->ContextIsValid())
+ return;
+ ScriptState::Scope scope(script_state);
+
+ v8::Local<v8::Value> value =
+ GetSerializedResult()->Deserialize(script_state->GetIsolate());
+ if (was_successful)
+ resolver_->Resolve(value);
+ else
+ resolver_->Reject(v8::Exception::Error(value.As<v8::String>()));
+ TaskBase::TaskCompleted(was_successful);
+}
+
+void ResolveTask::Trace(Visitor* visitor) {
+ TaskBase::Trace(visitor);
+ visitor->Trace(resolver_);
+}
+
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task.h b/chromium/third_party/blink/renderer/core/workers/experimental/task.h
index c3b1c3742ee..5b04979d1c8 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.h
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task.h
@@ -6,98 +6,125 @@
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_H_
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
-#include "third_party/blink/renderer/core/workers/experimental/thread_pool.h"
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/wtf/ref_counted.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
namespace blink {
+class ResolveTask;
class SerializedScriptValue;
-class Task;
// Runs |function| with |arguments| on a thread from the given ThreadPool.
// Scans |arguments| for Task objects, and registers those as dependencies,
// passing the result of those tasks in place of the Task arguments.
// All public functions are main-thread-only.
-// ThreadPoolTask keeps itself alive via a self scoped_refptr until the
+// TaskBase keeps itself alive via a SelfKeepAlive until the
// the task completes and reports itself done on the main thread via
-// TaskCompleted(). Other users (e.g. Task below) can keep the task
-// alive after completion.
-class ThreadPoolTask final : public RefCounted<ThreadPoolTask> {
+// TaskCompleted().
+class TaskBase : public GarbageCollectedMixin {
public:
- // Called on main thread
- ThreadPoolTask(ThreadPool*,
- v8::Isolate*,
- const ScriptValue& function,
- const Vector<ScriptValue>& arguments,
- TaskType);
- ~ThreadPoolTask();
- // Returns the result of this task, or a promise that will be resolved with
- // the result when it completes.
- ScriptValue GetResult(ScriptState*) LOCKS_EXCLUDED(mutex_);
- void Cancel() LOCKS_EXCLUDED(mutex_);
-
- base::WeakPtr<ThreadPoolTask> GetWeakPtr() {
- return weak_factory_.GetWeakPtr();
- }
+ virtual ~TaskBase();
+
+ protected:
+ virtual void StartTaskOnWorkerThread() LOCKS_EXCLUDED(mutex_) = 0;
+ virtual bool IsTargetThreadForArguments() = 0;
- private:
enum class State { kPending, kStarted, kCancelPending, kCompleted, kFailed };
- void StartTaskOnWorkerThread() LOCKS_EXCLUDED(mutex_);
- v8::Local<v8::Value> RunTaskOnWorkerThread(v8::Isolate*);
+ TaskBase(TaskType,
+ ScriptState*,
+ const ScriptValue& function,
+ const String& function_name);
+
+ void InitializeArgumentsOnMainThread(ThreadPoolThreadProvider*,
+ ScriptState*,
+ const Vector<ScriptValue>& arguments);
+
+ class AsyncFunctionCompleted;
+
+ // This caches the result after the task completes on the worker thread.
+ // We can't safely clear the ScopedPersistent from the main thread, so
+ // this wrappper allows us to hold a CrossThreadPersistent that arranges
+ // for GC on the worker thread.
+ class V8ResultHolder final
+ : public GarbageCollectedFinalized<V8ResultHolder> {
+ public:
+ V8ResultHolder(v8::Isolate* isolate, v8::Local<v8::Value> result)
+ : result_(isolate, result) {}
+ ~V8ResultHolder() = default;
+ v8::Local<v8::Value> GetResult(v8::Isolate* isolate) {
+ return result_.NewLocal(isolate);
+ }
+ void Trace(Visitor*) {}
+
+ private:
+ ScopedPersistent<v8::Value> result_;
+ };
+
+ bool WillStartTaskOnWorkerThread();
+ void RunTaskOnWorkerThread();
+ void TaskCompletedOnWorkerThread(v8::Local<v8::Value> v8_result, State)
+ LOCKS_EXCLUDED(mutex_);
+ void PassResultToDependentOnWorkerThread(size_t dependent_index, TaskBase*)
+ LOCKS_EXCLUDED(mutex_);
// Called on ANY thread (main thread, worker_thread_, or a sibling worker).
void MaybeStartTask() EXCLUSIVE_LOCKS_REQUIRED(mutex_);
- void PrerequisiteFinished(size_t prerequisite_index,
- v8::Local<v8::Value>,
+ void PrerequisiteFinished(size_t index,
+ V8ResultHolder*,
scoped_refptr<SerializedScriptValue>,
- State) LOCKS_EXCLUDED(mutex_);
+ bool failed) LOCKS_EXCLUDED(mutex_);
bool HasFinished() const EXCLUSIVE_LOCKS_REQUIRED(mutex_) {
return state_ == State::kCompleted || state_ == State::kFailed;
}
void AdvanceState(State new_state) EXCLUSIVE_LOCKS_REQUIRED(mutex_);
+ // Called on main thread or worker_thread_
+ scoped_refptr<SerializedScriptValue> GetSerializedResult()
+ LOCKS_EXCLUDED(mutex_);
+
// Called on main thread
static ThreadPoolThread* SelectThread(
- const Vector<ThreadPoolTask*>& prerequisites,
- ThreadPool*);
- ThreadPoolThread* GetScheduledThread() LOCKS_EXCLUDED(mutex_);
- void RegisterDependencies(const Vector<ThreadPoolTask*>& prerequisites,
+ const HeapVector<Member<TaskBase>>& prerequisites,
+ ThreadPoolThreadProvider*);
+ void RegisterDependencies(const HeapVector<Member<TaskBase>>& prerequisites,
const Vector<size_t>& prerequisite_indices)
LOCKS_EXCLUDED(mutex_);
- void TaskCompleted();
+ virtual void TaskCompleted(bool was_successful);
// worker_thread_ is selected in the constructor and not changed thereafter.
ThreadPoolThread* worker_thread_ = nullptr;
const TaskType task_type_;
// Main thread only
- scoped_refptr<ThreadPoolTask> self_keep_alive_;
- ScriptValue deserialized_result_;
- Persistent<ScriptPromiseResolver> resolver_;
+ SelfKeepAlive<TaskBase> self_keep_alive_;
// Created in constructor on the main thread, consumed and cleared on
// worker_thread_. Those steps can't overlap, so no mutex_ required.
scoped_refptr<SerializedScriptValue> function_;
+ const String function_name_;
// Created and populated with non-prerequiste parameters on the main thread.
// Each prerequisite writes its return value into arguments_ from its thread.
// If the prequisite and this have the same worker_thread_, there is no need
- // to serialize and deserialize the argument, so v8_argument will be populated
+ // to serialize and deserialize the argument, so v8_value will be populated
// with the v8::Value returned by the prerequisite.
// Consumed and cleared on worker_thread_.
// Only requires mutex_ when writing prerequisite results, at other times
// either the main thread or the worker_thread_ has sole access.
struct Argument {
scoped_refptr<SerializedScriptValue> serialized_value;
- std::unique_ptr<ScopedPersistent<v8::Value>> v8_value;
+ CrossThreadPersistent<V8ResultHolder> v8_value;
};
Vector<Argument> arguments_;
// Read on main thread, write on worker_thread_.
scoped_refptr<SerializedScriptValue> serialized_result_ GUARDED_BY(mutex_);
+ // Read/write on worker_thread_
+ CrossThreadPersistent<V8ResultHolder> v8_result_;
+
// Read/write on both main thread and worker_thread_.
State state_ GUARDED_BY(mutex_) = State::kPending;
@@ -106,40 +133,79 @@ class ThreadPoolTask final : public RefCounted<ThreadPoolTask> {
size_t prerequisites_remaining_ GUARDED_BY(mutex_) = 0u;
// Elements added from main thread. Cleared on completion on worker_thread_.
- // Each element in dependents_ is not yet in the kCompleted state and
- // therefore is guaranteed to be alive.
- struct Dependent {
+ // Each element in dependents_ is not yet in the kCompleted state.
+ struct Dependent final : public GarbageCollected<Dependent> {
public:
- Dependent(ThreadPoolTask* task, size_t index) : task(task), index(index) {}
- ThreadPoolTask* task;
+ Dependent(TaskBase* task, size_t index) : task(task), index(index) {
+ DCHECK(IsMainThread());
+ }
+ void Trace(Visitor* visitor) { visitor->Trace(task); }
+ Member<TaskBase> task;
+ // The index in the dependent's argument array where this result should go.
size_t index;
};
- HashSet<std::unique_ptr<Dependent>> dependents_ GUARDED_BY(mutex_);
+ Vector<CrossThreadPersistent<Dependent>> dependents_ GUARDED_BY(mutex_);
Mutex mutex_;
-
- base::WeakPtrFactory<ThreadPoolTask> weak_factory_;
};
-// This is a thin, v8-exposed wrapper around ThreadPoolTask that allows
-// ThreadPoolTask to avoid being GarbageCollected.
-class Task : public ScriptWrappable {
+// The variant of TaskBase that is exposed to JS.
+class Task final : public ScriptWrappable, public TaskBase {
DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(Task);
public:
- explicit Task(ThreadPoolTask* thread_pool_task)
- : thread_pool_task_(thread_pool_task) {}
- ~Task() override = default;
+ // Called on main thread
+ Task(ThreadPoolThreadProvider* thread_provider,
+ ScriptState* script_state,
+ const ScriptValue& function,
+ const Vector<ScriptValue>& arguments,
+ TaskType task_type)
+ : TaskBase(task_type, script_state, function, String()) {
+ InitializeArgumentsOnMainThread(thread_provider, script_state, arguments);
+ }
+ Task(ThreadPoolThreadProvider* thread_provider,
+ ScriptState* script_state,
+ const String& function_name,
+ const Vector<ScriptValue>& arguments,
+ TaskType task_type)
+ : TaskBase(task_type, script_state, ScriptValue(), function_name) {
+ InitializeArgumentsOnMainThread(thread_provider, script_state, arguments);
+ }
- ScriptValue result(ScriptState* script_state) {
- return thread_pool_task_->GetResult(script_state);
+ // Returns a promise that will be resolved with the result when it completes.
+ ScriptPromise result(ScriptState*);
+ void cancel() LOCKS_EXCLUDED(mutex_);
+
+ void StartTaskOnWorkerThread() override LOCKS_EXCLUDED(mutex_);
+ bool IsTargetThreadForArguments() override {
+ return worker_thread_->IsCurrentThread();
}
- void cancel() { thread_pool_task_->Cancel(); }
+ void Trace(Visitor*) override;
+
+ private:
+ Member<ResolveTask> resolve_task_;
+};
+
+// An internal TaskBase subclass that drives main thread promise resolution.
+// It registers itself as a dependent on the Task whose result is being
+// promised. When that Task completes, it runs a dummy script that just returns
+// the dependent's result as its own. It then eagerly serializes the result, and
+// overrides TaskCompleted() to actually resolve the promise.
+class ResolveTask final : public GarbageCollectedFinalized<ResolveTask>,
+ public TaskBase {
+ USING_GARBAGE_COLLECTED_MIXIN(ResolveTask);
- ThreadPoolTask* GetThreadPoolTask() const { return thread_pool_task_.get(); }
+ public:
+ ResolveTask(ScriptState*, TaskType, Task* prerequisite);
+ void StartTaskOnWorkerThread() override LOCKS_EXCLUDED(mutex_);
+ bool IsTargetThreadForArguments() override { return IsMainThread(); }
+ void TaskCompleted(bool was_successful) override;
+ ScriptPromise GetPromise() { return resolver_->Promise(); }
+ void Trace(Visitor*) override;
private:
- scoped_refptr<ThreadPoolTask> thread_pool_task_;
+ Member<ScriptPromiseResolver> resolver_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task.idl b/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
index c0d2230a85c..b3a2bf74622 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task.idl
@@ -6,6 +6,6 @@
Exposed=Window,
RuntimeEnabled=WorkerTaskQueue
] interface Task {
- [CallWith=ScriptState] readonly attribute any result;
+ [CallWith=ScriptState] readonly attribute Promise<any> result;
void cancel();
};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc
new file mode 100644
index 00000000000..8cdafe2afa6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.cc
@@ -0,0 +1,121 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet.h"
+
+#include "third_party/blink/renderer/core/frame/local_dom_window.h"
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h"
+#include "third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h"
+#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+
+namespace blink {
+
+class TaskWorkletMessagingProxy final : public ThreadedWorkletMessagingProxy {
+ public:
+ TaskWorkletMessagingProxy(ExecutionContext* context)
+ : ThreadedWorkletMessagingProxy(context) {}
+ ~TaskWorkletMessagingProxy() override = default;
+
+ std::unique_ptr<WorkerThread> CreateWorkerThread() override {
+ return std::make_unique<ThreadPoolThread>(GetExecutionContext(),
+ WorkletObjectProxy(),
+ ThreadPoolThread::kWorklet);
+ }
+
+ ThreadPoolThread* GetWorkerThread() const {
+ return static_cast<ThreadPoolThread*>(
+ ThreadedMessagingProxyBase::GetWorkerThread());
+ }
+};
+
+const char TaskWorklet::kSupplementName[] = "TaskWorklet";
+
+TaskWorklet* TaskWorklet::From(LocalDOMWindow& window) {
+ TaskWorklet* task_worklet =
+ Supplement<LocalDOMWindow>::From<TaskWorklet>(window);
+ if (!task_worklet) {
+ task_worklet = new TaskWorklet(window.document());
+ Supplement<LocalDOMWindow>::ProvideTo(window, task_worklet);
+ }
+ return task_worklet;
+}
+
+static const size_t kMaxTaskWorkletThreads = 4;
+
+TaskWorklet::TaskWorklet(Document* document) : Worklet(document) {}
+
+Task* TaskWorklet::postTask(ScriptState* script_state,
+ const ScriptValue& function,
+ const Vector<ScriptValue>& arguments) {
+ DCHECK(function.IsFunction());
+ // TODO(japhet): Here and below: it's unclear what task type should be used,
+ // and whether the API should allow it to be configured. Using kIdleTask as a
+ // placeholder for now.
+ return new Task(this, script_state, function, arguments, TaskType::kIdleTask);
+}
+
+Task* TaskWorklet::postTask(ScriptState* script_state,
+ const String& function_name,
+ const Vector<ScriptValue>& arguments) {
+ return new Task(this, script_state, function_name, arguments,
+ TaskType::kIdleTask);
+}
+
+ThreadPoolThread* TaskWorklet::GetLeastBusyThread() {
+ DCHECK(IsMainThread());
+ ThreadPoolThread* least_busy_thread = nullptr;
+ size_t lowest_task_count = std::numeric_limits<std::size_t>::max();
+ for (auto& proxy : proxies_) {
+ ThreadPoolThread* current_thread =
+ static_cast<TaskWorkletMessagingProxy*>(proxy.Get())->GetWorkerThread();
+ size_t current_task_count = current_thread->GetTasksInProgressCount();
+ // If there's an idle thread, use it.
+ if (current_task_count == 0)
+ return current_thread;
+ if (current_task_count < lowest_task_count) {
+ least_busy_thread = current_thread;
+ lowest_task_count = current_task_count;
+ }
+ }
+ if (proxies_.size() == kMaxTaskWorkletThreads)
+ return least_busy_thread;
+ auto* proxy = static_cast<TaskWorkletMessagingProxy*>(CreateGlobalScope());
+ proxies_.push_back(proxy);
+ return proxy->GetWorkerThread();
+}
+
+// TODO(japhet): This causes all of the backing threads to be created when
+// addModule() is first called. Sort out lazy global scope creation.
+// Note that if the function variant of postTask() is called first, global
+// scopes will be created lazily; it's only module loading that needs upfront
+// global scope creation, presumably because we don't have a way to replay
+// module loads from WorkletModuleResponsesMap yet.
+bool TaskWorklet::NeedsToCreateGlobalScope() {
+ return GetNumberOfGlobalScopes() < kMaxTaskWorkletThreads;
+}
+
+WorkletGlobalScopeProxy* TaskWorklet::CreateGlobalScope() {
+ DCHECK_LT(GetNumberOfGlobalScopes(), kMaxTaskWorkletThreads);
+ TaskWorkletMessagingProxy* proxy =
+ new TaskWorkletMessagingProxy(GetExecutionContext());
+ proxy->Initialize(WorkerClients::Create(), ModuleResponsesMap(),
+ WorkerBackingThreadStartupData::CreateDefault());
+ return proxy;
+}
+
+// We select a global scope without this getting called.
+wtf_size_t TaskWorklet::SelectGlobalScope() {
+ NOTREACHED();
+ return 0u;
+}
+
+void TaskWorklet::Trace(blink::Visitor* visitor) {
+ Worklet::Trace(visitor);
+ Supplement<LocalDOMWindow>::Trace(visitor);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h
new file mode 100644
index 00000000000..49c367ab2e9
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.h
@@ -0,0 +1,49 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_H_
+
+#include "third_party/blink/renderer/core/workers/experimental/task.h"
+#include "third_party/blink/renderer/core/workers/worklet.h"
+#include "third_party/blink/renderer/platform/supplementable.h"
+
+namespace blink {
+class Document;
+class LocalDOMWindow;
+
+class TaskWorklet final : public Worklet,
+ public Supplement<LocalDOMWindow>,
+ public ThreadPoolThreadProvider {
+ DEFINE_WRAPPERTYPEINFO();
+ USING_GARBAGE_COLLECTED_MIXIN(TaskWorklet);
+
+ public:
+ static const char kSupplementName[];
+ static TaskWorklet* From(LocalDOMWindow&);
+
+ Task* postTask(ScriptState*,
+ const ScriptValue& task,
+ const Vector<ScriptValue>& arguments);
+
+ Task* postTask(ScriptState*,
+ const String& function_name,
+ const Vector<ScriptValue>& arguments);
+
+ ThreadPoolThread* GetLeastBusyThread() override;
+
+ void Trace(blink::Visitor*) override;
+
+ private:
+ explicit TaskWorklet(Document*);
+ ~TaskWorklet() override = default;
+
+ bool NeedsToCreateGlobalScope() final;
+ WorkletGlobalScopeProxy* CreateGlobalScope() final;
+ wtf_size_t SelectGlobalScope() final;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl
new file mode 100644
index 00000000000..cbf68ff0a57
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet.idl
@@ -0,0 +1,11 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=WorkerTaskQueue,
+ SecureContext
+] interface TaskWorklet : Worklet {
+ [CallWith=ScriptState] Task postTask(CallbackFunctionTreatedAsScriptValue task, any... arguments);
+ [CallWith=ScriptState] Task postTask(USVString task, any... arguments);
+};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc
new file mode 100644
index 00000000000..efec929d9f6
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.cc
@@ -0,0 +1,115 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h"
+
+#include "third_party/blink/renderer/bindings/core/v8/v8_object_parser.h"
+#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+
+namespace blink {
+
+class TaskDefinition final : public GarbageCollectedFinalized<TaskDefinition> {
+ public:
+ TaskDefinition(v8::Isolate* isolate,
+ v8::Local<v8::Value> instance,
+ v8::Local<v8::Function> process)
+ : instance_(isolate, instance), process_(isolate, process) {}
+ ~TaskDefinition() = default;
+
+ v8::Local<v8::Value> InstanceLocal(v8::Isolate* isolate) {
+ return instance_.NewLocal(isolate);
+ }
+ v8::Local<v8::Function> ProcessLocal(v8::Isolate* isolate) {
+ return process_.NewLocal(isolate);
+ }
+
+ void Trace(blink::Visitor* visitor) {
+ visitor->Trace(instance_.Cast<v8::Value>());
+ visitor->Trace(process_.Cast<v8::Value>());
+ }
+
+ private:
+ // This object keeps the object and process function alive.
+ // It participates in wrapper tracing as it holds onto V8 wrappers.
+ TraceWrapperV8Reference<v8::Value> instance_;
+ TraceWrapperV8Reference<v8::Function> process_;
+};
+
+TaskWorkletGlobalScope::TaskWorkletGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params,
+ WorkerThread* thread)
+ : WorkletGlobalScope(std::move(creation_params),
+ thread->GetWorkerReportingProxy(),
+ thread) {}
+
+void TaskWorkletGlobalScope::Trace(blink::Visitor* visitor) {
+ WorkletGlobalScope::Trace(visitor);
+ visitor->Trace(task_definitions_);
+}
+
+void TaskWorkletGlobalScope::registerTask(const String& name,
+ const ScriptValue& constructor_value,
+ ExceptionState& exception_state) {
+ DCHECK(IsContextThread());
+ if (task_definitions_.Contains(name)) {
+ exception_state.ThrowDOMException(
+ DOMExceptionCode::kNotSupportedError,
+ "A class with name:'" + name + "' is already registered.");
+ return;
+ }
+
+ if (name.IsEmpty()) {
+ exception_state.ThrowTypeError("The empty string is not a valid name.");
+ return;
+ }
+
+ v8::Isolate* isolate = ScriptController()->GetScriptState()->GetIsolate();
+ v8::Local<v8::Context> context = ScriptController()->GetContext();
+
+ DCHECK(constructor_value.V8Value()->IsFunction());
+ v8::Local<v8::Function> constructor =
+ v8::Local<v8::Function>::Cast(constructor_value.V8Value());
+
+ v8::Local<v8::Object> prototype;
+ if (!V8ObjectParser::ParsePrototype(context, constructor, &prototype,
+ &exception_state))
+ return;
+
+ v8::Local<v8::Function> process;
+ if (!V8ObjectParser::ParseFunction(context, prototype, "process", &process,
+ &exception_state))
+ return;
+
+ v8::Local<v8::Value> instance;
+ bool did_construct =
+ V8ScriptRunner::CallAsConstructor(isolate, constructor, this)
+ .ToLocal(&instance);
+ if (!did_construct) {
+ exception_state.ThrowTypeError("Failed to construct TaskProcessor");
+ return;
+ }
+
+ TaskDefinition* definition = new TaskDefinition(isolate, instance, process);
+ task_definitions_.Set(name, definition);
+}
+
+v8::Local<v8::Value> TaskWorkletGlobalScope::GetInstanceForName(
+ const String& name,
+ v8::Isolate* isolate) {
+ TaskDefinition* definition = task_definitions_.at(name);
+ return definition ? definition->InstanceLocal(isolate)
+ : v8::Local<v8::Value>();
+}
+
+v8::Local<v8::Function> TaskWorkletGlobalScope::GetProcessFunctionForName(
+ const String& name,
+ v8::Isolate* isolate) {
+ TaskDefinition* definition = task_definitions_.at(name);
+ return definition ? definition->ProcessLocal(isolate)
+ : v8::Local<v8::Function>();
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h
new file mode 100644
index 00000000000..1e4ebb717e8
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h
@@ -0,0 +1,38 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_GLOBAL_SCOPE_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_GLOBAL_SCOPE_H_
+
+#include "third_party/blink/renderer/bindings/core/v8/script_value.h"
+#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
+#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
+
+namespace blink {
+class ExceptionState;
+class TaskDefinition;
+
+class TaskWorkletGlobalScope : public WorkletGlobalScope {
+ DEFINE_WRAPPERTYPEINFO();
+
+ public:
+ TaskWorkletGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
+ WorkerThread*);
+ ~TaskWorkletGlobalScope() override = default;
+ void Trace(blink::Visitor*) override;
+
+ void registerTask(const String& name,
+ const ScriptValue& constructor_value,
+ ExceptionState&);
+ v8::Local<v8::Value> GetInstanceForName(const String&, v8::Isolate*);
+ v8::Local<v8::Function> GetProcessFunctionForName(const String&,
+ v8::Isolate*);
+
+ private:
+ HeapHashMap<String, TraceWrapperMember<TaskDefinition>> task_definitions_;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_TASK_WORKLET_GLOBAL_SCOPE_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl
new file mode 100644
index 00000000000..4e7caced021
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.idl
@@ -0,0 +1,10 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=WorkerTaskQueue,
+ Global=(Worklet,TaskWorklet)
+] interface TaskWorkletGlobalScope : WorkletGlobalScope {
+ [RaisesException] void registerTask(DOMString name, CallbackFunctionTreatedAsScriptValue taskConstructor);
+};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc
index fd79626be2a..bf4e433a239 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.cc
@@ -6,56 +6,15 @@
#include "services/service_manager/public/cpp/interface_provider.h"
#include "third_party/blink/public/platform/dedicated_worker_factory.mojom-blink.h"
-#include "third_party/blink/renderer/bindings/core/v8/serialization/serialized_script_value.h"
-#include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h"
-#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
-#include "third_party/blink/renderer/core/dom/abort_signal.h"
-#include "third_party/blink/renderer/core/execution_context/execution_context.h"
-#include "third_party/blink/renderer/core/inspector/main_thread_debugger.h"
+#include "third_party/blink/renderer/core/dom/document.h"
+#include "third_party/blink/renderer/core/frame/local_frame.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
-#include "third_party/blink/renderer/core/probe/core_probes.h"
-#include "third_party/blink/renderer/core/workers/dedicated_worker_messaging_proxy.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h"
#include "third_party/blink/renderer/core/workers/threaded_object_proxy_base.h"
-#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_options.h"
-#include "third_party/blink/renderer/platform/bindings/exception_state.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
-#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
namespace blink {
-class ThreadPoolWorkerGlobalScope final : public WorkerGlobalScope {
- public:
- ThreadPoolWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params,
- WorkerThread* thread)
- : WorkerGlobalScope(std::move(creation_params),
- thread,
- CurrentTimeTicks()) {}
-
- ~ThreadPoolWorkerGlobalScope() override = default;
-
- // EventTarget
- const AtomicString& InterfaceName() const override {
- // TODO(japhet): Replaces this with
- // EventTargetNames::ThreadPoolWorkerGlobalScope.
- return EventTargetNames::DedicatedWorkerGlobalScope;
- }
-
- // WorkerGlobalScope
- void ImportModuleScript(
- const KURL& module_url_record,
- FetchClientSettingsObjectSnapshot* outside_settings_object,
- network::mojom::FetchCredentialsMode) override {
- // TODO(japhet): Consider whether modules should be supported.
- NOTREACHED();
- }
-
- void ExceptionThrown(ErrorEvent*) override {}
-};
-
class ThreadPoolObjectProxy final : public ThreadedObjectProxyBase {
public:
ThreadPoolObjectProxy(ThreadPoolMessagingProxy* messaging_proxy,
@@ -87,8 +46,8 @@ class ThreadPoolMessagingProxy final : public ThreadedMessagingProxyBase {
WorkerBackingThreadStartupData::CreateDefault());
}
std::unique_ptr<WorkerThread> CreateWorkerThread() override {
- return std::make_unique<ThreadPoolThread>(GetExecutionContext(),
- *object_proxy_.get());
+ return std::make_unique<ThreadPoolThread>(
+ GetExecutionContext(), *object_proxy_.get(), ThreadPoolThread::kWorker);
}
ThreadPoolThread* GetWorkerThread() const {
@@ -100,22 +59,6 @@ class ThreadPoolMessagingProxy final : public ThreadedMessagingProxyBase {
std::unique_ptr<ThreadPoolObjectProxy> object_proxy_;
};
-ThreadPoolThread::ThreadPoolThread(ExecutionContext* parent_execution_context,
- ThreadPoolObjectProxy& object_proxy)
- : WorkerThread(object_proxy) {
- FrameOrWorkerScheduler* scheduler =
- parent_execution_context ? parent_execution_context->GetScheduler()
- : nullptr;
- worker_backing_thread_ =
- WorkerBackingThread::Create(ThreadCreationParams(GetThreadType())
- .SetFrameOrWorkerScheduler(scheduler));
-}
-
-WorkerOrWorkletGlobalScope* ThreadPoolThread::CreateWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- return new ThreadPoolWorkerGlobalScope(std::move(creation_params), this);
-}
-
service_manager::mojom::blink::InterfaceProviderPtrInfo
ConnectToWorkerInterfaceProviderForThreadPool(
ExecutionContext* execution_context,
@@ -165,12 +108,15 @@ ThreadPoolThread* ThreadPool::CreateNewThread() {
std::unique_ptr<WorkerSettings> settings =
std::make_unique<WorkerSettings>(GetFrame()->GetSettings());
+ // WebWorkerFetchContext is provided later in
+ // ThreadedMessagingProxyBase::InitializeWorkerThread().
proxy->StartWorker(std::make_unique<GlobalScopeCreationParams>(
- context->Url(), ScriptType::kClassic, context->UserAgent(),
- context->GetContentSecurityPolicy()->Headers(), kReferrerPolicyDefault,
- context->GetSecurityOrigin(), context->IsSecureContext(),
- context->GetHttpsState(), WorkerClients::Create(),
- context->GetSecurityContext().AddressSpace(),
+ context->Url(), mojom::ScriptType::kClassic, context->UserAgent(),
+ nullptr /* web_worker_fetch_context */,
+ context->GetContentSecurityPolicy()->Headers(),
+ network::mojom::ReferrerPolicy::kDefault, context->GetSecurityOrigin(),
+ context->IsSecureContext(), context->GetHttpsState(),
+ WorkerClients::Create(), context->GetSecurityContext().AddressSpace(),
OriginTrialContext::GetTokens(context).get(), devtools_worker_token,
std::move(settings), kV8CacheOptionsDefault,
nullptr /* worklet_module_responses_map */,
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h
index af950edb7bf..ff651fa06cc 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool.h
@@ -5,55 +5,17 @@
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_H_
-#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
-#include "third_party/blink/renderer/core/workers/worker_thread.h"
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
#include "third_party/blink/renderer/platform/supplementable.h"
namespace blink {
-
class Document;
class ThreadPoolMessagingProxy;
-class ThreadPoolObjectProxy;
-
-class ThreadPoolThread final : public WorkerThread {
- public:
- ThreadPoolThread(ExecutionContext*, ThreadPoolObjectProxy&);
- ~ThreadPoolThread() override = default;
-
- void IncrementTasksInProgressCount() {
- DCHECK(IsMainThread());
- tasks_in_progress_++;
- }
- void DecrementTasksInProgressCount() {
- DCHECK(IsMainThread());
- DCHECK_GT(tasks_in_progress_, 0u);
- tasks_in_progress_--;
- }
- size_t GetTasksInProgressCount() const {
- DCHECK(IsMainThread());
- return tasks_in_progress_;
- }
-
- private:
- WorkerBackingThread& GetWorkerBackingThread() override {
- return *worker_backing_thread_;
- }
- void ClearWorkerBackingThread() override { worker_backing_thread_ = nullptr; }
-
- WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
- std::unique_ptr<GlobalScopeCreationParams> creation_params) override;
-
- WebThreadType GetThreadType() const override {
- // TODO(japhet): Replace with WebThreadType::kThreadPoolWorkerThread.
- return WebThreadType::kDedicatedWorkerThread;
- }
- std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
- size_t tasks_in_progress_ = 0;
-};
class ThreadPool final : public GarbageCollectedFinalized<ThreadPool>,
public Supplement<Document>,
- public ContextLifecycleObserver {
+ public ContextLifecycleObserver,
+ public ThreadPoolThreadProvider {
USING_GARBAGE_COLLECTED_MIXIN(ThreadPool);
EAGERLY_FINALIZE();
@@ -62,7 +24,7 @@ class ThreadPool final : public GarbageCollectedFinalized<ThreadPool>,
static ThreadPool* From(Document&);
~ThreadPool();
- ThreadPoolThread* GetLeastBusyThread();
+ ThreadPoolThread* GetLeastBusyThread() override;
void ContextDestroyed(ExecutionContext*) final;
void Trace(blink::Visitor*) final;
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc
new file mode 100644
index 00000000000..a6371c7adb4
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.cc
@@ -0,0 +1,69 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#include "third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h"
+
+#include "third_party/blink/renderer/core/execution_context/execution_context.h"
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet_global_scope.h"
+#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
+#include "third_party/blink/renderer/core/workers/threaded_object_proxy_base.h"
+#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
+
+namespace blink {
+
+namespace {
+
+class ThreadPoolWorkerGlobalScope final : public WorkerGlobalScope {
+ public:
+ ThreadPoolWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params,
+ WorkerThread* thread)
+ : WorkerGlobalScope(std::move(creation_params),
+ thread,
+ CurrentTimeTicks()) {}
+
+ ~ThreadPoolWorkerGlobalScope() override = default;
+
+ // EventTarget
+ const AtomicString& InterfaceName() const override {
+ // TODO(japhet): Replaces this with
+ // EventTargetNames::ThreadPoolWorkerGlobalScope.
+ return event_target_names::kDedicatedWorkerGlobalScope;
+ }
+
+ // WorkerGlobalScope
+ void ImportModuleScript(
+ const KURL& module_url_record,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ network::mojom::FetchCredentialsMode) override {
+ // TODO(japhet): Consider whether modules should be supported.
+ NOTREACHED();
+ }
+
+ void ExceptionThrown(ErrorEvent*) override {}
+};
+
+} // anonymous namespace
+
+ThreadPoolThread::ThreadPoolThread(ExecutionContext* parent_execution_context,
+ ThreadedObjectProxyBase& object_proxy,
+ ThreadBackingPolicy backing_policy)
+ : WorkerThread(object_proxy), backing_policy_(backing_policy) {
+ DCHECK(parent_execution_context);
+ worker_backing_thread_ = WorkerBackingThread::Create(
+ ThreadCreationParams(GetThreadType())
+ .SetFrameOrWorkerScheduler(parent_execution_context->GetScheduler()));
+}
+
+WorkerOrWorkletGlobalScope* ThreadPoolThread::CreateWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params) {
+ if (backing_policy_ == kWorker)
+ return new ThreadPoolWorkerGlobalScope(std::move(creation_params), this);
+ return new TaskWorkletGlobalScope(std::move(creation_params), this);
+}
+
+} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h
new file mode 100644
index 00000000000..6c8871a0487
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/thread_pool_thread.h
@@ -0,0 +1,65 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_THREAD_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_THREAD_H_
+
+#include "third_party/blink/renderer/core/workers/worker_backing_thread.h"
+#include "third_party/blink/renderer/core/workers/worker_thread.h"
+
+namespace blink {
+class ExecutionContext;
+class ThreadedObjectProxyBase;
+
+class ThreadPoolThread final : public WorkerThread {
+ public:
+ enum ThreadBackingPolicy { kWorker, kWorklet };
+
+ ThreadPoolThread(ExecutionContext*,
+ ThreadedObjectProxyBase&,
+ ThreadBackingPolicy);
+ ~ThreadPoolThread() override = default;
+
+ void IncrementTasksInProgressCount() {
+ DCHECK(IsMainThread());
+ tasks_in_progress_++;
+ }
+ void DecrementTasksInProgressCount() {
+ DCHECK(IsMainThread());
+ DCHECK_GT(tasks_in_progress_, 0u);
+ tasks_in_progress_--;
+ }
+ size_t GetTasksInProgressCount() const {
+ DCHECK(IsMainThread());
+ return tasks_in_progress_;
+ }
+
+ bool IsWorklet() const { return backing_policy_ == kWorklet; }
+
+ private:
+ WorkerBackingThread& GetWorkerBackingThread() override {
+ return *worker_backing_thread_;
+ }
+ void ClearWorkerBackingThread() override { worker_backing_thread_ = nullptr; }
+
+ WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
+ std::unique_ptr<GlobalScopeCreationParams> creation_params) override;
+
+ WebThreadType GetThreadType() const override {
+ // TODO(japhet): Replace with WebThreadType::kThreadPoolWorkerThread.
+ return WebThreadType::kDedicatedWorkerThread;
+ }
+ std::unique_ptr<WorkerBackingThread> worker_backing_thread_;
+ size_t tasks_in_progress_ = 0;
+ const ThreadBackingPolicy backing_policy_;
+};
+
+class ThreadPoolThreadProvider {
+ public:
+ virtual ThreadPoolThread* GetLeastBusyThread() = 0;
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_THREAD_POOL_THREAD_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h
new file mode 100644
index 00000000000..f4446c8c898
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.h
@@ -0,0 +1,23 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WINDOW_TASK_WORKLET_H_
+#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WINDOW_TASK_WORKLET_H_
+
+#include "third_party/blink/renderer/core/workers/experimental/task_worklet.h"
+
+namespace blink {
+
+class WindowTaskWorklet {
+ STATIC_ONLY(WindowTaskWorklet);
+
+ public:
+ static TaskWorklet* taskWorklet(LocalDOMWindow& window) {
+ return TaskWorklet::From(window);
+ }
+};
+
+} // namespace blink
+
+#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_EXPERIMENTAL_WINDOW_TASK_WORKLET_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl
new file mode 100644
index 00000000000..626225faa7b
--- /dev/null
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/window_task_worklet.idl
@@ -0,0 +1,11 @@
+// Copyright 2018 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+[
+ RuntimeEnabled=WorkerTaskQueue,
+ ImplementedAs=WindowTaskWorklet,
+ SecureContext
+] partial interface Window {
+ [SameObject] readonly attribute TaskWorklet taskWorklet;
+};
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc
index faf398bfb77..45c42286143 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.cc
@@ -39,23 +39,17 @@ WorkerTaskQueue::WorkerTaskQueue(Document* document, TaskType task_type)
ScriptPromise WorkerTaskQueue::postFunction(
ScriptState* script_state,
- const ScriptValue& task,
+ const ScriptValue& function,
AbortSignal* signal,
const Vector<ScriptValue>& arguments) {
DCHECK(document_->IsContextThread());
- DCHECK(task.IsFunction());
-
- ThreadPoolTask* thread_pool_task = new ThreadPoolTask(
- ThreadPool::From(*document_), script_state->GetIsolate(), task, arguments,
- task_type_);
- if (signal) {
- signal->AddAlgorithm(
- WTF::Bind(&ThreadPoolTask::Cancel, thread_pool_task->GetWeakPtr()));
- }
- ScriptValue value = thread_pool_task->GetResult(script_state);
- DCHECK(value.V8Value()->IsPromise());
+ DCHECK(function.IsFunction());
- return ScriptPromise(script_state, value.V8Value());
+ Task* task = new Task(ThreadPool::From(*document_), script_state, function,
+ arguments, task_type_);
+ if (signal)
+ signal->AddAlgorithm(WTF::Bind(&Task::cancel, WrapWeakPersistent(task)));
+ return task->result(script_state);
}
Task* WorkerTaskQueue::postTask(ScriptState* script_state,
@@ -63,11 +57,8 @@ Task* WorkerTaskQueue::postTask(ScriptState* script_state,
const Vector<ScriptValue>& arguments) {
DCHECK(document_->IsContextThread());
DCHECK(function.IsFunction());
-
- ThreadPoolTask* thread_pool_task = new ThreadPoolTask(
- ThreadPool::From(*document_), script_state->GetIsolate(), function,
- arguments, task_type_);
- return new Task(thread_pool_task);
+ return new Task(ThreadPool::From(*document_), script_state, function,
+ arguments, task_type_);
}
void WorkerTaskQueue::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h
index 6eb29b67597..0872c73a929 100644
--- a/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h
+++ b/chromium/third_party/blink/renderer/core/workers/experimental/worker_task_queue.h
@@ -30,12 +30,12 @@ class CORE_EXPORT WorkerTaskQueue : public ScriptWrappable {
~WorkerTaskQueue() override = default;
ScriptPromise postFunction(ScriptState*,
- const ScriptValue& task,
+ const ScriptValue& function,
AbortSignal*,
const Vector<ScriptValue>& arguments);
Task* postTask(ScriptState*,
- const ScriptValue& task,
+ const ScriptValue& function,
const Vector<ScriptValue>& arguments);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc
index d49696c4306..51b2c32b5e8 100644
--- a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc
+++ b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.cc
@@ -11,11 +11,11 @@ namespace blink {
GlobalScopeCreationParams::GlobalScopeCreationParams(
const KURL& script_url,
- // TODO(asamidoi): Replace ScriptType to mojom::ScriptType
- ScriptType script_type,
+ mojom::ScriptType script_type,
const String& user_agent,
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context,
const Vector<CSPHeaderAndType>& content_security_policy_parsed_headers,
- ReferrerPolicy referrer_policy,
+ network::mojom::ReferrerPolicy referrer_policy,
const SecurityOrigin* starter_origin,
bool starter_secure_context,
HttpsState starter_https_state,
@@ -34,6 +34,7 @@ GlobalScopeCreationParams::GlobalScopeCreationParams(
: script_url(script_url.Copy()),
script_type(script_type),
user_agent(user_agent.IsolatedCopy()),
+ web_worker_fetch_context(std::move(web_worker_fetch_context)),
referrer_policy(referrer_policy),
starter_origin(starter_origin ? starter_origin->IsolatedCopy() : nullptr),
starter_secure_context(starter_secure_context),
diff --git a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h
index dc8b5a119c2..113e5d0773b 100644
--- a/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h
+++ b/chromium/third_party/blink/renderer/core/workers/global_scope_creation_params.h
@@ -9,9 +9,12 @@
#include "base/macros.h"
#include "base/optional.h"
#include "base/unguessable_token.h"
+#include "services/network/public/mojom/referrer_policy.mojom-shared.h"
#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h"
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/public/mojom/net/ip_address_space.mojom-blink.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
+#include "third_party/blink/public/platform/web_worker_fetch_context.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
@@ -24,7 +27,6 @@
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_response_headers.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-#include "third_party/blink/renderer/platform/weborigin/referrer_policy.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
namespace blink {
@@ -39,11 +41,11 @@ struct CORE_EXPORT GlobalScopeCreationParams final {
public:
GlobalScopeCreationParams(
const KURL& script_url,
- // TODO(asamidoi): Replace ScriptType to mojom::ScriptType
- ScriptType script_type,
+ mojom::ScriptType script_type,
const String& user_agent,
+ scoped_refptr<WebWorkerFetchContext>,
const Vector<CSPHeaderAndType>& content_security_policy_parsed_headers,
- ReferrerPolicy referrer_policy,
+ network::mojom::ReferrerPolicy referrer_policy,
const SecurityOrigin*,
bool starter_secure_context,
HttpsState starter_https_state,
@@ -75,9 +77,11 @@ struct CORE_EXPORT GlobalScopeCreationParams final {
// workers.
KURL script_url;
- ScriptType script_type;
+ mojom::ScriptType script_type;
String user_agent;
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context;
+
// |content_security_policy_parsed_headers| and
// |content_security_policy_raw_headers| are mutually exclusive.
// |content_security_policy_parsed_headers| is an empty vector
@@ -86,7 +90,7 @@ struct CORE_EXPORT GlobalScopeCreationParams final {
base::Optional<ContentSecurityPolicyResponseHeaders>
content_security_policy_raw_headers;
- ReferrerPolicy referrer_policy;
+ network::mojom::ReferrerPolicy referrer_policy;
std::unique_ptr<Vector<String>> origin_trial_tokens;
// The SecurityOrigin of the Document creating a Worker/Worklet.
diff --git a/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc b/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc
index 4ce377db000..6e9e5b9d44a 100644
--- a/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc
+++ b/chromium/third_party/blink/renderer/core/workers/installed_scripts_manager.cc
@@ -27,13 +27,13 @@ InstalledScriptsManager::ScriptData::GetContentSecurityPolicyResponseHeaders() {
}
String InstalledScriptsManager::ScriptData::GetReferrerPolicy() {
- return headers_.Get(HTTPNames::Referrer_Policy);
+ return headers_.Get(http_names::kReferrerPolicy);
}
std::unique_ptr<Vector<String>>
InstalledScriptsManager::ScriptData::CreateOriginTrialTokens() {
return OriginTrialContext::ParseHeaderValue(
- headers_.Get(HTTPNames::Origin_Trial));
+ headers_.Get(http_names::kOriginTrial));
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc b/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc
index 6771bef6856..4df15f6fadb 100644
--- a/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/main_thread_worklet_test.cc
@@ -64,7 +64,8 @@ class MainThreadWorkletTest : public PageTestBase {
reporting_proxy_ =
std::make_unique<MainThreadWorkletReportingProxyForTest>(document);
auto creation_params = std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */,
document->GetContentSecurityPolicy()->Headers(),
document->GetReferrerPolicy(), document->GetSecurityOrigin(),
document->IsSecureContext(), document->GetHttpsState(),
@@ -72,8 +73,8 @@ class MainThreadWorkletTest : public PageTestBase {
OriginTrialContext::GetTokens(document).get(),
base::UnguessableToken::Create(), nullptr /* worker_settings */,
kV8CacheOptionsDefault, new WorkletModuleResponsesMap);
- global_scope_ = new WorkletGlobalScope(std::move(creation_params),
- *reporting_proxy_, &GetFrame());
+ global_scope_ = MakeGarbageCollected<WorkletGlobalScope>(
+ std::move(creation_params), *reporting_proxy_, &GetFrame());
EXPECT_TRUE(global_scope_->IsMainThreadWorkletGlobalScope());
EXPECT_FALSE(global_scope_->IsThreadedWorkletGlobalScope());
}
diff --git a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc
index 7b3da53d694..1fd643b3b02 100644
--- a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc
+++ b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.cc
@@ -17,11 +17,11 @@ ParentExecutionContextTaskRunners* ParentExecutionContextTaskRunners::Create(
ExecutionContext* context) {
DCHECK(context);
DCHECK(context->IsContextThread());
- return new ParentExecutionContextTaskRunners(context);
+ return MakeGarbageCollected<ParentExecutionContextTaskRunners>(context);
}
ParentExecutionContextTaskRunners* ParentExecutionContextTaskRunners::Create() {
- return new ParentExecutionContextTaskRunners(nullptr);
+ return MakeGarbageCollected<ParentExecutionContextTaskRunners>(nullptr);
}
ParentExecutionContextTaskRunners::ParentExecutionContextTaskRunners(
@@ -34,9 +34,8 @@ ParentExecutionContextTaskRunners::ParentExecutionContextTaskRunners(
TaskType::kInternalLoading, TaskType::kInternalTest,
TaskType::kInternalMedia, TaskType::kInternalInspector,
TaskType::kInternalWorker}) {
- auto task_runner =
- context ? context->GetTaskRunner(type)
- : Platform::Current()->CurrentThread()->GetTaskRunner();
+ auto task_runner = context ? context->GetTaskRunner(type)
+ : Thread::Current()->GetTaskRunner();
task_runners_.insert(type, std::move(task_runner));
}
}
@@ -54,7 +53,7 @@ void ParentExecutionContextTaskRunners::Trace(blink::Visitor* visitor) {
void ParentExecutionContextTaskRunners::ContextDestroyed(ExecutionContext*) {
MutexLocker lock(mutex_);
for (auto& entry : task_runners_)
- entry.value = Platform::Current()->CurrentThread()->GetTaskRunner();
+ entry.value = Thread::Current()->GetTaskRunner();
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h
index 87f22db0c14..05adfb5d2b8 100644
--- a/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h
+++ b/chromium/third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h
@@ -35,6 +35,10 @@ class CORE_EXPORT ParentExecutionContextTaskRunners final
// tests that don't have a parent frame.
static ParentExecutionContextTaskRunners* Create();
+ // ExecutionContext could be nullptr if the worker is not associated with a
+ // particular context.
+ explicit ParentExecutionContextTaskRunners(ExecutionContext*);
+
// Might return nullptr for unsupported task types. This can be called from
// any threads.
scoped_refptr<base::SingleThreadTaskRunner> Get(TaskType)
@@ -48,10 +52,6 @@ class CORE_EXPORT ParentExecutionContextTaskRunners final
WTF::IntHash<TaskType>,
TaskTypeTraits>;
- // ExecutionContext could be nullptr if the worker is not associated with a
- // particular context.
- explicit ParentExecutionContextTaskRunners(ExecutionContext*);
-
void ContextDestroyed(ExecutionContext*) LOCKS_EXCLUDED(mutex_) override;
Mutex mutex_;
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
index e222bdefae3..4433a999d5f 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker.cc
@@ -58,7 +58,7 @@ SharedWorker* SharedWorker::Create(ExecutionContext* context,
UseCounter::Count(context, WebFeature::kSharedWorkerStart);
- SharedWorker* worker = new SharedWorker(context);
+ SharedWorker* worker = MakeGarbageCollected<SharedWorker>(context);
MessageChannel* channel = MessageChannel::Create(context);
worker->port_ = channel->port1();
@@ -99,7 +99,7 @@ SharedWorker* SharedWorker::Create(ExecutionContext* context,
SharedWorker::~SharedWorker() = default;
const AtomicString& SharedWorker::InterfaceName() const {
- return EventTargetNames::SharedWorker;
+ return event_target_names::kSharedWorker;
}
bool SharedWorker::HasPendingActivity() const {
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker.h b/chromium/third_party/blink/renderer/core/workers/shared_worker.h
index 9b438d69eb7..3a1851ebd65 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker.h
@@ -54,6 +54,8 @@ class CORE_EXPORT SharedWorker final
const String& url,
const String& name,
ExceptionState&);
+
+ explicit SharedWorker(ExecutionContext*);
~SharedWorker() override;
MessagePort* port() const { return port_.Get(); }
@@ -68,8 +70,6 @@ class CORE_EXPORT SharedWorker final
void Trace(blink::Visitor*) override;
private:
- explicit SharedWorker(ExecutionContext*);
-
Member<MessagePort> port_;
bool is_being_connected_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc
index 5d4894caeca..262aeea034f 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.cc
@@ -15,10 +15,9 @@ SharedWorkerContentSettingsProxy::SharedWorkerContentSettingsProxy(
SharedWorkerContentSettingsProxy::~SharedWorkerContentSettingsProxy() = default;
bool SharedWorkerContentSettingsProxy::AllowIndexedDB(
- const WebString& name,
const WebSecurityOrigin& origin) {
bool result = false;
- GetService()->AllowIndexedDB(name, &result);
+ GetService()->AllowIndexedDB(&result);
return result;
}
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h
index 1fb2dccc283..f1a3f2eec1e 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_content_settings_proxy.h
@@ -22,7 +22,7 @@ class SharedWorkerContentSettingsProxy : public WebContentSettingsClient {
~SharedWorkerContentSettingsProxy() override;
// WebContentSettingsClient overrides.
- bool AllowIndexedDB(const WebString& name, const WebSecurityOrigin&) override;
+ bool AllowIndexedDB(const WebSecurityOrigin&) override;
bool RequestFileSystemAccessSync() override;
private:
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc
index 6ae503c2c98..c68d18e1b3d 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.cc
@@ -52,7 +52,7 @@ SharedWorkerGlobalScope::SharedWorkerGlobalScope(
SharedWorkerGlobalScope::~SharedWorkerGlobalScope() = default;
const AtomicString& SharedWorkerGlobalScope::InterfaceName() const {
- return EventTargetNames::SharedWorkerGlobalScope;
+ return event_target_names::kSharedWorkerGlobalScope;
}
// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
@@ -81,9 +81,10 @@ void SharedWorkerGlobalScope::ConnectPausable(MessagePortChannel channel) {
MessagePort* port = MessagePort::Create(*this);
port->Entangle(std::move(channel));
- MessageEvent* event = MessageEvent::Create(new MessagePortArray(1, port),
- String(), String(), port);
- event->initEvent(EventTypeNames::connect, false, false);
+ MessageEvent* event =
+ MessageEvent::Create(MakeGarbageCollected<MessagePortArray>(1, port),
+ String(), String(), port);
+ event->initEvent(event_type_names::kConnect, false, false);
DispatchEvent(*event);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h
index 9f51411a1f8..8b5a667f308 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.h
@@ -64,7 +64,7 @@ class SharedWorkerGlobalScope final : public WorkerGlobalScope {
network::mojom::FetchCredentialsMode) override;
// Setters/Getters for attributes in SharedWorkerGlobalScope.idl
- DEFINE_ATTRIBUTE_EVENT_LISTENER(connect);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(connect, kConnect);
String name() const { return name_; }
void ConnectPausable(MessagePortChannel channel);
@@ -76,6 +76,14 @@ class SharedWorkerGlobalScope final : public WorkerGlobalScope {
const String name_;
};
+
+template <>
+struct DowncastTraits<SharedWorkerGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsSharedWorkerGlobalScope();
+ }
+};
+
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_SHARED_WORKER_GLOBAL_SCOPE_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl
index 9b3d13b296d..c26b4c4af34 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_global_scope.idl
@@ -34,7 +34,7 @@
Global=(Worker,SharedWorker),
Exposed=SharedWorker
] interface SharedWorkerGlobalScope : WorkerGlobalScope {
- readonly attribute DOMString name;
+ [Replaceable] readonly attribute DOMString name;
// TODO(foolip): readonly attribute ApplicationCache applicationCache;
void close();
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc
index 5433c7444d9..a1def054e31 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.cc
@@ -58,18 +58,6 @@ void SharedWorkerReportingProxy::ReportConsoleMessage(MessageSource,
// Not supported in SharedWorker.
}
-void SharedWorkerReportingProxy::PostMessageToPageInspector(
- int session_id,
- const String& message) {
- DCHECK(!IsMainThread());
- PostCrossThreadTask(
- *parent_execution_context_task_runners_->Get(
- TaskType::kInternalInspector),
- FROM_HERE,
- CrossThreadBind(&WebSharedWorkerImpl::PostMessageToPageInspector,
- CrossThreadUnretained(worker_), session_id, message));
-}
-
void SharedWorkerReportingProxy::DidCloseWorkerGlobalScope() {
DCHECK(!IsMainThread());
PostCrossThreadTask(
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h
index 280e2da2ce5..ad84445fe28 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_reporting_proxy.h
@@ -35,7 +35,6 @@ class SharedWorkerReportingProxy final
MessageLevel,
const String& message,
SourceLocation*) override;
- void PostMessageToPageInspector(int session_id, const WTF::String&) override;
void DidEvaluateClassicScript(bool success) override {}
void DidCloseWorkerGlobalScope() override;
void WillDestroyWorkerGlobalScope() override {}
diff --git a/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc b/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc
index a5c62bfc32c..58643083e14 100644
--- a/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/shared_worker_thread.cc
@@ -53,8 +53,8 @@ void SharedWorkerThread::ClearWorkerBackingThread() {
WorkerOrWorkletGlobalScope* SharedWorkerThread::CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) {
- return new SharedWorkerGlobalScope(name_, std::move(creation_params), this,
- time_origin_);
+ return MakeGarbageCollected<SharedWorkerGlobalScope>(
+ name_, std::move(creation_params), this, time_origin_);
}
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc
index 79a53c6e7d0..124ee1e0c70 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.cc
@@ -10,13 +10,12 @@
#include "third_party/blink/renderer/bindings/core/v8/source_location.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
-#include "third_party/blink/renderer/core/frame/local_frame.h"
-#include "third_party/blink/renderer/core/frame/local_frame_client.h"
+#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/devtools_agent.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/loader/document_loader.h"
-#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_fetcher.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
@@ -31,7 +30,6 @@ static int g_live_messaging_proxy_count = 0;
ThreadedMessagingProxyBase::ThreadedMessagingProxyBase(
ExecutionContext* execution_context)
: execution_context_(execution_context),
- worker_inspector_proxy_(WorkerInspectorProxy::Create()),
parent_execution_context_task_runners_(
ParentExecutionContextTaskRunners::Create(execution_context_.Get())),
terminate_sync_load_event_(
@@ -53,7 +51,6 @@ int ThreadedMessagingProxyBase::ProxyCount() {
void ThreadedMessagingProxyBase::Trace(blink::Visitor* visitor) {
visitor->Trace(execution_context_);
- visitor->Trace(worker_inspector_proxy_);
}
void ThreadedMessagingProxyBase::InitializeWorkerThread(
@@ -63,44 +60,22 @@ void ThreadedMessagingProxyBase::InitializeWorkerThread(
KURL script_url = global_scope_creation_params->script_url.Copy();
- std::unique_ptr<WebWorkerFetchContext> web_worker_fetch_context;
- if (auto* document = DynamicTo<Document>(execution_context_.Get())) {
- LocalFrame* frame = document->GetFrame();
- web_worker_fetch_context = frame->Client()->CreateWorkerFetchContext();
- // |web_worker_fetch_context| is null in some unit tests.
- if (web_worker_fetch_context) {
- web_worker_fetch_context->SetApplicationCacheHostID(
- GetExecutionContext()->Fetcher()->Context().ApplicationCacheHostID());
- web_worker_fetch_context->SetIsOnSubframe(!frame->IsMainFrame());
- }
- } else if (execution_context_->IsWorkerGlobalScope()) {
- web_worker_fetch_context =
- static_cast<WorkerFetchContext&>(
- ToWorkerGlobalScope(execution_context_)->Fetcher()->Context())
- .GetWebWorkerFetchContext()
- ->CloneForNestedWorker();
- }
-
- if (web_worker_fetch_context) {
- web_worker_fetch_context->SetTerminateSyncLoadEvent(
- &terminate_sync_load_event_);
- ProvideWorkerFetchContextToWorker(
- global_scope_creation_params->worker_clients,
- std::move(web_worker_fetch_context));
+ if (global_scope_creation_params->web_worker_fetch_context) {
+ global_scope_creation_params->web_worker_fetch_context
+ ->SetTerminateSyncLoadEvent(&terminate_sync_load_event_);
}
worker_thread_ = CreateWorkerThread();
- worker_thread_->Start(
- std::move(global_scope_creation_params), thread_startup_data,
- GetWorkerInspectorProxy()->ShouldPauseOnWorkerStart(execution_context_),
- GetParentExecutionContextTaskRunners());
- GetWorkerInspectorProxy()->WorkerThreadCreated(execution_context_,
- GetWorkerThread(), script_url);
-
- if (execution_context_->IsWorkerGlobalScope()) {
- ToWorkerGlobalScope(execution_context_)
- ->GetThread()
- ->ChildThreadStartedOnWorkerThread(worker_thread_.get());
+
+ auto devtools_params = DevToolsAgent::WorkerThreadCreated(
+ execution_context_.Get(), worker_thread_.get(), script_url);
+
+ worker_thread_->Start(std::move(global_scope_creation_params),
+ thread_startup_data, std::move(devtools_params),
+ GetParentExecutionContextTaskRunners());
+
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_)) {
+ scope->GetThread()->ChildThreadStartedOnWorkerThread(worker_thread_.get());
}
}
@@ -145,12 +120,14 @@ void ThreadedMessagingProxyBase::WorkerThreadTerminated() {
// Worker/Worklet object may still exist, and it assumes that the proxy
// exists, too.
asked_to_terminate_ = true;
- WorkerThread* parent_thread =
- execution_context_->IsWorkerGlobalScope()
- ? ToWorkerGlobalScope(execution_context_)->GetThread()
- : nullptr;
+ WorkerThread* parent_thread = nullptr;
+ if (auto* scope = DynamicTo<WorkerGlobalScope>(*execution_context_))
+ parent_thread = scope->GetThread();
std::unique_ptr<WorkerThread> child_thread = std::move(worker_thread_);
- worker_inspector_proxy_->WorkerThreadTerminated();
+ if (child_thread) {
+ DevToolsAgent::WorkerThreadTerminated(execution_context_.Get(),
+ child_thread.get());
+ }
// If the parent Worker/Worklet object was already destroyed, this will
// destroy |this|.
@@ -169,18 +146,11 @@ void ThreadedMessagingProxyBase::TerminateGlobalScope() {
terminate_sync_load_event_.Signal();
- if (worker_thread_)
- worker_thread_->Terminate();
-
- worker_inspector_proxy_->WorkerThreadTerminated();
-}
-
-void ThreadedMessagingProxyBase::PostMessageToPageInspector(
- int session_id,
- const String& message) {
- DCHECK(IsParentContextThread());
- if (worker_inspector_proxy_)
- worker_inspector_proxy_->DispatchMessageFromWorker(session_id, message);
+ if (!worker_thread_)
+ return;
+ worker_thread_->Terminate();
+ DevToolsAgent::WorkerThreadTerminated(execution_context_.Get(),
+ worker_thread_.get());
}
ExecutionContext* ThreadedMessagingProxyBase::GetExecutionContext() const {
@@ -194,12 +164,6 @@ ThreadedMessagingProxyBase::GetParentExecutionContextTaskRunners() const {
return parent_execution_context_task_runners_;
}
-WorkerInspectorProxy* ThreadedMessagingProxyBase::GetWorkerInspectorProxy()
- const {
- DCHECK(IsParentContextThread());
- return worker_inspector_proxy_;
-}
-
WorkerThread* ThreadedMessagingProxyBase::GetWorkerThread() const {
DCHECK(IsParentContextThread());
return worker_thread_.get();
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h
index fa6c682bd40..d4b61b1cef5 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h
@@ -25,7 +25,6 @@ namespace blink {
class ExecutionContext;
class SourceLocation;
-class WorkerInspectorProxy;
struct GlobalScopeCreationParams;
// The base proxy class to talk to Worker/WorkletGlobalScope on a worker thread
@@ -60,7 +59,6 @@ class CORE_EXPORT ThreadedMessagingProxyBase
MessageLevel,
const String& message,
std::unique_ptr<SourceLocation>);
- void PostMessageToPageInspector(int session_id, const String&);
void WorkerThreadTerminated();
@@ -79,7 +77,6 @@ class CORE_EXPORT ThreadedMessagingProxyBase
ExecutionContext* GetExecutionContext() const;
ParentExecutionContextTaskRunners* GetParentExecutionContextTaskRunners()
const;
- WorkerInspectorProxy* GetWorkerInspectorProxy() const;
// May return nullptr after termination is requested.
WorkerThread* GetWorkerThread() const;
@@ -93,7 +90,6 @@ class CORE_EXPORT ThreadedMessagingProxyBase
virtual std::unique_ptr<WorkerThread> CreateWorkerThread() = 0;
Member<ExecutionContext> execution_context_;
- Member<WorkerInspectorProxy> worker_inspector_proxy_;
// Accessed cross-thread when worker thread posts tasks to the parent.
CrossThreadPersistent<ParentExecutionContextTaskRunners>
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc
index 7784a284c20..1730f2ef808 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.cc
@@ -10,7 +10,7 @@
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
#include "third_party/blink/renderer/core/workers/threaded_messaging_proxy_base.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
namespace blink {
@@ -43,19 +43,6 @@ void ThreadedObjectProxyBase::ReportConsoleMessage(MessageSource source,
WTF::Passed(location->Clone())));
}
-void ThreadedObjectProxyBase::PostMessageToPageInspector(
- int session_id,
- const String& message) {
- // The TaskType of Inspector tasks need to be Unthrottled because they need to
- // run even on a suspended page.
- PostCrossThreadTask(
- *GetParentExecutionContextTaskRunners()->Get(
- TaskType::kInternalInspector),
- FROM_HERE,
- CrossThreadBind(&ThreadedMessagingProxyBase::PostMessageToPageInspector,
- MessagingProxyWeakPtr(), session_id, message));
-}
-
void ThreadedObjectProxyBase::DidCloseWorkerGlobalScope() {
PostCrossThreadTask(
*GetParentExecutionContextTaskRunners()->Get(TaskType::kInternalDefault),
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h
index 69c7850a385..b8bbe9e0f27 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_object_proxy_base.h
@@ -35,7 +35,6 @@ class CORE_EXPORT ThreadedObjectProxyBase : public WorkerReportingProxy {
MessageLevel,
const String& message,
SourceLocation*) override;
- void PostMessageToPageInspector(int session_id, const String&) override;
void DidCloseWorkerGlobalScope() override;
void DidTerminateWorkerThread() override;
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc
index 8be178d7e25..dc7d022c400 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.cc
@@ -5,6 +5,7 @@
#include "third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h"
#include "base/single_thread_task_runner.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/public/platform/task_type.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/dom/document.h"
@@ -19,13 +20,12 @@
#include "third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_clients.h"
#include "third_party/blink/renderer/core/workers/worker_content_settings_client.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
#include "third_party/blink/renderer/core/workers/worklet_module_responses_map.h"
#include "third_party/blink/renderer/core/workers/worklet_pending_tasks.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -35,7 +35,8 @@ ThreadedWorkletMessagingProxy::ThreadedWorkletMessagingProxy(
void ThreadedWorkletMessagingProxy::Initialize(
WorkerClients* worker_clients,
- WorkletModuleResponsesMap* module_responses_map) {
+ WorkletModuleResponsesMap* module_responses_map,
+ const base::Optional<WorkerBackingThreadStartupData>& thread_startup_data) {
DCHECK(IsMainThread());
if (AskedToTerminate())
return;
@@ -47,16 +48,14 @@ void ThreadedWorkletMessagingProxy::Initialize(
ContentSecurityPolicy* csp = document->GetContentSecurityPolicy();
DCHECK(csp);
- ProvideWorkerFetchContextToWorker(
- worker_clients,
- document->GetFrame()->Client()->CreateWorkerFetchContext());
ProvideContentSettingsClientToWorker(
worker_clients,
document->GetFrame()->Client()->CreateWorkerContentSettingsClient());
auto global_scope_creation_params =
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ document->GetFrame()->Client()->CreateWorkerFetchContext(),
csp->Headers(), document->GetReferrerPolicy(),
document->GetSecurityOrigin(), document->IsSecureContext(),
document->GetHttpsState(), worker_clients, document->AddressSpace(),
@@ -71,7 +70,7 @@ void ThreadedWorkletMessagingProxy::Initialize(
// Worklets share the pre-initialized backing thread so that we don't have to
// specify the backing thread startup data.
InitializeWorkerThread(std::move(global_scope_creation_params),
- base::nullopt);
+ thread_startup_data);
}
void ThreadedWorkletMessagingProxy::Trace(blink::Visitor* visitor) {
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h
index caad225d996..733b29f7f98 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_messaging_proxy.h
@@ -32,7 +32,10 @@ class CORE_EXPORT ThreadedWorkletMessagingProxy
void WorkletObjectDestroyed() final;
void TerminateWorkletGlobalScope() final;
- void Initialize(WorkerClients*, WorkletModuleResponsesMap*);
+ void Initialize(
+ WorkerClients*,
+ WorkletModuleResponsesMap*,
+ const base::Optional<WorkerBackingThreadStartupData>& = base::nullopt);
void Trace(blink::Visitor*) override;
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc
index b98c1b5fa75..3a70d19ae1e 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_object_proxy.cc
@@ -33,11 +33,11 @@ void ThreadedWorkletObjectProxy::FetchAndInvokeScript(
scoped_refptr<base::SingleThreadTaskRunner> outside_settings_task_runner,
WorkletPendingTasks* pending_tasks,
WorkerThread* worker_thread) {
- WorkletGlobalScope* global_scope =
- ToWorkletGlobalScope(worker_thread->GlobalScope());
+ auto* global_scope = To<WorkletGlobalScope>(worker_thread->GlobalScope());
global_scope->FetchAndInvokeScript(
module_url_record, credentials_mode,
- new FetchClientSettingsObjectSnapshot(std::move(outside_settings_object)),
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ std::move(outside_settings_object)),
std::move(outside_settings_task_runner), pending_tasks);
}
diff --git a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc
index 4b9d4854aed..052cdb7a446 100644
--- a/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/threaded_worklet_test.cc
@@ -83,7 +83,7 @@ class ThreadedWorkletThreadForTest : public WorkerThread {
}
void TestSecurityOrigin() {
- WorkletGlobalScope* global_scope = ToWorkletGlobalScope(GlobalScope());
+ WorkletGlobalScope* global_scope = To<WorkletGlobalScope>(GlobalScope());
// The SecurityOrigin for a worklet should be a unique opaque origin, while
// the owner Document's SecurityOrigin shouldn't.
EXPECT_TRUE(global_scope->GetSecurityOrigin()->IsOpaque());
@@ -170,7 +170,7 @@ class ThreadedWorkletThreadForTest : public WorkerThread {
private:
WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) final {
- auto* global_scope = new WorkletGlobalScope(
+ auto* global_scope = MakeGarbageCollected<WorkletGlobalScope>(
std::move(creation_params), GetWorkerReportingProxy(), this);
EXPECT_FALSE(global_scope->IsMainThreadWorkletGlobalScope());
EXPECT_TRUE(global_scope->IsThreadedWorkletGlobalScope());
@@ -203,7 +203,8 @@ class ThreadedWorkletMessagingProxyForTest
std::unique_ptr<WorkerSettings> worker_settings = nullptr;
InitializeWorkerThread(
std::make_unique<GlobalScopeCreationParams>(
- document->Url(), ScriptType::kModule, document->UserAgent(),
+ document->Url(), mojom::ScriptType::kModule, document->UserAgent(),
+ nullptr /* web_worker_fetch_context */,
document->GetContentSecurityPolicy()->Headers(),
document->GetReferrerPolicy(), document->GetSecurityOrigin(),
document->IsSecureContext(), document->GetHttpsState(),
@@ -230,7 +231,8 @@ class ThreadedWorkletTest : public testing::Test {
document->SetURL(KURL("https://example.com/"));
document->UpdateSecurityOrigin(SecurityOrigin::Create(document->Url()));
messaging_proxy_ =
- new ThreadedWorkletMessagingProxyForTest(&page_->GetDocument());
+ MakeGarbageCollected<ThreadedWorkletMessagingProxyForTest>(
+ &page_->GetDocument());
ThreadedWorkletThreadForTest::EnsureSharedBackingThread();
}
diff --git a/chromium/third_party/blink/renderer/core/workers/worker.idl b/chromium/third_party/blink/renderer/core/workers/worker.idl
index 463f2518a88..3830550e27b 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker.idl
+++ b/chromium/third_party/blink/renderer/core/workers/worker.idl
@@ -31,14 +31,14 @@
ActiveScriptWrappable,
Constructor(DOMString scriptURL, optional WorkerOptions options),
ConstructorCallWith=ExecutionContext,
- Exposed(Window StableBlinkFeatures,DedicatedWorker NestedWorkers),
+ Exposed=(Window,DedicatedWorker),
RaisesException=Constructor,
ImplementedAs=DedicatedWorker
] interface Worker : EventTarget {
void terminate();
- [CallWith=ScriptState, RaisesException] void postMessage(any message, optional sequence<object> transfer=[]);
- [RuntimeEnabled=PostMessageOptions, CallWith=ScriptState, RaisesException] void postMessage(any message, PostMessageOptions options);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, sequence<object> transfer);
+ [CallWith=ScriptState, RaisesException] void postMessage(any message, optional PostMessageOptions options);
attribute EventHandler onmessage;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h b/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h
index 386e133fa34..2b954efeded 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_animation_frame_provider.h
@@ -32,10 +32,14 @@ class CORE_EXPORT WorkerAnimationFrameProvider
static WorkerAnimationFrameProvider* Create(
ExecutionContext* context,
const BeginFrameProviderParams& begin_frame_provider_params) {
- return new WorkerAnimationFrameProvider(context,
- begin_frame_provider_params);
+ return MakeGarbageCollected<WorkerAnimationFrameProvider>(
+ context, begin_frame_provider_params);
}
+ WorkerAnimationFrameProvider(
+ ExecutionContext* context,
+ const BeginFrameProviderParams& begin_frame_provider_params);
+
int RegisterCallback(FrameRequestCallbackCollection::FrameCallback* callback);
void CancelCallback(int id);
@@ -50,11 +54,6 @@ class CORE_EXPORT WorkerAnimationFrameProvider
static const int kInvalidCallbackId = -1;
- protected:
- WorkerAnimationFrameProvider(
- ExecutionContext* context,
- const BeginFrameProviderParams& begin_frame_provider_params);
-
private:
const std::unique_ptr<BeginFrameProvider> begin_frame_provider_;
DISALLOW_COPY_AND_ASSIGN(WorkerAnimationFrameProvider);
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc
index 4bc3d11ba02..c0cec745454 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.cc
@@ -33,7 +33,6 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/html/parser/text_resource_decoder.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
-#include "third_party/blink/renderer/core/loader/allowed_by_nosniff.h"
#include "third_party/blink/renderer/core/loader/resource/script_resource.h"
#include "third_party/blink/renderer/core/origin_trials/origin_trial_context.h"
#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
@@ -43,21 +42,14 @@
#include "third_party/blink/renderer/platform/network/content_security_policy_response_headers.h"
#include "third_party/blink/renderer/platform/network/http_names.h"
#include "third_party/blink/renderer/platform/network/network_utils.h"
+#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
namespace blink {
WorkerClassicScriptLoader::WorkerClassicScriptLoader()
- : response_address_space_(mojom::IPAddressSpace::kPublic) {}
-
-WorkerClassicScriptLoader::~WorkerClassicScriptLoader() {
- // If |threadable_loader_| is still working, we have to cancel it here.
- // Otherwise DidFail() of the deleted |this| will be called from
- // ThreadableLoader::NotifyFinished() when the frame will be
- // destroyed.
- if (need_to_cancel_)
- Cancel();
-}
+ : response_address_space_(mojom::IPAddressSpace::kPublic),
+ mime_type_check_mode_(AllowedByNosniff::MimeTypeCheck::kStrict) {}
void WorkerClassicScriptLoader::LoadSynchronously(
ExecutionContext& execution_context,
@@ -67,8 +59,12 @@ void WorkerClassicScriptLoader::LoadSynchronously(
url_ = url;
execution_context_ = &execution_context;
+ // Impose strict MIME-type checks on importScripts(). See
+ // https://crbug.com/794548.
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kStrict;
+
ResourceRequest request(url);
- request.SetHTTPMethod(HTTPNames::GET);
+ request.SetHTTPMethod(http_names::kGET);
request.SetExternalRequestStateFromRequestorAddressSpace(
creation_address_space);
request.SetRequestContext(request_context);
@@ -80,7 +76,7 @@ void WorkerClassicScriptLoader::LoadSynchronously(
ParserDisposition::kNotParserInserted;
resource_loader_options.synchronous_policy = kRequestSynchronously;
- threadable_loader_ = new ThreadableLoader(
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
execution_context, this, resource_loader_options);
threadable_loader_->Start(request);
}
@@ -92,6 +88,7 @@ void WorkerClassicScriptLoader::LoadTopLevelScriptAsynchronously(
network::mojom::FetchRequestMode fetch_request_mode,
network::mojom::FetchCredentialsMode fetch_credentials_mode,
mojom::IPAddressSpace creation_address_space,
+ bool is_nested_worker,
base::OnceClosure response_callback,
base::OnceClosure finished_callback) {
DCHECK(response_callback || finished_callback);
@@ -101,24 +98,41 @@ void WorkerClassicScriptLoader::LoadTopLevelScriptAsynchronously(
execution_context_ = &execution_context;
forbid_cross_origin_redirects_ = true;
+ if (execution_context.IsDocument()) {
+ // For worker creation on a document, don't impose strict MIME-type checks
+ // on the top-level worker script for backward compatibility. Note that
+ // there is a plan to deprecate legacy mime types for workers. See
+ // https://crbug.com/794548.
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kLax;
+ } else {
+ DCHECK(execution_context.IsWorkerGlobalScope());
+ if (is_nested_worker) {
+ // For nested workers, impose the strict MIME-type checks because the
+ // feature is new (enabled by default in M69) and there is no backward
+ // compatibility issue.
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kStrict;
+ } else {
+ // For worker creation on a document with off-the-main-thread top-level
+ // worker classic script loading, don't impose strict MIME-type checks for
+ // backward compatibility.
+ // TODO(nhiroki): Always impose strict MIME-type checks on all web
+ // workers (https://crbug.com/794548).
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+ mime_type_check_mode_ = AllowedByNosniff::MimeTypeCheck::kLax;
+ }
+ }
+
ResourceRequest request(url);
- request.SetHTTPMethod(HTTPNames::GET);
+ request.SetHTTPMethod(http_names::kGET);
request.SetExternalRequestStateFromRequestorAddressSpace(
creation_address_space);
request.SetRequestContext(request_context);
request.SetFetchRequestMode(fetch_request_mode);
request.SetFetchCredentialsMode(fetch_credentials_mode);
- ResourceLoaderOptions resource_loader_options;
-
- // During create, callbacks may happen which could remove the last reference
- // to this object, while some of the callchain assumes that the client and
- // loader wouldn't be deleted within callbacks.
- // (E.g. see crbug.com/524694 for why we can't easily remove this protect)
- scoped_refptr<WorkerClassicScriptLoader> protect(this);
need_to_cancel_ = true;
- threadable_loader_ = new ThreadableLoader(
- execution_context, this, resource_loader_options);
+ threadable_loader_ = MakeGarbageCollected<ThreadableLoader>(
+ execution_context, this, ResourceLoaderOptions());
threadable_loader_->Start(request);
if (failed_)
NotifyFinished();
@@ -138,7 +152,8 @@ void WorkerClassicScriptLoader::DidReceiveResponse(
NotifyError();
return;
}
- if (!AllowedByNosniff::MimeTypeAsScript(execution_context_, response)) {
+ if (!AllowedByNosniff::MimeTypeAsScript(execution_context_, response,
+ mime_type_check_mode_)) {
NotifyError();
return;
}
@@ -165,12 +180,12 @@ void WorkerClassicScriptLoader::DidReceiveResponse(
response_encoding_ = response.TextEncodingName();
app_cache_id_ = response.AppCacheID();
- referrer_policy_ = response.HttpHeaderField(HTTPNames::Referrer_Policy);
+ referrer_policy_ = response.HttpHeaderField(http_names::kReferrerPolicy);
ProcessContentSecurityPolicy(response);
origin_trial_tokens_ = OriginTrialContext::ParseHeaderValue(
- response.HttpHeaderField(HTTPNames::Origin_Trial));
+ response.HttpHeaderField(http_names::kOriginTrial));
- if (NetworkUtils::IsReservedIPAddress(response.RemoteIPAddress())) {
+ if (network_utils::IsReservedIPAddress(response.RemoteIPAddress())) {
response_address_space_ =
SecurityOrigin::Create(response_url_)->IsLocalhost()
? mojom::IPAddressSpace::kLocal
@@ -224,7 +239,16 @@ void WorkerClassicScriptLoader::DidFailRedirectCheck() {
NotifyError();
}
+void WorkerClassicScriptLoader::Trace(Visitor* visitor) {
+ visitor->Trace(threadable_loader_);
+ visitor->Trace(content_security_policy_);
+ visitor->Trace(execution_context_);
+ ThreadableLoaderClient::Trace(visitor);
+}
+
void WorkerClassicScriptLoader::Cancel() {
+ if (!need_to_cancel_)
+ return;
need_to_cancel_ = false;
if (threadable_loader_)
threadable_loader_->Cancel();
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h
index b561a9633c6..55810312926 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_classic_script_loader.h
@@ -35,6 +35,7 @@
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
+#include "third_party/blink/renderer/core/loader/allowed_by_nosniff.h"
#include "third_party/blink/renderer/core/loader/threadable_loader.h"
#include "third_party/blink/renderer/core/loader/threadable_loader_client.h"
#include "third_party/blink/renderer/platform/loader/fetch/resource_request.h"
@@ -52,14 +53,12 @@ class ExecutionContext;
class TextResourceDecoder;
class CORE_EXPORT WorkerClassicScriptLoader final
- : public RefCounted<WorkerClassicScriptLoader>,
+ : public GarbageCollectedFinalized<WorkerClassicScriptLoader>,
public ThreadableLoaderClient {
- USING_FAST_MALLOC(WorkerClassicScriptLoader);
+ USING_GARBAGE_COLLECTED_MIXIN(WorkerClassicScriptLoader);
public:
- static scoped_refptr<WorkerClassicScriptLoader> Create() {
- return base::AdoptRef(new WorkerClassicScriptLoader());
- }
+ WorkerClassicScriptLoader();
// For importScript().
void LoadSynchronously(ExecutionContext&,
@@ -75,6 +74,7 @@ class CORE_EXPORT WorkerClassicScriptLoader final
network::mojom::FetchRequestMode,
network::mojom::FetchCredentialsMode,
mojom::IPAddressSpace,
+ bool is_nested_worker,
base::OnceClosure response_callback,
base::OnceClosure finished_callback);
@@ -93,7 +93,6 @@ class CORE_EXPORT WorkerClassicScriptLoader final
std::unique_ptr<Vector<char>> ReleaseCachedMetadata() {
return std::move(cached_metadata_);
}
- const Vector<char>* CachedMetadata() const { return cached_metadata_.get(); }
ContentSecurityPolicy* GetContentSecurityPolicy() {
return content_security_policy_.Get();
@@ -119,12 +118,9 @@ class CORE_EXPORT WorkerClassicScriptLoader final
void DidFail(const ResourceError&) override;
void DidFailRedirectCheck() override;
- private:
- friend class WTF::RefCounted<WorkerClassicScriptLoader>;
-
- WorkerClassicScriptLoader();
- ~WorkerClassicScriptLoader() override;
+ void Trace(Visitor*) override;
+ private:
void NotifyError();
void NotifyFinished();
@@ -134,7 +130,7 @@ class CORE_EXPORT WorkerClassicScriptLoader final
base::OnceClosure response_callback_;
base::OnceClosure finished_callback_;
- Persistent<ThreadableLoader> threadable_loader_;
+ Member<ThreadableLoader> threadable_loader_;
String response_encoding_;
std::unique_ptr<TextResourceDecoder> decoder_;
StringBuilder source_text_;
@@ -151,11 +147,14 @@ class CORE_EXPORT WorkerClassicScriptLoader final
unsigned long identifier_ = 0;
long long app_cache_id_ = 0;
std::unique_ptr<Vector<char>> cached_metadata_;
- Persistent<ContentSecurityPolicy> content_security_policy_;
- Persistent<ExecutionContext> execution_context_;
+ Member<ContentSecurityPolicy> content_security_policy_;
+ Member<ExecutionContext> execution_context_;
mojom::IPAddressSpace response_address_space_;
std::unique_ptr<Vector<String>> origin_trial_tokens_;
String referrer_policy_;
+
+ // TODO(nhiroki): Move this to FetchClientSettingsObject.
+ AllowedByNosniff::MimeTypeCheck mime_type_check_mode_;
};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_clients.h b/chromium/third_party/blink/renderer/core/workers/worker_clients.h
index 11f0154d23a..2f5ca1cb1be 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_clients.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_clients.h
@@ -47,14 +47,17 @@ class CORE_EXPORT WorkerClients final : public GarbageCollected<WorkerClients>,
USING_GARBAGE_COLLECTED_MIXIN(WorkerClients);
public:
- static WorkerClients* Create() { return new WorkerClients; }
+ static WorkerClients* Create() {
+ return MakeGarbageCollected<WorkerClients>();
+ }
+
+ WorkerClients() = default;
void Trace(blink::Visitor* visitor) override {
Supplementable<WorkerClients>::Trace(visitor);
}
private:
- WorkerClients() = default;
DISALLOW_COPY_AND_ASSIGN(WorkerClients);
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc
index 484c4f3ccdf..a255a36a4c8 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.cc
@@ -40,7 +40,7 @@ namespace blink {
WorkerContentSettingsClient* WorkerContentSettingsClient::Create(
std::unique_ptr<WebContentSettingsClient> client) {
- return new WorkerContentSettingsClient(std::move(client));
+ return MakeGarbageCollected<WorkerContentSettingsClient>(std::move(client));
}
WorkerContentSettingsClient::~WorkerContentSettingsClient() = default;
@@ -51,10 +51,10 @@ bool WorkerContentSettingsClient::RequestFileSystemAccessSync() {
return client_->RequestFileSystemAccessSync();
}
-bool WorkerContentSettingsClient::AllowIndexedDB(const WebString& name) {
+bool WorkerContentSettingsClient::AllowIndexedDB() {
if (!client_)
return true;
- return client_->AllowIndexedDB(name, WebSecurityOrigin());
+ return client_->AllowIndexedDB(WebSecurityOrigin());
}
bool WorkerContentSettingsClient::AllowScriptFromSource(
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h
index 4db0bf225e9..3a7f7f61abe 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_content_settings_client.h
@@ -42,7 +42,6 @@ namespace blink {
class ExecutionContext;
class KURL;
class SecurityOrigin;
-class WebString;
class CORE_EXPORT WorkerContentSettingsClient final
: public GarbageCollectedFinalized<WorkerContentSettingsClient>,
@@ -54,10 +53,13 @@ class CORE_EXPORT WorkerContentSettingsClient final
static WorkerContentSettingsClient* Create(
std::unique_ptr<WebContentSettingsClient>);
+
+ explicit WorkerContentSettingsClient(
+ std::unique_ptr<WebContentSettingsClient>);
virtual ~WorkerContentSettingsClient();
bool RequestFileSystemAccessSync();
- bool AllowIndexedDB(const WebString& name);
+ bool AllowIndexedDB();
bool AllowRunningInsecureContent(bool enabled_per_settings,
const SecurityOrigin*,
const KURL&);
@@ -74,9 +76,6 @@ class CORE_EXPORT WorkerContentSettingsClient final
}
private:
- explicit WorkerContentSettingsClient(
- std::unique_ptr<WebContentSettingsClient>);
-
std::unique_ptr<WebContentSettingsClient> client_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc
index 38df09470d3..78d29e65477 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.cc
@@ -69,6 +69,7 @@
#include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
+#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/assertions.h"
namespace blink {
@@ -145,7 +146,7 @@ void WorkerGlobalScope::importScripts(const Vector<String>& urls,
// Step 1: "If worker global scope's type is "module", throw a TypeError
// exception."
- if (script_type_ == ScriptType::kModule) {
+ if (script_type_ == mojom::ScriptType::kModule) {
exception_state.ThrowTypeError(
"Module scripts don't support importScripts().");
return;
@@ -200,10 +201,10 @@ void WorkerGlobalScope::importScripts(const Vector<String>& urls,
// importScripts always uses "no-cors", so simply checking the origin is
// enough.
// TODO(yhirano): Remove this ad-hoc logic and use the response type.
- const AccessControlStatus access_control_status =
+ const SanitizeScriptErrors sanitize_script_errors =
execution_context.GetSecurityOrigin()->CanReadContent(response_url)
- ? kSharableCrossOrigin
- : kOpaqueResource;
+ ? SanitizeScriptErrors::kDoNotSanitize
+ : SanitizeScriptErrors::kSanitize;
ErrorEvent* error_event = nullptr;
SingleCachedMetadataHandler* handler(
@@ -214,7 +215,7 @@ void WorkerGlobalScope::importScripts(const Vector<String>& urls,
ScriptController()->Evaluate(
ScriptSourceCode(source_code, ScriptSourceLocationType::kUnknown,
handler, response_url),
- access_control_status, &error_event, v8_cache_options_);
+ sanitize_script_errors, &error_event, v8_cache_options_);
if (error_event) {
ScriptController()->RethrowExceptionFromImportedScript(error_event,
exception_state);
@@ -252,8 +253,8 @@ WorkerGlobalScope::LoadScriptFromClassicScriptLoader(
String* out_source_code,
std::unique_ptr<Vector<char>>* out_cached_meta_data) {
ExecutionContext* execution_context = GetExecutionContext();
- scoped_refptr<WorkerClassicScriptLoader> classic_script_loader(
- WorkerClassicScriptLoader::Create());
+ WorkerClassicScriptLoader* classic_script_loader =
+ MakeGarbageCollected<WorkerClassicScriptLoader>();
classic_script_loader->LoadSynchronously(
*execution_context, script_url, mojom::RequestContextType::SCRIPT,
execution_context->GetSecurityContext().AddressSpace());
@@ -316,6 +317,16 @@ ExecutionContext* WorkerGlobalScope::GetExecutionContext() const {
void WorkerGlobalScope::TasksWereUnpaused() {
WorkerOrWorkletGlobalScope::TasksWereUnpaused();
+ // We cannot run the paused tasks right away, as there might be some other
+ // code that still needs to be run synchronously.
+ GetTaskRunner(TaskType::kInternalWorker)
+ ->PostTask(FROM_HERE, WTF::Bind(&WorkerGlobalScope::MaybeRunPausedTasks,
+ WrapWeakPersistent(this)));
+}
+
+void WorkerGlobalScope::MaybeRunPausedTasks() {
+ if (IsContextPaused())
+ return;
Vector<base::OnceClosure> calls;
paused_calls_.swap(calls);
for (auto& call : calls)
@@ -324,26 +335,116 @@ void WorkerGlobalScope::TasksWereUnpaused() {
void WorkerGlobalScope::EvaluateClassicScriptPausable(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id) {
if (IsContextPaused()) {
- AddPausedCall(WTF::Bind(
- &WorkerGlobalScope::EvaluateClassicScriptPausable,
- WrapWeakPersistent(this), script_url, access_control_status,
- source_code, WTF::Passed(std::move(cached_meta_data)), stack_id));
+ AddPausedCall(WTF::Bind(&WorkerGlobalScope::EvaluateClassicScriptPausable,
+ WrapWeakPersistent(this), script_url, source_code,
+ WTF::Passed(std::move(cached_meta_data)),
+ stack_id));
return;
}
ThreadDebugger* debugger = ThreadDebugger::From(GetThread()->GetIsolate());
if (debugger)
debugger->ExternalAsyncTaskStarted(stack_id);
- EvaluateClassicScript(script_url, access_control_status, source_code,
- std::move(cached_meta_data));
+ EvaluateClassicScript(script_url, source_code, std::move(cached_meta_data));
if (debugger)
debugger->ExternalAsyncTaskFinished(stack_id);
}
+// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
+void WorkerGlobalScope::ImportClassicScriptPausable(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+ if (IsContextPaused()) {
+ AddPausedCall(WTF::Bind(&WorkerGlobalScope::ImportClassicScriptPausable,
+ WrapWeakPersistent(this), script_url,
+ WrapPersistent(outside_settings_object), stack_id));
+ return;
+ }
+
+ // Step 12. "Fetch a classic worker script given url, outside settings,
+ // destination, and inside settings."
+ // TODO(nhiroki): Load a main script using |outside_settings_object|.
+ // (https://crbug.com/835717, https://crbug.com/880027)
+
+ // Step 12.1. "Set request's reserved client to inside settings."
+ // The browesr process takes care of this.
+
+ // Step 12.2. "Fetch request, and asynchronously wait to run the remaining
+ // steps as part of fetch's process response for the response response."
+ ExecutionContext* execution_context = GetExecutionContext();
+ WorkerClassicScriptLoader* classic_script_loader =
+ MakeGarbageCollected<WorkerClassicScriptLoader>();
+ classic_script_loader->LoadTopLevelScriptAsynchronously(
+ *execution_context, script_url, mojom::RequestContextType::WORKER,
+ network::mojom::FetchRequestMode::kSameOrigin,
+ network::mojom::FetchCredentialsMode::kSameOrigin,
+ GetSecurityContext().AddressSpace(), IsNestedWorker(),
+ WTF::Bind(&WorkerGlobalScope::DidReceiveResponseForClassicScript,
+ WrapWeakPersistent(this),
+ WrapPersistent(classic_script_loader)),
+ WTF::Bind(&WorkerGlobalScope::DidImportClassicScript,
+ WrapWeakPersistent(this), WrapPersistent(classic_script_loader),
+ stack_id));
+}
+
+void WorkerGlobalScope::DidReceiveResponseForClassicScript(
+ WorkerClassicScriptLoader* classic_script_loader) {
+ DCHECK(IsContextThread());
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+ probe::didReceiveScriptResponse(this, classic_script_loader->Identifier());
+}
+
+// https://html.spec.whatwg.org/multipage/workers.html#worker-processing-model
+void WorkerGlobalScope::DidImportClassicScript(
+ WorkerClassicScriptLoader* classic_script_loader,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ DCHECK(IsContextThread());
+ DCHECK(RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled());
+
+ // Step 12. "If the algorithm asynchronously completes with null, then:"
+ if (classic_script_loader->Failed()) {
+ // Step 12.1. "Queue a task to fire an event named error at worker."
+ // Step 12.2. "Run the environment discarding steps for inside settings."
+ // Step 12.3. "Return."
+ ExceptionThrown(ErrorEvent::Create(
+ "Failed to load a worker script: " + url_.GetString(),
+ SourceLocation::Capture(), nullptr /* world */));
+ return;
+ }
+
+ // Step 12.3. "Set worker global scope's url to response's url."
+ // Step 12.4. "Set worker global scope's HTTPS state to response's HTTPS
+ // state."
+ // These are done in the constructor of WorkerGlobalScope.
+
+ // Step 12.5. "Set worker global scope's referrer policy to the result of
+ // parsing the `Referrer-Policy` header of response."
+ network::mojom::ReferrerPolicy referrer_policy =
+ network::mojom::ReferrerPolicy::kDefault;
+ if (!classic_script_loader->GetReferrerPolicy().IsNull()) {
+ SecurityPolicy::ReferrerPolicyFromHeaderValue(
+ classic_script_loader->GetReferrerPolicy(),
+ kDoNotSupportReferrerPolicyLegacyKeywords, &referrer_policy);
+ SetReferrerPolicy(referrer_policy);
+ }
+
+ // Step 13.6. "Execute the Initialize a global object's CSP list algorithm
+ // on worker global scope and response. [CSP]"
+ // This is done in the constructor of WorkerGlobalScope.
+
+ // Step 13.7. "Asynchronously complete the perform the fetch steps with
+ // response."
+
+ EvaluateClassicScriptPausable(
+ classic_script_loader->ResponseURL(), classic_script_loader->SourceText(),
+ classic_script_loader->ReleaseCachedMetadata(), stack_id);
+}
+
void WorkerGlobalScope::ImportModuleScriptPausable(
const KURL& module_url_record,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -372,9 +473,9 @@ void WorkerGlobalScope::ReceiveMessagePausable(
debugger->ExternalAsyncTaskStarted(message.sender_stack_trace_id);
UserActivation* user_activation = nullptr;
if (message.user_activation) {
- user_activation =
- new UserActivation(message.user_activation->has_been_active,
- message.user_activation->was_active);
+ user_activation = MakeGarbageCollected<UserActivation>(
+ message.user_activation->has_been_active,
+ message.user_activation->was_active);
}
DispatchEvent(*MessageEvent::Create(ports, std::move(message.message),
user_activation));
@@ -384,7 +485,6 @@ void WorkerGlobalScope::ReceiveMessagePausable(
void WorkerGlobalScope::EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data) {
DCHECK(IsContextThread());
@@ -395,10 +495,12 @@ void WorkerGlobalScope::EvaluateClassicScript(
ReportingProxy().WillEvaluateClassicScript(
source_code.length(),
cached_meta_data.get() ? cached_meta_data->size() : 0);
+ // Cross-origin workers are disallowed, so use
+ // SanitizeScriptErrors::kDoNotSanitize.
bool success = ScriptController()->Evaluate(
- ScriptSourceCode(source_code, ScriptSourceLocationType::kUnknown, handler,
- script_url),
- access_control_status, nullptr /* error_event */, v8_cache_options_);
+ ScriptSourceCode(source_code, handler, script_url),
+ SanitizeScriptErrors::kDoNotSanitize, nullptr /* error_event */,
+ v8_cache_options_);
ReportingProxy().DidEvaluateClassicScript(success);
}
@@ -410,9 +512,11 @@ WorkerGlobalScope::WorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params,
WorkerThread* thread,
base::TimeTicks time_origin)
- : WorkerOrWorkletGlobalScope(thread->GetIsolate(),
- creation_params->worker_clients,
- thread->GetWorkerReportingProxy()),
+ : WorkerOrWorkletGlobalScope(
+ thread->GetIsolate(),
+ creation_params->worker_clients,
+ std::move(creation_params->web_worker_fetch_context),
+ thread->GetWorkerReportingProxy()),
url_(creation_params->script_url),
script_type_(creation_params->script_type),
user_agent_(creation_params->user_agent),
@@ -448,9 +552,10 @@ WorkerGlobalScope::WorkerGlobalScope(
BindContentSecurityPolicyToExecutionContext();
SetWorkerSettings(std::move(creation_params->worker_settings));
- // For module scripts, referrer policy will be set after the top-level module
+ // Set the referrer policy here for workers whose script is fetched on the
+ // main thread. For off-the-main-thread fetches, it is instead set after the
// script is fetched.
- if (creation_params->script_type == ScriptType::kClassic)
+ if (IsScriptFetchedOnMainThread())
SetReferrerPolicy(creation_params->referrer_policy);
SetAddressSpace(creation_params->address_space);
@@ -530,6 +635,20 @@ void WorkerGlobalScope::SetWorkerSettings(
worker_settings_->GetGenericFontFamilySettings());
}
+bool WorkerGlobalScope::IsScriptFetchedOnMainThread() {
+ if (script_type_ == mojom::ScriptType::kModule)
+ return false;
+ // It's now supported only for dedicated workers to load top-level classic
+ // worker script off the main thread.
+ // TODO(nhiroki): Support loading top-level classic worker script off the main
+ // thread for shared workers and service workers.
+ if (IsDedicatedWorkerGlobalScope() &&
+ RuntimeEnabledFeatures::OffMainThreadWorkerScriptFetchEnabled()) {
+ return false;
+ }
+ return true;
+}
+
void WorkerGlobalScope::Trace(blink::Visitor* visitor) {
visitor->Trace(location_);
visitor->Trace(navigator_);
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h
index 18c26947b21..8b45870c385 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.h
@@ -31,6 +31,7 @@
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "services/service_manager/public/cpp/interface_provider.h"
#include "services/service_manager/public/mojom/interface_provider.mojom-blink.h"
+#include "third_party/blink/public/mojom/script/script_type.mojom-blink.h"
#include "third_party/blink/renderer/bindings/core/v8/active_script_wrappable.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/core_export.h"
@@ -38,7 +39,6 @@
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/dom_timer_coordinator.h"
-#include "third_party/blink/renderer/core/frame/dom_window_base64.h"
#include "third_party/blink/renderer/core/messaging/blink_transferable_message.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/workers/worker_animation_frame_provider.h"
@@ -46,6 +46,7 @@
#include "third_party/blink/renderer/core/workers/worker_settings.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/loader/fetch/cached_metadata_handler.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace service_manager {
class InterfaceProvider;
@@ -59,6 +60,7 @@ class FetchClientSettingsObjectSnapshot;
class FontFaceSet;
class OffscreenFontSelector;
class V8VoidFunction;
+class WorkerClassicScriptLoader;
class WorkerLocation;
class WorkerNavigator;
class WorkerThread;
@@ -67,8 +69,7 @@ struct GlobalScopeCreationParams;
class CORE_EXPORT WorkerGlobalScope
: public WorkerOrWorkletGlobalScope,
public ActiveScriptWrappable<WorkerGlobalScope>,
- public Supplementable<WorkerGlobalScope>,
- public DOMWindowBase64 {
+ public Supplementable<WorkerGlobalScope> {
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(WorkerGlobalScope);
@@ -100,9 +101,9 @@ class CORE_EXPORT WorkerGlobalScope
String origin() const;
- DEFINE_ATTRIBUTE_EVENT_LISTENER(error);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(rejectionhandled);
- DEFINE_ATTRIBUTE_EVENT_LISTENER(unhandledrejection);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(error, kError);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(rejectionhandled, kRejectionhandled);
+ DEFINE_ATTRIBUTE_EVENT_LISTENER(unhandledrejection, kUnhandledrejection);
// WorkerUtils
virtual void importScripts(const Vector<String>& urls, ExceptionState&);
@@ -140,10 +141,13 @@ class CORE_EXPORT WorkerGlobalScope
// so that WorkerGlobalScope can be paused.
void EvaluateClassicScriptPausable(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id);
+ void ImportClassicScriptPausable(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id);
void ImportModuleScriptPausable(
const KURL& module_url_record,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -169,6 +173,9 @@ class CORE_EXPORT WorkerGlobalScope
return animation_frame_provider_;
}
+ // Returns true when this is a nested worker.
+ virtual bool IsNestedWorker() const { return false; }
+
protected:
WorkerGlobalScope(std::unique_ptr<GlobalScopeCreationParams>,
WorkerThread*,
@@ -183,7 +190,6 @@ class CORE_EXPORT WorkerGlobalScope
// Evaluates the given top-level classic script.
virtual void EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data);
@@ -195,11 +201,22 @@ class CORE_EXPORT WorkerGlobalScope
void AddPausedCall(base::OnceClosure closure);
- ScriptType GetScriptType() const { return script_type_; }
+ void MaybeRunPausedTasks();
+
+ mojom::ScriptType GetScriptType() const { return script_type_; }
private:
void SetWorkerSettings(std::unique_ptr<WorkerSettings>);
+ // Returns true if this worker script is supposed to be fetched on the main
+ // thread and passed to the worker thread.
+ bool IsScriptFetchedOnMainThread();
+
+ void DidReceiveResponseForClassicScript(
+ WorkerClassicScriptLoader* classic_script_loader);
+ void DidImportClassicScript(WorkerClassicScriptLoader* classic_script_loader,
+ const v8_inspector::V8StackTraceId& stack_id);
+
// |kNotHandled| is used when the script was not in
// InstalledScriptsManager, which means it was not an installed script.
enum class LoadResult { kSuccess, kFailed, kNotHandled };
@@ -232,7 +249,7 @@ class CORE_EXPORT WorkerGlobalScope
void TasksWereUnpaused() override;
const KURL url_;
- const ScriptType script_type_;
+ const mojom::ScriptType script_type_;
const String user_agent_;
const base::UnguessableToken parent_devtools_token_;
const V8CacheOptions v8_cache_options_;
@@ -264,11 +281,12 @@ class CORE_EXPORT WorkerGlobalScope
Vector<base::OnceClosure> paused_calls_;
};
-DEFINE_TYPE_CASTS(WorkerGlobalScope,
- ExecutionContext,
- context,
- context->IsWorkerGlobalScope(),
- context.IsWorkerGlobalScope());
+template <>
+struct DowncastTraits<WorkerGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsWorkerGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl
index 8ff553b78ca..5926174c80e 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl
+++ b/chromium/third_party/blink/renderer/core/workers/worker_global_scope.idl
@@ -79,7 +79,6 @@
[RuntimeEnabled=OffscreenCanvasText] readonly attribute FontFaceSet fonts;
};
-WorkerGlobalScope implements WindowBase64;
-WorkerGlobalScope implements WindowTimers;
+WorkerGlobalScope implements WindowOrWorkerGlobalScope;
// TODO(fserb): this needs to be enabled once we get out of RuntimeEnabled.
//WorkerGlobalScope implements FontFaceSource;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc b/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc
deleted file mode 100644
index c06bfa4aa24..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.cc
+++ /dev/null
@@ -1,164 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
-
-#include "base/location.h"
-#include "third_party/blink/renderer/core/frame/frame_console.h"
-#include "third_party/blink/renderer/core/inspector/identifiers_factory.h"
-#include "third_party/blink/renderer/core/inspector/inspector_trace_events.h"
-#include "third_party/blink/renderer/core/inspector/inspector_worker_agent.h"
-#include "third_party/blink/renderer/core/inspector/worker_inspector_controller.h"
-#include "third_party/blink/renderer/core/probe/core_probes.h"
-#include "third_party/blink/renderer/core/workers/execution_context_worker_registry.h"
-#include "third_party/blink/renderer/core/workers/worker_global_scope.h"
-#include "third_party/blink/renderer/core/workers/worker_thread.h"
-#include "third_party/blink/renderer/platform/cross_thread_functional.h"
-#include "third_party/blink/renderer/platform/instrumentation/tracing/trace_event.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
-#include "third_party/blink/renderer/platform/weborigin/kurl.h"
-
-namespace blink {
-
-WorkerInspectorProxy::WorkerInspectorProxy()
- : worker_thread_(nullptr), execution_context_(nullptr) {}
-
-WorkerInspectorProxy* WorkerInspectorProxy::Create() {
- return new WorkerInspectorProxy();
-}
-
-WorkerInspectorProxy::~WorkerInspectorProxy() = default;
-
-const String& WorkerInspectorProxy::InspectorId() {
- if (inspector_id_.IsEmpty() && worker_thread_) {
- inspector_id_ = IdentifiersFactory::IdFromToken(
- worker_thread_->GetDevToolsWorkerToken());
- }
- return inspector_id_;
-}
-
-WorkerInspectorProxy::PauseOnWorkerStart
-WorkerInspectorProxy::ShouldPauseOnWorkerStart(
- ExecutionContext* execution_context) {
- bool result = false;
- probe::shouldWaitForDebuggerOnWorkerStart(execution_context, &result);
- return result ? PauseOnWorkerStart::kPause : PauseOnWorkerStart::kDontPause;
-}
-
-void WorkerInspectorProxy::WorkerThreadCreated(
- ExecutionContext* execution_context,
- WorkerThread* worker_thread,
- const KURL& url) {
- worker_thread_ = worker_thread;
- execution_context_ = execution_context;
- url_ = url.GetString();
- DCHECK(execution_context_);
- ExecutionContextWorkerRegistry::From(*execution_context_)
- ->AddWorkerInspectorProxy(this);
- // We expect everyone starting worker thread to synchronously ask for
- // ShouldPauseOnWorkerStart() right before.
- bool waiting_for_debugger = false;
- probe::shouldWaitForDebuggerOnWorkerStart(execution_context_,
- &waiting_for_debugger);
- probe::didStartWorker(execution_context_, this, waiting_for_debugger);
-}
-
-void WorkerInspectorProxy::WorkerThreadTerminated() {
- if (worker_thread_) {
- ExecutionContextWorkerRegistry::From(*execution_context_)
- ->RemoveWorkerInspectorProxy(this);
- probe::workerTerminated(execution_context_, this);
- }
-
- worker_thread_ = nullptr;
- page_inspectors_.clear();
- execution_context_ = nullptr;
-}
-
-void WorkerInspectorProxy::DispatchMessageFromWorker(int session_id,
- const String& message) {
- auto it = page_inspectors_.find(session_id);
- if (it != page_inspectors_.end())
- it->value->DispatchMessageFromWorker(this, session_id, message);
-}
-
-static void ConnectToWorkerGlobalScopeInspectorTask(WorkerThread* worker_thread,
- int session_id) {
- if (WorkerInspectorController* inspector =
- worker_thread->GetWorkerInspectorController()) {
- inspector->ConnectFrontend(session_id);
- }
-}
-
-void WorkerInspectorProxy::ConnectToInspector(
- int session_id,
- WorkerInspectorProxy::PageInspector* page_inspector) {
- if (!worker_thread_)
- return;
- DCHECK(page_inspectors_.find(session_id) == page_inspectors_.end());
- page_inspectors_.insert(session_id, page_inspector);
- PostCrossThreadTask(
- *worker_thread_->GetTaskRunner(TaskType::kInternalInspector), FROM_HERE,
- CrossThreadBind(ConnectToWorkerGlobalScopeInspectorTask,
- CrossThreadUnretained(worker_thread_), session_id));
-}
-
-static void DisconnectFromWorkerGlobalScopeInspectorTask(
- WorkerThread* worker_thread,
- int session_id) {
- if (WorkerInspectorController* inspector =
- worker_thread->GetWorkerInspectorController()) {
- inspector->DisconnectFrontend(session_id);
- }
-}
-
-void WorkerInspectorProxy::DisconnectFromInspector(
- int session_id,
- WorkerInspectorProxy::PageInspector* page_inspector) {
- DCHECK(page_inspectors_.at(session_id) == page_inspector);
- page_inspectors_.erase(session_id);
- if (worker_thread_) {
- PostCrossThreadTask(
- *worker_thread_->GetTaskRunner(TaskType::kInternalInspector), FROM_HERE,
- CrossThreadBind(DisconnectFromWorkerGlobalScopeInspectorTask,
- CrossThreadUnretained(worker_thread_), session_id));
- }
-}
-
-static void DispatchOnInspectorBackendTask(int session_id,
- const String& message,
- WorkerThread* worker_thread) {
- if (WorkerInspectorController* inspector =
- worker_thread->GetWorkerInspectorController()) {
- inspector->DispatchMessageFromFrontend(session_id, message);
- }
-}
-
-void WorkerInspectorProxy::SendMessageToInspector(int session_id,
- const String& message) {
- if (!worker_thread_)
- return;
-
- String method;
- protocol::UberDispatcher dispatcher(nullptr);
- dispatcher.parseCommand(protocol::StringUtil::parseJSON(message).get(),
- nullptr, &method);
-
- if (InspectorSession::ShouldInterruptForMethod(method)) {
- worker_thread_->GetInspectorTaskRunner()->AppendTask(
- CrossThreadBind(DispatchOnInspectorBackendTask, session_id, message,
- CrossThreadUnretained(worker_thread_)));
- } else {
- PostCrossThreadTask(
- *worker_thread_->GetTaskRunner(TaskType::kInternalInspector), FROM_HERE,
- CrossThreadBind(DispatchOnInspectorBackendTask, session_id, message,
- CrossThreadUnretained(worker_thread_)));
- }
-}
-
-void WorkerInspectorProxy::Trace(blink::Visitor* visitor) {
- visitor->Trace(execution_context_);
-}
-
-} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h b/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h
deleted file mode 100644
index c7e8848307e..00000000000
--- a/chromium/third_party/blink/renderer/core/workers/worker_inspector_proxy.h
+++ /dev/null
@@ -1,72 +0,0 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_INSPECTOR_PROXY_H_
-#define THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_INSPECTOR_PROXY_H_
-
-#include "base/macros.h"
-#include "third_party/blink/renderer/core/core_export.h"
-#include "third_party/blink/renderer/core/inspector/console_message.h"
-#include "third_party/blink/renderer/core/inspector/thread_debugger.h"
-#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/wtf/forward.h"
-#include "third_party/blink/renderer/platform/wtf/hash_map.h"
-
-namespace blink {
-
-class ExecutionContext;
-class KURL;
-class WorkerThread;
-
-// A proxy for talking to the worker inspector on the worker thread.
-// All of these methods should be called on the main thread.
-class CORE_EXPORT WorkerInspectorProxy final
- : public GarbageCollectedFinalized<WorkerInspectorProxy> {
- public:
- enum class PauseOnWorkerStart { kPause, kDontPause };
-
- static WorkerInspectorProxy* Create();
-
- ~WorkerInspectorProxy();
- void Trace(blink::Visitor*);
-
- class CORE_EXPORT PageInspector {
- public:
- virtual ~PageInspector() = default;
- virtual void DispatchMessageFromWorker(WorkerInspectorProxy*,
- int session_id,
- const String& message) = 0;
- };
-
- // Returns whether WorkerThread should pause to run debugger tasks on its
- // startup.
- PauseOnWorkerStart ShouldPauseOnWorkerStart(ExecutionContext*);
-
- void WorkerThreadCreated(ExecutionContext*, WorkerThread*, const KURL&);
- void WorkerThreadTerminated();
- void DispatchMessageFromWorker(int session_id, const String&);
-
- void ConnectToInspector(int session_id,
- PageInspector*);
- void DisconnectFromInspector(int session_id, PageInspector*);
- void SendMessageToInspector(int session_id, const String& message);
-
- const String& Url() { return url_; }
- ExecutionContext* GetExecutionContext() { return execution_context_; }
- const String& InspectorId();
- WorkerThread* GetWorkerThread() { return worker_thread_; }
-
- private:
- WorkerInspectorProxy();
-
- WorkerThread* worker_thread_;
- Member<ExecutionContext> execution_context_;
- HashMap<int, PageInspector*> page_inspectors_;
- String url_;
- String inspector_id_;
-};
-
-} // namespace blink
-
-#endif // THIRD_PARTY_BLINK_RENDERER_CORE_WORKERS_WORKER_INSPECTOR_PROXY_H_
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_location.h b/chromium/third_party/blink/renderer/core/workers/worker_location.h
index 942fe74a499..d6918b61fb1 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_location.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_location.h
@@ -40,9 +40,11 @@ class WorkerLocation final : public ScriptWrappable,
public:
static WorkerLocation* Create(const KURL& url) {
- return new WorkerLocation(url);
+ return MakeGarbageCollected<WorkerLocation>(url);
}
+ explicit WorkerLocation(const KURL& url) : url_(url) {}
+
KURL Url() const override { return url_; }
String Input() const override {
NOTREACHED();
@@ -50,8 +52,6 @@ class WorkerLocation final : public ScriptWrappable,
}
private:
- explicit WorkerLocation(const KURL& url) : url_(url) {}
-
KURL url_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_location.idl b/chromium/third_party/blink/renderer/core/workers/worker_location.idl
index e271597c274..ffdf2ecdf30 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_location.idl
+++ b/chromium/third_party/blink/renderer/core/workers/worker_location.idl
@@ -31,6 +31,14 @@
[
Exposed=Worker
] interface WorkerLocation {
+ stringifier readonly attribute USVString href;
+ readonly attribute USVString origin;
+ readonly attribute USVString protocol;
+ readonly attribute USVString host;
+ readonly attribute USVString hostname;
+ readonly attribute USVString port;
+ readonly attribute USVString pathname;
+ readonly attribute USVString search;
+ readonly attribute USVString hash;
};
-WorkerLocation implements URLUtilsReadOnly;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc b/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc
index 1a6a79224a6..c68d2f9e8a7 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_module_tree_client.cc
@@ -24,7 +24,7 @@ void WorkerModuleTreeClient::NotifyModuleTreeLoadFinished(
auto* execution_context =
ExecutionContext::From(modulator_->GetScriptState());
blink::WorkerReportingProxy& worker_reporting_proxy =
- ToWorkerGlobalScope(execution_context)->ReportingProxy();
+ To<WorkerGlobalScope>(execution_context)->ReportingProxy();
if (!module_script) {
// Step 12: "If the algorithm asynchronously completes with null, queue
@@ -41,6 +41,9 @@ void WorkerModuleTreeClient::NotifyModuleTreeLoadFinished(
// asynchronous completion, with script being the asynchronous completion
// value."
worker_reporting_proxy.WillEvaluateModuleScript();
+ // This |error| is always null because the second argument is |kReport|.
+ // TODO(nhiroki): Catch an error when an evaluation error happens.
+ // (https://crbug.com/680046)
ScriptValue error = modulator_->ExecuteModule(
module_script, Modulator::CaptureEvalErrorFlag::kReport);
worker_reporting_proxy.DidEvaluateModuleScript(error.IsEmpty());
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_navigator.h b/chromium/third_party/blink/renderer/core/workers/worker_navigator.h
index 203f006ce40..376f5995f97 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_navigator.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_navigator.h
@@ -50,8 +50,10 @@ class CORE_EXPORT WorkerNavigator final
public:
static WorkerNavigator* Create(const String& user_agent) {
- return new WorkerNavigator(user_agent);
+ return MakeGarbageCollected<WorkerNavigator>(user_agent);
}
+
+ explicit WorkerNavigator(const String&);
~WorkerNavigator() override;
String userAgent() const override;
@@ -59,8 +61,6 @@ class CORE_EXPORT WorkerNavigator final
void Trace(blink::Visitor*) override;
private:
- explicit WorkerNavigator(const String&);
-
String user_agent_;
};
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc
index 5a0ccabbfa2..4189e13ae0a 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.cc
@@ -5,13 +5,16 @@
#include "third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h"
#include "third_party/blink/public/platform/task_type.h"
+#include "third_party/blink/public/platform/web_worker_fetch_context.h"
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/dom/events/event_queue.h"
#include "third_party/blink/renderer/core/frame/deprecation.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
#include "third_party/blink/renderer/core/loader/modulescript/module_script_fetch_request.h"
+#include "third_party/blink/renderer/core/loader/subresource_filter.h"
#include "third_party/blink/renderer/core/loader/worker_fetch_context.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
+#include "third_party/blink/renderer/core/script/fetch_client_settings_object_impl.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
@@ -23,8 +26,11 @@ namespace blink {
WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(
v8::Isolate* isolate,
WorkerClients* worker_clients,
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context,
WorkerReportingProxy& reporting_proxy)
- : worker_clients_(worker_clients),
+ : ExecutionContext(isolate),
+ worker_clients_(worker_clients),
+ web_worker_fetch_context_(std::move(web_worker_fetch_context)),
script_controller_(
WorkerOrWorkletScriptController::Create(this, isolate)),
reporting_proxy_(reporting_proxy),
@@ -93,22 +99,57 @@ void WorkerOrWorkletGlobalScope::CountDeprecation(WebFeature feature) {
ReportingProxy().CountDeprecation(feature);
}
+void WorkerOrWorkletGlobalScope::InitializeWebFetchContextIfNeeded() {
+ if (web_fetch_context_initialized_)
+ return;
+ web_fetch_context_initialized_ = true;
+
+ if (!web_worker_fetch_context_)
+ return;
+
+ DCHECK(!subresource_filter_);
+ web_worker_fetch_context_->InitializeOnWorkerThread();
+ std::unique_ptr<blink::WebDocumentSubresourceFilter> web_filter =
+ web_worker_fetch_context_->TakeSubresourceFilter();
+ if (web_filter) {
+ subresource_filter_ =
+ SubresourceFilter::Create(*this, std::move(web_filter));
+ }
+}
+
ResourceFetcher* WorkerOrWorkletGlobalScope::EnsureFetcher() {
DCHECK(IsContextThread());
- if (resource_fetcher_)
- return resource_fetcher_;
- WorkerFetchContext* fetch_context = WorkerFetchContext::Create(*this);
- resource_fetcher_ = ResourceFetcher::Create(fetch_context);
+ if (inside_settings_resource_fetcher_)
+ return inside_settings_resource_fetcher_;
+ inside_settings_resource_fetcher_ = CreateFetcherInternal(
+ MakeGarbageCollected<FetchClientSettingsObjectImpl>(*this));
+ return inside_settings_resource_fetcher_;
+}
+
+ResourceFetcher* WorkerOrWorkletGlobalScope::CreateFetcherInternal(
+ FetchClientSettingsObject* fetch_client_settings_object) {
+ DCHECK(IsContextThread());
+ InitializeWebFetchContextIfNeeded();
+ WorkerFetchContext* fetch_context = WorkerFetchContext::Create(
+ *this, web_worker_fetch_context_, subresource_filter_,
+ fetch_client_settings_object);
+ ResourceFetcher* resource_fetcher = ResourceFetcher::Create(fetch_context);
if (IsContextPaused())
- resource_fetcher_->SetDefersLoading(true);
- DCHECK(resource_fetcher_);
- return resource_fetcher_;
+ resource_fetcher->SetDefersLoading(true);
+ resource_fetchers_.insert(resource_fetcher);
+ return resource_fetcher;
}
ResourceFetcher* WorkerOrWorkletGlobalScope::Fetcher() const {
DCHECK(IsContextThread());
- DCHECK(resource_fetcher_);
- return resource_fetcher_;
+ DCHECK(inside_settings_resource_fetcher_);
+ return inside_settings_resource_fetcher_;
+}
+
+ResourceFetcher* WorkerOrWorkletGlobalScope::CreateOutsideSettingsFetcher(
+ FetchClientSettingsObject* fetch_client_settings_object) {
+ DCHECK(IsContextThread());
+ return CreateFetcherInternal(fetch_client_settings_object);
}
bool WorkerOrWorkletGlobalScope::IsJSExecutionForbidden() const {
@@ -132,9 +173,9 @@ void WorkerOrWorkletGlobalScope::Dispose() {
script_controller_->Dispose();
script_controller_.Clear();
- if (resource_fetcher_) {
- resource_fetcher_->StopFetching();
- resource_fetcher_->ClearContext();
+ for (ResourceFetcher* resource_fetcher : resource_fetchers_) {
+ resource_fetcher->StopFetching();
+ resource_fetcher->ClearContext();
}
}
@@ -192,7 +233,7 @@ void WorkerOrWorkletGlobalScope::FetchModuleScript(
// string."
ScriptFetchOptions options(nonce, IntegrityMetadataSet(), integrity_attribute,
parser_state, credentials_mode,
- kReferrerPolicyDefault);
+ network::mojom::ReferrerPolicy::kDefault);
Modulator* modulator = Modulator::From(ScriptController()->GetScriptState());
// Step 3. "Perform the internal module script graph fetching procedure ..."
@@ -202,18 +243,20 @@ void WorkerOrWorkletGlobalScope::FetchModuleScript(
void WorkerOrWorkletGlobalScope::TasksWerePaused() {
ExecutionContext::TasksWerePaused();
- if (resource_fetcher_)
- resource_fetcher_->SetDefersLoading(true);
+ for (ResourceFetcher* resource_fetcher : resource_fetchers_)
+ resource_fetcher->SetDefersLoading(true);
}
void WorkerOrWorkletGlobalScope::TasksWereUnpaused() {
ExecutionContext::TasksWereUnpaused();
- if (resource_fetcher_)
- resource_fetcher_->SetDefersLoading(false);
+ for (ResourceFetcher* resource_fetcher : resource_fetchers_)
+ resource_fetcher->SetDefersLoading(false);
}
void WorkerOrWorkletGlobalScope::Trace(blink::Visitor* visitor) {
- visitor->Trace(resource_fetcher_);
+ visitor->Trace(inside_settings_resource_fetcher_);
+ visitor->Trace(resource_fetchers_);
+ visitor->Trace(subresource_filter_);
visitor->Trace(script_controller_);
visitor->Trace(modulator_);
EventTargetWithInlineData::Trace(visitor);
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h
index afc993d8520..83c26870289 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_or_worklet_global_scope.h
@@ -9,6 +9,7 @@
#include "services/network/public/mojom/fetch_api.mojom-shared.h"
#include "third_party/blink/public/platform/web_url_request.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
+#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/events/event_target.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/execution_context/security_context.h"
@@ -22,10 +23,13 @@
namespace blink {
+class FetchClientSettingsObject;
class FetchClientSettingsObjectSnapshot;
class Modulator;
class ModuleTreeClient;
class ResourceFetcher;
+class SubresourceFilter;
+class WebWorkerFetchContext;
class WorkerOrWorkletScriptController;
class WorkerReportingProxy;
class WorkerThread;
@@ -39,6 +43,7 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
WorkerOrWorkletGlobalScope(v8::Isolate*,
WorkerClients*,
+ scoped_refptr<WebWorkerFetchContext>,
WorkerReportingProxy&);
~WorkerOrWorkletGlobalScope() override;
@@ -89,6 +94,17 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
ResourceFetcher* Fetcher() const override;
ResourceFetcher* EnsureFetcher();
+ // ResourceFetcher for off-the-main-thread worker top-level script fetching,
+ // corresponding to "outside" fetch client's settings object.
+ // CreateOutsideSettingsFetcher() is called for each invocation of top-level
+ // script fetch, which can occur multiple times in worklets.
+ // TODO(hiroshige, nhiroki): Currently this outside ResourceFetcher and its
+ // WorkerFetchContext is mostly the copy of the insideSettings
+ // ResourceFetcher, and have dependencies to WorkerOrWorkletGlobalScope. Plumb
+ // more data to the outside ResourceFetcher to fix the behavior and reduce the
+ // dependencies.
+ ResourceFetcher* CreateOutsideSettingsFetcher(FetchClientSettingsObject*);
+
WorkerClients* Clients() const { return worker_clients_.Get(); }
WorkerOrWorkletScriptController* ScriptController() {
@@ -119,8 +135,34 @@ class CORE_EXPORT WorkerOrWorkletGlobalScope : public EventTargetWithInlineData,
void TasksWereUnpaused() override;
private:
+ void InitializeWebFetchContextIfNeeded();
+ ResourceFetcher* CreateFetcherInternal(FetchClientSettingsObject*);
+
+ bool web_fetch_context_initialized_ = false;
+
CrossThreadPersistent<WorkerClients> worker_clients_;
- Member<ResourceFetcher> resource_fetcher_;
+
+ Member<ResourceFetcher> inside_settings_resource_fetcher_;
+
+ // Keeps track of all ResourceFetchers (including
+ // |inside_settings_resource_fetcher_|) for disposing and pausing/unpausing.
+ HeapHashSet<WeakMember<ResourceFetcher>> resource_fetchers_;
+
+ // A WorkerOrWorkletGlobalScope has one WebWorkerFetchContext and one
+ // corresponding SubresourceFilter, which are shared by all
+ // WorkerFetchContexts of |this| global scope, i.e. those behind
+ // ResourceFetchers created by EnsureFetcher() and
+ // CreateOutsideSettingsFetcher().
+ // As all references to |web_worker_fetch_context_| are on the context
+ // thread, |web_worker_fetch_context_| is destructed on the context
+ // thread.
+ //
+ // TODO(crbug/903579): Consider putting WebWorkerFetchContext-originated
+ // things at a single place. Currently they are placed here and subclasses of
+ // WebWorkerFetchContext.
+ scoped_refptr<WebWorkerFetchContext> web_worker_fetch_context_;
+ Member<SubresourceFilter> subresource_filter_;
+
Member<WorkerOrWorkletScriptController> script_controller_;
WorkerReportingProxy& reporting_proxy_;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h b/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h
index c801c3efe45..c4a1f1c8adb 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_reporting_proxy.h
@@ -60,7 +60,6 @@ class CORE_EXPORT WorkerReportingProxy {
MessageLevel,
const String& message,
SourceLocation*) {}
- virtual void PostMessageToPageInspector(int session_id, const String&) {}
// Invoked when the new WorkerGlobalScope is created on
// WorkerThread::InitializeOnWorkerThread.
@@ -76,6 +75,14 @@ class CORE_EXPORT WorkerReportingProxy {
// via ResourceLoader. Called before WillEvaluateClassicScript().
virtual void DidLoadInstalledScript() {}
+ // Invoked when it's failed to load the worker's main script from
+ // InstalledScriptsManager.
+ virtual void DidFailToLoadInstalledClassicScript() {}
+
+ // Invoked on failure to fetch the worker's module script (either from network
+ // or InstalledScriptsManager).
+ virtual void DidFailToFetchModuleScript() {}
+
// Invoked when the main classic script is about to be evaluated.
virtual void WillEvaluateClassicScript(size_t script_size,
size_t cached_metadata_size) {}
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread.cc b/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
index a231d079da2..dfe382cdefb 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread.cc
@@ -36,6 +36,7 @@
#include "third_party/blink/renderer/bindings/core/v8/worker_or_worklet_script_controller.h"
#include "third_party/blink/renderer/core/inspector/console_message_storage.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/inspector/worker_inspector_controller.h"
#include "third_party/blink/renderer/core/inspector/worker_thread_debugger.h"
#include "third_party/blink/renderer/core/probe/core_probes.h"
@@ -50,8 +51,8 @@
#include "third_party/blink/renderer/platform/histogram.h"
#include "third_party/blink/renderer/platform/loader/fetch/fetch_client_settings_object_snapshot.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
-#include "third_party/blink/renderer/platform/scheduler/child/webthread_impl_for_worker_scheduler.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_scheduler.h"
+#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread.h"
#include "third_party/blink/renderer/platform/scheduler/worker/worker_thread_scheduler.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
@@ -107,19 +108,6 @@ class WorkerThread::RefCountedWaitableEvent
DISALLOW_COPY_AND_ASSIGN(RefCountedWaitableEvent);
};
-WorkerThread::ScopedDebuggerTask::ScopedDebuggerTask(WorkerThread* thread)
- : thread_(thread) {
- MutexLocker lock(thread_->mutex_);
- DCHECK(thread_->IsCurrentThread());
- thread_->debugger_task_counter_++;
-}
-
-WorkerThread::ScopedDebuggerTask::~ScopedDebuggerTask() {
- MutexLocker lock(thread_->mutex_);
- DCHECK(thread_->IsCurrentThread());
- thread_->debugger_task_counter_--;
-}
-
WorkerThread::~WorkerThread() {
MutexLocker lock(ThreadSetMutex());
DCHECK(WorkerThreads().Contains(this));
@@ -136,12 +124,13 @@ WorkerThread::~WorkerThread() {
void WorkerThread::Start(
std::unique_ptr<GlobalScopeCreationParams> global_scope_creation_params,
const base::Optional<WorkerBackingThreadStartupData>& thread_startup_data,
- WorkerInspectorProxy::PauseOnWorkerStart pause_on_start,
+ std::unique_ptr<WorkerDevToolsParams> devtools_params,
ParentExecutionContextTaskRunners* parent_execution_context_task_runners) {
DCHECK_CALLED_ON_VALID_THREAD(parent_thread_checker_);
DCHECK(!parent_execution_context_task_runners_);
parent_execution_context_task_runners_ =
parent_execution_context_task_runners;
+ devtools_worker_token_ = devtools_params->devtools_worker_token;
// Synchronously initialize the per-global-scope scheduler to prevent someone
// from posting a task to the thread before the scheduler is ready.
@@ -158,15 +147,14 @@ void WorkerThread::Start(
GetWorkerBackingThread().BackingThread().PostTask(
FROM_HERE,
- CrossThreadBind(&WorkerThread::InitializeOnWorkerThread,
- CrossThreadUnretained(this),
- WTF::Passed(std::move(global_scope_creation_params)),
- thread_startup_data, pause_on_start));
+ CrossThreadBind(
+ &WorkerThread::InitializeOnWorkerThread, CrossThreadUnretained(this),
+ WTF::Passed(std::move(global_scope_creation_params)),
+ thread_startup_data, WTF::Passed(std::move(devtools_params))));
}
void WorkerThread::EvaluateClassicScript(
const KURL& script_url,
- AccessControlStatus access_control_status,
const String& source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id) {
@@ -174,11 +162,23 @@ void WorkerThread::EvaluateClassicScript(
PostCrossThreadTask(
*GetTaskRunner(TaskType::kInternalWorker), FROM_HERE,
CrossThreadBind(&WorkerThread::EvaluateClassicScriptOnWorkerThread,
- CrossThreadUnretained(this), script_url,
- access_control_status, source_code,
+ CrossThreadUnretained(this), script_url, source_code,
WTF::Passed(std::move(cached_meta_data)), stack_id));
}
+void WorkerThread::ImportClassicScript(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ DCHECK_CALLED_ON_VALID_THREAD(parent_thread_checker_);
+ PostCrossThreadTask(
+ *GetTaskRunner(TaskType::kInternalWorker), FROM_HERE,
+ CrossThreadBind(&WorkerThread::ImportClassicScriptOnWorkerThread,
+ CrossThreadUnretained(this), script_url,
+ WTF::Passed(outside_settings_object->CopyData()),
+ stack_id));
+}
+
void WorkerThread::ImportModuleScript(
const KURL& script_url,
FetchClientSettingsObjectSnapshot* outside_settings_object,
@@ -243,14 +243,14 @@ void WorkerThread::TerminateAllWorkersForTesting() {
thread->ClearWorkerBackingThread();
}
-void WorkerThread::WillProcessTask() {
+void WorkerThread::WillProcessTask(const base::PendingTask& pending_task) {
DCHECK(IsCurrentThread());
// No tasks should get executed after we have closed.
DCHECK(!GlobalScope()->IsClosing());
}
-void WorkerThread::DidProcessTask() {
+void WorkerThread::DidProcessTask(const base::PendingTask& pending_task) {
DCHECK(IsCurrentThread());
Microtask::PerformCheckpoint(GetIsolate());
GlobalScope()->ScriptController()->GetRejectedPromises()->ProcessQueue();
@@ -275,9 +275,16 @@ bool WorkerThread::IsCurrentThread() {
return GetWorkerBackingThread().BackingThread().IsCurrentThread();
}
-InspectorTaskRunner* WorkerThread::GetInspectorTaskRunner() {
- DCHECK_CALLED_ON_VALID_THREAD(parent_thread_checker_);
- return inspector_task_runner_.get();
+void WorkerThread::DebuggerTaskStarted() {
+ MutexLocker lock(mutex_);
+ DCHECK(IsCurrentThread());
+ debugger_task_counter_++;
+}
+
+void WorkerThread::DebuggerTaskFinished() {
+ MutexLocker lock(mutex_);
+ DCHECK(IsCurrentThread());
+ debugger_task_counter_--;
}
WorkerOrWorkletGlobalScope* WorkerThread::GlobalScope() {
@@ -358,7 +365,6 @@ WorkerThread::WorkerThread(WorkerReportingProxy& worker_reporting_proxy)
: time_origin_(CurrentTimeTicks()),
worker_thread_id_(GetNextWorkerThreadId()),
forcible_termination_delay_(kForcibleTerminationDelay),
- devtools_worker_token_(base::UnguessableToken::Create()),
worker_reporting_proxy_(worker_reporting_proxy),
shutdown_event_(RefCountedWaitableEvent::Create()) {
MutexLocker lock(ThreadSetMutex());
@@ -414,20 +420,20 @@ void WorkerThread::InitializeSchedulerOnWorkerThread(
base::WaitableEvent* waitable_event) {
DCHECK(IsCurrentThread());
DCHECK(!worker_scheduler_);
- scheduler::WebThreadImplForWorkerScheduler& web_thread_for_worker =
- static_cast<scheduler::WebThreadImplForWorkerScheduler&>(
+ scheduler::WorkerThread& worker_thread =
+ static_cast<scheduler::WorkerThread&>(
GetWorkerBackingThread().BackingThread().PlatformThread());
worker_scheduler_ = std::make_unique<scheduler::WorkerScheduler>(
static_cast<scheduler::WorkerThreadScheduler*>(
- web_thread_for_worker.GetNonMainThreadScheduler()),
- web_thread_for_worker.worker_scheduler_proxy());
+ worker_thread.GetNonMainThreadScheduler()),
+ worker_thread.worker_scheduler_proxy());
waitable_event->Signal();
}
void WorkerThread::InitializeOnWorkerThread(
std::unique_ptr<GlobalScopeCreationParams> global_scope_creation_params,
const base::Optional<WorkerBackingThreadStartupData>& thread_startup_data,
- WorkerInspectorProxy::PauseOnWorkerStart pause_on_start) {
+ std::unique_ptr<WorkerDevToolsParams> devtools_params) {
DCHECK(IsCurrentThread());
{
MutexLocker lock(mutex_);
@@ -447,7 +453,9 @@ void WorkerThread::InitializeOnWorkerThread(
global_scope_ =
CreateWorkerGlobalScope(std::move(global_scope_creation_params));
worker_reporting_proxy_.DidCreateWorkerGlobalScope(GlobalScope());
- worker_inspector_controller_ = WorkerInspectorController::Create(this);
+
+ worker_inspector_controller_ = WorkerInspectorController::Create(
+ this, inspector_task_runner_, std::move(devtools_params));
// Since context initialization below may fail, we should notify debugger
// about the new worker thread separately, so that it can resolve it by id
@@ -483,25 +491,32 @@ void WorkerThread::InitializeOnWorkerThread(
// Otherwise, InspectorTaskRunner might interrupt isolate execution
// from another thread and try to resume "pause on start" before
// we even paused.
- if (pause_on_start == WorkerInspectorProxy::PauseOnWorkerStart::kPause) {
- WorkerThreadDebugger* debugger = WorkerThreadDebugger::From(GetIsolate());
- if (debugger)
- debugger->PauseWorkerOnStart(this);
- }
+ worker_inspector_controller_->WaitForDebuggerIfNeeded();
}
void WorkerThread::EvaluateClassicScriptOnWorkerThread(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id) {
- ToWorkerGlobalScope(GlobalScope())
- ->EvaluateClassicScriptPausable(script_url, access_control_status,
- std::move(source_code),
+ To<WorkerGlobalScope>(GlobalScope())
+ ->EvaluateClassicScriptPausable(script_url, std::move(source_code),
std::move(cached_meta_data), stack_id);
}
+void WorkerThread::ImportClassicScriptOnWorkerThread(
+ const KURL& script_url,
+ std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
+ outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id) {
+ To<WorkerGlobalScope>(GlobalScope())
+ ->ImportClassicScriptPausable(
+ script_url,
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ std::move(outside_settings_object)),
+ stack_id);
+}
+
void WorkerThread::ImportModuleScriptOnWorkerThread(
const KURL& script_url,
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
@@ -510,11 +525,12 @@ void WorkerThread::ImportModuleScriptOnWorkerThread(
// Worklets have a different code path to import module scripts.
// TODO(nhiroki): Consider excluding this code path from WorkerThread like
// Worklets.
- ToWorkerGlobalScope(GlobalScope())
- ->ImportModuleScriptPausable(script_url,
- new FetchClientSettingsObjectSnapshot(
- std::move(outside_settings_object)),
- credentials_mode);
+ To<WorkerGlobalScope>(GlobalScope())
+ ->ImportModuleScriptPausable(
+ script_url,
+ MakeGarbageCollected<FetchClientSettingsObjectSnapshot>(
+ std::move(outside_settings_object)),
+ credentials_mode);
}
void WorkerThread::PrepareForShutdownOnWorkerThread() {
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread.h b/chromium/third_party/blink/renderer/core/workers/worker_thread.h
index 36e197428fd..a7a03d2f5cd 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread.h
@@ -41,11 +41,10 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
#include "third_party/blink/renderer/core/workers/worker_backing_thread_startup_data.h"
-#include "third_party/blink/renderer/core/workers/worker_inspector_proxy.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cancellable_task.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
#include "third_party/blink/renderer/platform/scheduler/public/thread.h"
#include "third_party/blink/renderer/platform/scheduler/public/worker_scheduler.h"
-#include "third_party/blink/renderer/platform/web_task_runner.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/forward.h"
#include "third_party/blink/renderer/platform/wtf/functional.h"
@@ -63,6 +62,7 @@ class WorkerOrWorkletGlobalScope;
class WorkerReportingProxy;
struct CrossThreadFetchClientSettingsObjectData;
struct GlobalScopeCreationParams;
+struct WorkerDevToolsParams;
// WorkerThread is a kind of WorkerBackingThread client. Each worker mechanism
// can access the lower thread infrastructure via an implementation of this
@@ -101,17 +101,23 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
// (https://crbug.com/710364)
void Start(std::unique_ptr<GlobalScopeCreationParams>,
const base::Optional<WorkerBackingThreadStartupData>&,
- WorkerInspectorProxy::PauseOnWorkerStart,
+ std::unique_ptr<WorkerDevToolsParams>,
ParentExecutionContextTaskRunners*);
// Posts a task to evaluate a top-level classic script on the worker thread.
// Called on the main thread after Start().
void EvaluateClassicScript(const KURL& script_url,
- AccessControlStatus access_control_status,
const String& source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id);
+ // Posts a task to import a top-level classic script on the worker thread.
+ // Called on the main thread after start().
+ void ImportClassicScript(
+ const KURL& script_url,
+ FetchClientSettingsObjectSnapshot* outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id);
+
// Posts a task to import a top-level module script on the worker thread.
// Called on the main thread after start().
void ImportModuleScript(
@@ -140,8 +146,8 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
static void TerminateAllWorkersForTesting();
// Thread::TaskObserver.
- void WillProcessTask() override;
- void DidProcessTask() override;
+ void WillProcessTask(const base::PendingTask&) override;
+ void DidProcessTask(const base::PendingTask&) override;
virtual WorkerBackingThread& GetWorkerBackingThread() = 0;
virtual void ClearWorkerBackingThread() = 0;
@@ -156,19 +162,9 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
return worker_reporting_proxy_;
}
- // Only constructible on the main thread.
- class CORE_EXPORT ScopedDebuggerTask {
- STACK_ALLOCATED();
-
- public:
- explicit ScopedDebuggerTask(WorkerThread*);
- ~ScopedDebuggerTask();
-
- private:
- WorkerThread* thread_;
- DISALLOW_COPY_AND_ASSIGN(ScopedDebuggerTask);
- };
- InspectorTaskRunner* GetInspectorTaskRunner();
+ // Only callable on the parent thread.
+ void DebuggerTaskStarted();
+ void DebuggerTaskFinished();
// Callable on both the main thread and the worker thread.
const base::UnguessableToken& GetDevToolsWorkerToken() const {
@@ -290,14 +286,18 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
void InitializeOnWorkerThread(
std::unique_ptr<GlobalScopeCreationParams>,
const base::Optional<WorkerBackingThreadStartupData>&,
- WorkerInspectorProxy::PauseOnWorkerStart) LOCKS_EXCLUDED(mutex_);
+ std::unique_ptr<WorkerDevToolsParams>) LOCKS_EXCLUDED(mutex_);
void EvaluateClassicScriptOnWorkerThread(
const KURL& script_url,
- AccessControlStatus access_control_status,
String source_code,
std::unique_ptr<Vector<char>> cached_meta_data,
const v8_inspector::V8StackTraceId& stack_id);
+ void ImportClassicScriptOnWorkerThread(
+ const KURL& script_url,
+ std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
+ outside_settings_object,
+ const v8_inspector::V8StackTraceId& stack_id);
void ImportModuleScriptOnWorkerThread(
const KURL& script_url,
std::unique_ptr<CrossThreadFetchClientSettingsObjectData>
@@ -325,7 +325,7 @@ class CORE_EXPORT WorkerThread : public Thread::TaskObserver {
TimeDelta forcible_termination_delay_;
scoped_refptr<InspectorTaskRunner> inspector_task_runner_;
- const base::UnguessableToken devtools_worker_token_;
+ base::UnguessableToken devtools_worker_token_;
int debugger_task_counter_ GUARDED_BY(mutex_) = 0;
WorkerReportingProxy& worker_reporting_proxy_;
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc b/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc
index 4c9c29a7ba5..05edaaf7074 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread_test.cc
@@ -12,6 +12,7 @@
#include "third_party/blink/renderer/bindings/core/v8/v8_cache_options.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/inspector/inspector_task_runner.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
@@ -65,8 +66,9 @@ void WaitForSignalTask(WorkerThread* worker_thread,
*worker_thread->GetParentExecutionContextTaskRunners()->Get(
TaskType::kInternalTest),
FROM_HERE, CrossThreadBind(&test::ExitRunLoop));
- WorkerThread::ScopedDebuggerTask debugger_task(worker_thread);
+ worker_thread->DebuggerTaskStarted();
waitable_event->Wait();
+ worker_thread->DebuggerTaskFinished();
}
void TerminateParentOfNestedWorker(WorkerThread* parent_thread,
@@ -387,8 +389,9 @@ TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunningOnInitialization) {
auto global_scope_creation_params =
std::make_unique<GlobalScopeCreationParams>(
- KURL("http://fake.url/"), ScriptType::kClassic, "fake user agent",
- headers, kReferrerPolicyDefault, security_origin_.get(),
+ KURL("http://fake.url/"), mojom::ScriptType::kClassic,
+ "fake user agent", nullptr /* web_worker_fetch_context */, headers,
+ network::mojom::ReferrerPolicy::kDefault, security_origin_.get(),
false /* starter_secure_context */,
CalculateHttpsState(security_origin_.get()), WorkerClients::Create(),
mojom::IPAddressSpace::kLocal, nullptr /* originTrialToken */,
@@ -396,11 +399,14 @@ TEST_F(WorkerThreadTest, Terminate_WhileDebuggerTaskIsRunningOnInitialization) {
std::make_unique<WorkerSettings>(Settings::Create().get()),
kV8CacheOptionsDefault, nullptr /* worklet_module_responses_map */);
- // Specify PauseOnWorkerStart::kPause so that the worker thread can pause
+ // Set wait_for_debugger so that the worker thread can pause
// on initialization to run debugger tasks.
+ auto devtools_params = std::make_unique<WorkerDevToolsParams>();
+ devtools_params->wait_for_debugger = true;
+
worker_thread_->Start(std::move(global_scope_creation_params),
WorkerBackingThreadStartupData::CreateDefault(),
- WorkerInspectorProxy::PauseOnWorkerStart::kPause,
+ std::move(devtools_params),
ParentExecutionContextTaskRunners::Create());
// Used to wait for worker thread termination in a debugger task on the
diff --git a/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h b/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h
index b7a8348fb4f..590fb8729f1 100644
--- a/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h
+++ b/chromium/third_party/blink/renderer/core/workers/worker_thread_test_helper.h
@@ -16,6 +16,7 @@
#include "third_party/blink/renderer/core/frame/csp/content_security_policy.h"
#include "third_party/blink/renderer/core/frame/settings.h"
#include "third_party/blink/renderer/core/inspector/console_message.h"
+#include "third_party/blink/renderer/core/inspector/worker_devtools_params.h"
#include "third_party/blink/renderer/core/script/script.h"
#include "third_party/blink/renderer/core/workers/global_scope_creation_params.h"
#include "third_party/blink/renderer/core/workers/parent_execution_context_task_runners.h"
@@ -27,7 +28,6 @@
#include "third_party/blink/renderer/core/workers/worker_thread.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
-#include "third_party/blink/renderer/platform/loader/fetch/access_control_status.h"
#include "third_party/blink/renderer/platform/network/content_security_policy_parsers.h"
#include "third_party/blink/renderer/platform/waitable_event.h"
#include "third_party/blink/renderer/platform/web_thread_supporting_gc.h"
@@ -53,7 +53,7 @@ class FakeWorkerGlobalScope : public WorkerGlobalScope {
// EventTarget
const AtomicString& InterfaceName() const override {
- return EventTargetNames::DedicatedWorkerGlobalScope;
+ return event_target_names::kDedicatedWorkerGlobalScope;
}
// WorkerGlobalScope
@@ -91,8 +91,9 @@ class WorkerThreadForTest : public WorkerThread {
Vector<CSPHeaderAndType> headers{
{"contentSecurityPolicy", kContentSecurityPolicyHeaderTypeReport}};
auto creation_params = std::make_unique<GlobalScopeCreationParams>(
- script_url, ScriptType::kClassic, "fake user agent", headers,
- kReferrerPolicyDefault, security_origin,
+ script_url, mojom::ScriptType::kClassic, "fake user agent",
+ nullptr /* web_worker_fetch_context */, headers,
+ network::mojom::ReferrerPolicy::kDefault, security_origin,
false /* starter_secure_context */,
CalculateHttpsState(security_origin), worker_clients,
mojom::IPAddressSpace::kLocal, nullptr,
@@ -102,10 +103,9 @@ class WorkerThreadForTest : public WorkerThread {
Start(std::move(creation_params),
WorkerBackingThreadStartupData::CreateDefault(),
- WorkerInspectorProxy::PauseOnWorkerStart::kDontPause,
+ std::make_unique<WorkerDevToolsParams>(),
parent_execution_context_task_runners);
- EvaluateClassicScript(script_url, kOpaqueResource, source,
- nullptr /* cached_meta_data */,
+ EvaluateClassicScript(script_url, source, nullptr /* cached_meta_data */,
v8_inspector::V8StackTraceId());
}
@@ -120,7 +120,8 @@ class WorkerThreadForTest : public WorkerThread {
protected:
WorkerOrWorkletGlobalScope* CreateWorkerGlobalScope(
std::unique_ptr<GlobalScopeCreationParams> creation_params) override {
- return new FakeWorkerGlobalScope(std::move(creation_params), this);
+ return MakeGarbageCollected<FakeWorkerGlobalScope>(
+ std::move(creation_params), this);
}
private:
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet.cc b/chromium/third_party/blink/renderer/core/workers/worklet.cc
index 0e1999187fb..0739eea7373 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet.cc
@@ -37,7 +37,7 @@ Worklet::~Worklet() {
// https://drafts.css-houdini.org/worklets/#dom-worklet-addmodule
ScriptPromise Worklet::addModule(ScriptState* script_state,
const String& module_url,
- const WorkletOptions& options) {
+ const WorkletOptions* options) {
DCHECK(IsMainThread());
if (!GetExecutionContext()) {
return ScriptPromise::RejectWithDOMException(
@@ -67,7 +67,8 @@ ScriptPromise Worklet::addModule(ScriptState* script_state,
return promise;
}
- WorkletPendingTasks* pending_tasks = new WorkletPendingTasks(this, resolver);
+ WorkletPendingTasks* pending_tasks =
+ MakeGarbageCollected<WorkletPendingTasks>(this, resolver);
pending_tasks_set_.insert(pending_tasks);
// Step 5: "Return promise, and then continue running this algorithm in
@@ -78,7 +79,7 @@ ScriptPromise Worklet::addModule(ScriptState* script_state,
->GetTaskRunner(TaskType::kInternalLoading)
->PostTask(FROM_HERE,
WTF::Bind(&Worklet::FetchAndInvokeScript, WrapPersistent(this),
- module_url_record, options.credentials(),
+ module_url_record, options->credentials(),
WrapPersistent(pending_tasks)));
return promise;
}
@@ -164,7 +165,7 @@ void Worklet::FetchAndInvokeScript(const KURL& module_url_record,
}
}
-size_t Worklet::SelectGlobalScope() {
+wtf_size_t Worklet::SelectGlobalScope() {
DCHECK_EQ(GetNumberOfGlobalScopes(), 1u);
return 0u;
}
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet.h b/chromium/third_party/blink/renderer/core/workers/worklet.h
index 696843c15d5..1fe048cb334 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet.h
@@ -38,7 +38,7 @@ class CORE_EXPORT Worklet : public ScriptWrappable,
// addModule() imports ES6 module scripts.
ScriptPromise addModule(ScriptState*,
const String& module_url,
- const WorkletOptions&);
+ const WorkletOptions*);
// ContextLifecycleObserver
void ContextDestroyed(ExecutionContext*) override;
@@ -58,12 +58,18 @@ class CORE_EXPORT Worklet : public ScriptWrappable,
// Returns one of available global scopes.
WorkletGlobalScopeProxy* FindAvailableGlobalScope();
- size_t GetNumberOfGlobalScopes() const { return proxies_.size(); }
+ wtf_size_t GetNumberOfGlobalScopes() const { return proxies_.size(); }
WorkletModuleResponsesMap* ModuleResponsesMap() const {
return module_responses_map_.Get();
}
+ // "A Worklet has a list of the worklet's WorkletGlobalScopes. Initially this
+ // list is empty; it is populated when the user agent chooses to create its
+ // WorkletGlobalScope."
+ // https://drafts.css-houdini.org/worklets/#worklet-section
+ HeapVector<Member<WorkletGlobalScopeProxy>> proxies_;
+
private:
virtual void FetchAndInvokeScript(const KURL& module_url_record,
const String& credentials,
@@ -79,14 +85,7 @@ class CORE_EXPORT Worklet : public ScriptWrappable,
// there are multiple global scopes, this function MUST be overriden. The
// default behavior is to return the global scope at index 0, which is for the
// case where there is only one global scope.
- virtual size_t SelectGlobalScope();
-
- // "A Worklet has a list of the worklet's WorkletGlobalScopes. Initially this
- // list is empty; it is populated when the user agent chooses to create its
- // WorkletGlobalScope."
- // https://drafts.css-houdini.org/worklets/#worklet-section
- HeapVector<Member<WorkletGlobalScopeProxy>> proxies_;
-
+ virtual wtf_size_t SelectGlobalScope();
// "A Worklet has a module responses map. This is a ordered map of module URLs
// to values that are a fetch responses. The map's entries are ordered based
// on their insertion order. Access to this map should be thread-safe."
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc
index fb879e45a87..88da265e145 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.cc
@@ -61,9 +61,11 @@ WorkletGlobalScope::WorkletGlobalScope(
ThreadType thread_type,
LocalFrame* frame,
WorkerThread* worker_thread)
- : WorkerOrWorkletGlobalScope(isolate,
- creation_params->worker_clients,
- reporting_proxy),
+ : WorkerOrWorkletGlobalScope(
+ isolate,
+ creation_params->worker_clients,
+ std::move(creation_params->web_worker_fetch_context),
+ reporting_proxy),
url_(creation_params->script_url),
user_agent_(creation_params->user_agent),
document_security_origin_(creation_params->starter_origin),
@@ -203,8 +205,9 @@ void WorkletGlobalScope::FetchAndInvokeScript(
// Step 3 to 5 are implemented in
// WorkletModuleTreeClient::NotifyModuleTreeLoadFinished.
- WorkletModuleTreeClient* client = new WorkletModuleTreeClient(
- modulator, std::move(outside_settings_task_runner), pending_tasks);
+ WorkletModuleTreeClient* client =
+ MakeGarbageCollected<WorkletModuleTreeClient>(
+ modulator, std::move(outside_settings_task_runner), pending_tasks);
// TODO(nhiroki): Specify an appropriate destination defined in each worklet
// spec (e.g., "paint worklet", "audio worklet").
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h
index 1bdbef81c7d..2b748a33752 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_global_scope.h
@@ -17,6 +17,7 @@
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_member.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
+#include "third_party/blink/renderer/platform/wtf/casting.h"
namespace blink {
@@ -180,11 +181,12 @@ class CORE_EXPORT WorkletGlobalScope
WorkerThread* worker_thread_;
};
-DEFINE_TYPE_CASTS(WorkletGlobalScope,
- ExecutionContext,
- context,
- context->IsWorkletGlobalScope(),
- context.IsWorkletGlobalScope());
+template <>
+struct DowncastTraits<WorkletGlobalScope> {
+ static bool AllowFrom(const ExecutionContext& context) {
+ return context.IsWorkletGlobalScope();
+ }
+};
} // namespace blink
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc
index 17152f5e186..940a822a3f3 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map.cc
@@ -6,6 +6,7 @@
#include "base/optional.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc
index 3e1bf3da7e3..880426c2298 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_module_responses_map_test.cc
@@ -29,7 +29,7 @@ class WorkletModuleResponsesMapTest : public testing::Test {
auto* context =
MockFetchContext::Create(MockFetchContext::kShouldLoadNewResource);
fetcher_ = ResourceFetcher::Create(context);
- map_ = new WorkletModuleResponsesMap;
+ map_ = MakeGarbageCollected<WorkletModuleResponsesMap>();
}
void Fetch(const KURL& url, ClientImpl* client) {
@@ -39,7 +39,8 @@ class WorkletModuleResponsesMapTest : public testing::Test {
resource_request.SetRequestContext(mojom::RequestContextType::SCRIPT);
FetchParameters fetch_params(resource_request);
WorkletModuleScriptFetcher* module_fetcher =
- new WorkletModuleScriptFetcher(fetcher_.Get(), map_.Get());
+ MakeGarbageCollected<WorkletModuleScriptFetcher>(fetcher_.Get(),
+ map_.Get());
module_fetcher->Fetch(fetch_params, ModuleGraphLevel::kTopLevelModuleFetch,
client);
}
@@ -58,7 +59,7 @@ class WorkletModuleResponsesMapTest : public testing::Test {
TEST_F(WorkletModuleResponsesMapTest, Basic) {
const KURL kUrl("https://example.com/module.js");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
kUrl, test::CoreTestDataPath("module.js"), "text/javascript");
HeapVector<Member<ClientImpl>> clients;
@@ -89,7 +90,7 @@ TEST_F(WorkletModuleResponsesMapTest, Basic) {
TEST_F(WorkletModuleResponsesMapTest, Failure) {
const KURL kUrl("https://example.com/module.js");
- URLTestHelpers::RegisterMockedErrorURLLoad(kUrl);
+ url_test_helpers::RegisterMockedErrorURLLoad(kUrl);
HeapVector<Member<ClientImpl>> clients;
// An initial read call initiates a fetch request.
@@ -120,8 +121,8 @@ TEST_F(WorkletModuleResponsesMapTest, Failure) {
TEST_F(WorkletModuleResponsesMapTest, Isolation) {
const KURL kUrl1("https://example.com/module?1.js");
const KURL kUrl2("https://example.com/module?2.js");
- URLTestHelpers::RegisterMockedErrorURLLoad(kUrl1);
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedErrorURLLoad(kUrl1);
+ url_test_helpers::RegisterMockedURLLoad(
kUrl2, test::CoreTestDataPath("module.js"), "text/javascript");
HeapVector<Member<ClientImpl>> clients;
@@ -194,9 +195,9 @@ TEST_F(WorkletModuleResponsesMapTest, InvalidURL) {
TEST_F(WorkletModuleResponsesMapTest, Dispose) {
const KURL kUrl1("https://example.com/module?1.js");
const KURL kUrl2("https://example.com/module?2.js");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
kUrl1, test::CoreTestDataPath("module.js"), "text/javascript");
- URLTestHelpers::RegisterMockedURLLoad(
+ url_test_helpers::RegisterMockedURLLoad(
kUrl2, test::CoreTestDataPath("module.js"), "text/javascript");
HeapVector<Member<ClientImpl>> clients;
diff --git a/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc b/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc
index fb2499b7d7f..e936e508405 100644
--- a/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc
+++ b/chromium/third_party/blink/renderer/core/workers/worklet_module_tree_client.cc
@@ -9,6 +9,7 @@
#include "third_party/blink/renderer/core/workers/worker_reporting_proxy.h"
#include "third_party/blink/renderer/core/workers/worklet_global_scope.h"
#include "third_party/blink/renderer/platform/cross_thread_functional.h"
+#include "third_party/blink/renderer/platform/scheduler/public/post_cross_thread_task.h"
namespace blink {
@@ -58,7 +59,7 @@ void WorkletModuleTreeClient::NotifyModuleTreeLoadFinished(
ScriptValue error = modulator_->ExecuteModule(
module_script, Modulator::CaptureEvalErrorFlag::kReport);
- WorkletGlobalScope* global_scope = ToWorkletGlobalScope(
+ WorkletGlobalScope* global_scope = To<WorkletGlobalScope>(
ExecutionContext::From(modulator_->GetScriptState()));
global_scope->ReportingProxy().DidEvaluateModuleScript(error.IsEmpty());