feat: ServiceWorkerMain (#45232)
* feat: ServiceWorkerMain * refactor: disconnect remote * handle version_info_ nullptr case * initiate finish request when possible and enumerate errors * explicit name for test method * oops * fix: wait for redundant version to stop before destroying * docs: clarify when undefined is returned * chore: remove extra semicolons
This commit is contained in:
parent
75eac86506
commit
a467d0684e
23 changed files with 1265 additions and 50 deletions
|
@ -13,11 +13,18 @@
|
|||
#include "gin/data_object_builder.h"
|
||||
#include "gin/handle.h"
|
||||
#include "gin/object_template_builder.h"
|
||||
#include "shell/browser/api/electron_api_service_worker_main.h"
|
||||
#include "shell/browser/electron_browser_context.h"
|
||||
#include "shell/browser/javascript_environment.h"
|
||||
#include "shell/common/gin_converters/gurl_converter.h"
|
||||
#include "shell/common/gin_converters/service_worker_converter.h"
|
||||
#include "shell/common/gin_converters/value_converter.h"
|
||||
#include "shell/common/gin_helper/dictionary.h"
|
||||
#include "shell/common/gin_helper/promise.h"
|
||||
#include "shell/common/node_util.h"
|
||||
|
||||
using ServiceWorkerStatus =
|
||||
content::ServiceWorkerRunningInfo::ServiceWorkerVersionStatus;
|
||||
|
||||
namespace electron::api {
|
||||
|
||||
|
@ -72,8 +79,8 @@ gin::WrapperInfo ServiceWorkerContext::kWrapperInfo = {gin::kEmbedderNativeGin};
|
|||
ServiceWorkerContext::ServiceWorkerContext(
|
||||
v8::Isolate* isolate,
|
||||
ElectronBrowserContext* browser_context) {
|
||||
service_worker_context_ =
|
||||
browser_context->GetDefaultStoragePartition()->GetServiceWorkerContext();
|
||||
storage_partition_ = browser_context->GetDefaultStoragePartition();
|
||||
service_worker_context_ = storage_partition_->GetServiceWorkerContext();
|
||||
service_worker_context_->AddObserver(this);
|
||||
}
|
||||
|
||||
|
@ -81,6 +88,23 @@ ServiceWorkerContext::~ServiceWorkerContext() {
|
|||
service_worker_context_->RemoveObserver(this);
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnRunningStatusChanged(
|
||||
int64_t version_id,
|
||||
blink::EmbeddedWorkerStatus running_status) {
|
||||
ServiceWorkerMain* worker =
|
||||
ServiceWorkerMain::FromVersionID(version_id, storage_partition_);
|
||||
if (worker)
|
||||
worker->OnRunningStatusChanged(running_status);
|
||||
|
||||
v8::Isolate* isolate = JavascriptEnvironment::GetIsolate();
|
||||
v8::HandleScope scope(isolate);
|
||||
EmitWithoutEvent("running-status-changed",
|
||||
gin::DataObjectBuilder(isolate)
|
||||
.Set("versionId", version_id)
|
||||
.Set("runningStatus", running_status)
|
||||
.Build());
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnReportConsoleMessage(
|
||||
int64_t version_id,
|
||||
const GURL& scope,
|
||||
|
@ -105,6 +129,32 @@ void ServiceWorkerContext::OnRegistrationCompleted(const GURL& scope) {
|
|||
gin::DataObjectBuilder(isolate).Set("scope", scope).Build());
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnVersionRedundant(int64_t version_id,
|
||||
const GURL& scope) {
|
||||
ServiceWorkerMain* worker =
|
||||
ServiceWorkerMain::FromVersionID(version_id, storage_partition_);
|
||||
if (worker)
|
||||
worker->OnVersionRedundant();
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnVersionStartingRunning(int64_t version_id) {
|
||||
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kStarting);
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnVersionStartedRunning(
|
||||
int64_t version_id,
|
||||
const content::ServiceWorkerRunningInfo& running_info) {
|
||||
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kRunning);
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnVersionStoppingRunning(int64_t version_id) {
|
||||
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kStopping);
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnVersionStoppedRunning(int64_t version_id) {
|
||||
OnRunningStatusChanged(version_id, blink::EmbeddedWorkerStatus::kStopped);
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::OnDestruct(content::ServiceWorkerContext* context) {
|
||||
if (context == service_worker_context_) {
|
||||
delete this;
|
||||
|
@ -124,7 +174,7 @@ v8::Local<v8::Value> ServiceWorkerContext::GetAllRunningWorkerInfo(
|
|||
return builder.Build();
|
||||
}
|
||||
|
||||
v8::Local<v8::Value> ServiceWorkerContext::GetWorkerInfoFromID(
|
||||
v8::Local<v8::Value> ServiceWorkerContext::GetInfoFromVersionID(
|
||||
gin_helper::ErrorThrower thrower,
|
||||
int64_t version_id) {
|
||||
const base::flat_map<int64_t, content::ServiceWorkerRunningInfo>& info_map =
|
||||
|
@ -138,6 +188,87 @@ v8::Local<v8::Value> ServiceWorkerContext::GetWorkerInfoFromID(
|
|||
std::move(iter->second));
|
||||
}
|
||||
|
||||
v8::Local<v8::Value> ServiceWorkerContext::GetFromVersionID(
|
||||
gin_helper::ErrorThrower thrower,
|
||||
int64_t version_id) {
|
||||
util::EmitWarning(thrower.isolate(),
|
||||
"The session.serviceWorkers.getFromVersionID API is "
|
||||
"deprecated, use "
|
||||
"session.serviceWorkers.getInfoFromVersionID instead.",
|
||||
"ServiceWorkersDeprecateGetFromVersionID");
|
||||
|
||||
return GetInfoFromVersionID(thrower, version_id);
|
||||
}
|
||||
|
||||
v8::Local<v8::Value> ServiceWorkerContext::GetWorkerFromVersionID(
|
||||
v8::Isolate* isolate,
|
||||
int64_t version_id) {
|
||||
return ServiceWorkerMain::From(isolate, service_worker_context_,
|
||||
storage_partition_, version_id)
|
||||
.ToV8();
|
||||
}
|
||||
|
||||
gin::Handle<ServiceWorkerMain>
|
||||
ServiceWorkerContext::GetWorkerFromVersionIDIfExists(v8::Isolate* isolate,
|
||||
int64_t version_id) {
|
||||
ServiceWorkerMain* worker =
|
||||
ServiceWorkerMain::FromVersionID(version_id, storage_partition_);
|
||||
if (!worker)
|
||||
return gin::Handle<ServiceWorkerMain>();
|
||||
return gin::CreateHandle(isolate, worker);
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> ServiceWorkerContext::StartWorkerForScope(
|
||||
v8::Isolate* isolate,
|
||||
GURL scope) {
|
||||
auto shared_promise =
|
||||
std::make_shared<gin_helper::Promise<v8::Local<v8::Value>>>(isolate);
|
||||
v8::Local<v8::Promise> handle = shared_promise->GetHandle();
|
||||
|
||||
blink::StorageKey storage_key =
|
||||
blink::StorageKey::CreateFirstParty(url::Origin::Create(scope));
|
||||
service_worker_context_->StartWorkerForScope(
|
||||
scope, storage_key,
|
||||
base::BindOnce(&ServiceWorkerContext::DidStartWorkerForScope,
|
||||
weak_ptr_factory_.GetWeakPtr(), shared_promise),
|
||||
base::BindOnce(&ServiceWorkerContext::DidFailToStartWorkerForScope,
|
||||
weak_ptr_factory_.GetWeakPtr(), shared_promise));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::DidStartWorkerForScope(
|
||||
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
|
||||
int64_t version_id,
|
||||
int process_id,
|
||||
int thread_id) {
|
||||
v8::Isolate* isolate = shared_promise->isolate();
|
||||
v8::HandleScope handle_scope(isolate);
|
||||
v8::Local<v8::Value> service_worker_main =
|
||||
GetWorkerFromVersionID(isolate, version_id);
|
||||
shared_promise->Resolve(service_worker_main);
|
||||
shared_promise.reset();
|
||||
}
|
||||
|
||||
void ServiceWorkerContext::DidFailToStartWorkerForScope(
|
||||
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
|
||||
content::StatusCodeResponse status) {
|
||||
shared_promise->RejectWithErrorMessage("Failed to start service worker.");
|
||||
shared_promise.reset();
|
||||
}
|
||||
|
||||
v8::Local<v8::Promise> ServiceWorkerContext::StopAllWorkers(
|
||||
v8::Isolate* isolate) {
|
||||
auto promise = gin_helper::Promise<void>(isolate);
|
||||
v8::Local<v8::Promise> handle = promise.GetHandle();
|
||||
|
||||
service_worker_context_->StopAllServiceWorkers(base::BindOnce(
|
||||
[](gin_helper::Promise<void> promise) { promise.Resolve(); },
|
||||
std::move(promise)));
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
// static
|
||||
gin::Handle<ServiceWorkerContext> ServiceWorkerContext::Create(
|
||||
v8::Isolate* isolate,
|
||||
|
@ -153,8 +284,16 @@ gin::ObjectTemplateBuilder ServiceWorkerContext::GetObjectTemplateBuilder(
|
|||
ServiceWorkerContext>::GetObjectTemplateBuilder(isolate)
|
||||
.SetMethod("getAllRunning",
|
||||
&ServiceWorkerContext::GetAllRunningWorkerInfo)
|
||||
.SetMethod("getFromVersionID",
|
||||
&ServiceWorkerContext::GetWorkerInfoFromID);
|
||||
.SetMethod("getFromVersionID", &ServiceWorkerContext::GetFromVersionID)
|
||||
.SetMethod("getInfoFromVersionID",
|
||||
&ServiceWorkerContext::GetInfoFromVersionID)
|
||||
.SetMethod("getWorkerFromVersionID",
|
||||
&ServiceWorkerContext::GetWorkerFromVersionID)
|
||||
.SetMethod("_getWorkerFromVersionIDIfExists",
|
||||
&ServiceWorkerContext::GetWorkerFromVersionIDIfExists)
|
||||
.SetMethod("startWorkerForScope",
|
||||
&ServiceWorkerContext::StartWorkerForScope)
|
||||
.SetMethod("_stopAllWorkers", &ServiceWorkerContext::StopAllWorkers);
|
||||
}
|
||||
|
||||
const char* ServiceWorkerContext::GetTypeName() {
|
||||
|
|
|
@ -10,18 +10,30 @@
|
|||
#include "content/public/browser/service_worker_context_observer.h"
|
||||
#include "gin/wrappable.h"
|
||||
#include "shell/browser/event_emitter_mixin.h"
|
||||
#include "third_party/blink/public/common/service_worker/embedded_worker_status.h"
|
||||
|
||||
namespace content {
|
||||
class StoragePartition;
|
||||
}
|
||||
|
||||
namespace gin {
|
||||
template <typename T>
|
||||
class Handle;
|
||||
} // namespace gin
|
||||
|
||||
namespace gin_helper {
|
||||
template <typename T>
|
||||
class Promise;
|
||||
} // namespace gin_helper
|
||||
|
||||
namespace electron {
|
||||
|
||||
class ElectronBrowserContext;
|
||||
|
||||
namespace api {
|
||||
|
||||
class ServiceWorkerMain;
|
||||
|
||||
class ServiceWorkerContext final
|
||||
: public gin::Wrappable<ServiceWorkerContext>,
|
||||
public gin_helper::EventEmitterMixin<ServiceWorkerContext>,
|
||||
|
@ -32,14 +44,39 @@ class ServiceWorkerContext final
|
|||
ElectronBrowserContext* browser_context);
|
||||
|
||||
v8::Local<v8::Value> GetAllRunningWorkerInfo(v8::Isolate* isolate);
|
||||
v8::Local<v8::Value> GetWorkerInfoFromID(gin_helper::ErrorThrower thrower,
|
||||
int64_t version_id);
|
||||
v8::Local<v8::Value> GetInfoFromVersionID(gin_helper::ErrorThrower thrower,
|
||||
int64_t version_id);
|
||||
v8::Local<v8::Value> GetFromVersionID(gin_helper::ErrorThrower thrower,
|
||||
int64_t version_id);
|
||||
v8::Local<v8::Value> GetWorkerFromVersionID(v8::Isolate* isolate,
|
||||
int64_t version_id);
|
||||
gin::Handle<ServiceWorkerMain> GetWorkerFromVersionIDIfExists(
|
||||
v8::Isolate* isolate,
|
||||
int64_t version_id);
|
||||
v8::Local<v8::Promise> StartWorkerForScope(v8::Isolate* isolate, GURL scope);
|
||||
void DidStartWorkerForScope(
|
||||
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
|
||||
int64_t version_id,
|
||||
int process_id,
|
||||
int thread_id);
|
||||
void DidFailToStartWorkerForScope(
|
||||
std::shared_ptr<gin_helper::Promise<v8::Local<v8::Value>>> shared_promise,
|
||||
content::StatusCodeResponse status);
|
||||
void StopWorkersForScope(GURL scope);
|
||||
v8::Local<v8::Promise> StopAllWorkers(v8::Isolate* isolate);
|
||||
|
||||
// content::ServiceWorkerContextObserver
|
||||
void OnReportConsoleMessage(int64_t version_id,
|
||||
const GURL& scope,
|
||||
const content::ConsoleMessage& message) override;
|
||||
void OnRegistrationCompleted(const GURL& scope) override;
|
||||
void OnVersionStartingRunning(int64_t version_id) override;
|
||||
void OnVersionStartedRunning(
|
||||
int64_t version_id,
|
||||
const content::ServiceWorkerRunningInfo& running_info) override;
|
||||
void OnVersionStoppingRunning(int64_t version_id) override;
|
||||
void OnVersionStoppedRunning(int64_t version_id) override;
|
||||
void OnVersionRedundant(int64_t version_id, const GURL& scope) override;
|
||||
void OnDestruct(content::ServiceWorkerContext* context) override;
|
||||
|
||||
// gin::Wrappable
|
||||
|
@ -58,8 +95,15 @@ class ServiceWorkerContext final
|
|||
~ServiceWorkerContext() override;
|
||||
|
||||
private:
|
||||
void OnRunningStatusChanged(int64_t version_id,
|
||||
blink::EmbeddedWorkerStatus running_status);
|
||||
|
||||
raw_ptr<content::ServiceWorkerContext> service_worker_context_;
|
||||
|
||||
// Service worker registration and versions are unique to a storage partition.
|
||||
// Keep a reference to the storage partition to be used for lookups.
|
||||
raw_ptr<content::StoragePartition> storage_partition_;
|
||||
|
||||
base::WeakPtrFactory<ServiceWorkerContext> weak_ptr_factory_{this};
|
||||
};
|
||||
|
||||
|
|
359
shell/browser/api/electron_api_service_worker_main.cc
Normal file
359
shell/browser/api/electron_api_service_worker_main.cc
Normal file
|
@ -0,0 +1,359 @@
|
|||
// Copyright (c) 2025 Salesforce, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#include "shell/browser/api/electron_api_service_worker_main.h"
|
||||
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "base/logging.h"
|
||||
#include "base/no_destructor.h"
|
||||
#include "content/browser/service_worker/service_worker_context_wrapper.h" // nogncheck
|
||||
#include "content/browser/service_worker/service_worker_version.h" // nogncheck
|
||||
#include "electron/shell/common/api/api.mojom.h"
|
||||
#include "gin/handle.h"
|
||||
#include "gin/object_template_builder.h"
|
||||
#include "services/service_manager/public/cpp/interface_provider.h"
|
||||
#include "shell/browser/api/message_port.h"
|
||||
#include "shell/browser/browser.h"
|
||||
#include "shell/browser/javascript_environment.h"
|
||||
#include "shell/common/gin_converters/blink_converter.h"
|
||||
#include "shell/common/gin_converters/gurl_converter.h"
|
||||
#include "shell/common/gin_converters/value_converter.h"
|
||||
#include "shell/common/gin_helper/dictionary.h"
|
||||
#include "shell/common/gin_helper/error_thrower.h"
|
||||
#include "shell/common/gin_helper/object_template_builder.h"
|
||||
#include "shell/common/gin_helper/promise.h"
|
||||
#include "shell/common/node_includes.h"
|
||||
#include "shell/common/v8_util.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// Use private API to get the live version of the service worker. This will
|
||||
// exist while in starting, stopping, or stopped running status.
|
||||
content::ServiceWorkerVersion* GetLiveVersion(
|
||||
content::ServiceWorkerContext* service_worker_context,
|
||||
int64_t version_id) {
|
||||
auto* wrapper = static_cast<content::ServiceWorkerContextWrapper*>(
|
||||
service_worker_context);
|
||||
return wrapper->GetLiveVersion(version_id);
|
||||
}
|
||||
|
||||
// Get a public ServiceWorkerVersionBaseInfo object directly from the service
|
||||
// worker.
|
||||
std::optional<content::ServiceWorkerVersionBaseInfo> GetLiveVersionInfo(
|
||||
content::ServiceWorkerContext* service_worker_context,
|
||||
int64_t version_id) {
|
||||
auto* version = GetLiveVersion(service_worker_context, version_id);
|
||||
if (version) {
|
||||
return version->GetInfo();
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
namespace electron::api {
|
||||
|
||||
// ServiceWorkerKey -> ServiceWorkerMain*
|
||||
typedef std::unordered_map<ServiceWorkerKey,
|
||||
ServiceWorkerMain*,
|
||||
ServiceWorkerKey::Hasher>
|
||||
VersionIdMap;
|
||||
|
||||
VersionIdMap& GetVersionIdMap() {
|
||||
static base::NoDestructor<VersionIdMap> instance;
|
||||
return *instance;
|
||||
}
|
||||
|
||||
ServiceWorkerMain* FromServiceWorkerKey(const ServiceWorkerKey& key) {
|
||||
VersionIdMap& version_map = GetVersionIdMap();
|
||||
auto iter = version_map.find(key);
|
||||
auto* service_worker = iter == version_map.end() ? nullptr : iter->second;
|
||||
return service_worker;
|
||||
}
|
||||
|
||||
// static
|
||||
ServiceWorkerMain* ServiceWorkerMain::FromVersionID(
|
||||
int64_t version_id,
|
||||
const content::StoragePartition* storage_partition) {
|
||||
ServiceWorkerKey key(version_id, storage_partition);
|
||||
return FromServiceWorkerKey(key);
|
||||
}
|
||||
|
||||
gin::WrapperInfo ServiceWorkerMain::kWrapperInfo = {gin::kEmbedderNativeGin};
|
||||
|
||||
ServiceWorkerMain::ServiceWorkerMain(content::ServiceWorkerContext* sw_context,
|
||||
int64_t version_id,
|
||||
const ServiceWorkerKey& key)
|
||||
: version_id_(version_id), key_(key), service_worker_context_(sw_context) {
|
||||
GetVersionIdMap().emplace(key_, this);
|
||||
InvalidateVersionInfo();
|
||||
}
|
||||
|
||||
ServiceWorkerMain::~ServiceWorkerMain() {
|
||||
Destroy();
|
||||
}
|
||||
|
||||
void ServiceWorkerMain::Destroy() {
|
||||
version_destroyed_ = true;
|
||||
InvalidateVersionInfo();
|
||||
MaybeDisconnectRemote();
|
||||
GetVersionIdMap().erase(key_);
|
||||
Unpin();
|
||||
}
|
||||
|
||||
void ServiceWorkerMain::MaybeDisconnectRemote() {
|
||||
if (remote_.is_bound() &&
|
||||
(version_destroyed_ ||
|
||||
(!service_worker_context_->IsLiveStartingServiceWorker(version_id_) &&
|
||||
!service_worker_context_->IsLiveRunningServiceWorker(version_id_)))) {
|
||||
remote_.reset();
|
||||
}
|
||||
}
|
||||
|
||||
mojom::ElectronRenderer* ServiceWorkerMain::GetRendererApi() {
|
||||
if (!remote_.is_bound()) {
|
||||
if (!service_worker_context_->IsLiveRunningServiceWorker(version_id_)) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
service_worker_context_->GetRemoteAssociatedInterfaces(version_id_)
|
||||
.GetInterface(&remote_);
|
||||
}
|
||||
return remote_.get();
|
||||
}
|
||||
|
||||
void ServiceWorkerMain::Send(v8::Isolate* isolate,
|
||||
bool internal,
|
||||
const std::string& channel,
|
||||
v8::Local<v8::Value> args) {
|
||||
blink::CloneableMessage message;
|
||||
if (!gin::ConvertFromV8(isolate, args, &message)) {
|
||||
isolate->ThrowException(v8::Exception::Error(
|
||||
gin::StringToV8(isolate, "Failed to serialize arguments")));
|
||||
return;
|
||||
}
|
||||
|
||||
auto* renderer_api_remote = GetRendererApi();
|
||||
if (!renderer_api_remote) {
|
||||
return;
|
||||
}
|
||||
|
||||
renderer_api_remote->Message(internal, channel, std::move(message));
|
||||
}
|
||||
|
||||
void ServiceWorkerMain::InvalidateVersionInfo() {
|
||||
if (version_info_ != nullptr) {
|
||||
version_info_.reset();
|
||||
}
|
||||
|
||||
if (version_destroyed_)
|
||||
return;
|
||||
|
||||
auto version_info = GetLiveVersionInfo(service_worker_context_, version_id_);
|
||||
if (version_info) {
|
||||
version_info_ =
|
||||
std::make_unique<content::ServiceWorkerVersionBaseInfo>(*version_info);
|
||||
} else {
|
||||
// When ServiceWorkerContextCore::RemoveLiveVersion is called, it posts a
|
||||
// task to notify that the service worker has stopped. At this point, the
|
||||
// live version will no longer exist.
|
||||
Destroy();
|
||||
}
|
||||
}
|
||||
|
||||
void ServiceWorkerMain::OnRunningStatusChanged(
|
||||
blink::EmbeddedWorkerStatus running_status) {
|
||||
// Disconnect remote when content::ServiceWorkerHost has terminated.
|
||||
MaybeDisconnectRemote();
|
||||
|
||||
InvalidateVersionInfo();
|
||||
|
||||
// Redundant worker has been marked for deletion. Now that it's stopped, let's
|
||||
// destroy our wrapper.
|
||||
if (redundant_ && running_status == blink::EmbeddedWorkerStatus::kStopped) {
|
||||
Destroy();
|
||||
}
|
||||
}
|
||||
|
||||
void ServiceWorkerMain::OnVersionRedundant() {
|
||||
// Redundant service workers have been either unregistered or replaced. A new
|
||||
// ServiceWorkerMain will need to be created.
|
||||
// Set internal state to mark it for deletion once it has fully stopped.
|
||||
redundant_ = true;
|
||||
}
|
||||
|
||||
bool ServiceWorkerMain::IsDestroyed() const {
|
||||
return version_destroyed_;
|
||||
}
|
||||
|
||||
const blink::StorageKey ServiceWorkerMain::GetStorageKey() {
|
||||
GURL scope = version_info_ ? version_info()->scope : GURL::EmptyGURL();
|
||||
return blink::StorageKey::CreateFirstParty(url::Origin::Create(scope));
|
||||
}
|
||||
|
||||
gin_helper::Dictionary ServiceWorkerMain::StartExternalRequest(
|
||||
v8::Isolate* isolate,
|
||||
bool has_timeout) {
|
||||
auto details = gin_helper::Dictionary::CreateEmpty(isolate);
|
||||
|
||||
if (version_destroyed_) {
|
||||
isolate->ThrowException(v8::Exception::TypeError(
|
||||
gin::StringToV8(isolate, "ServiceWorkerMain is destroyed")));
|
||||
return details;
|
||||
}
|
||||
|
||||
auto request_uuid = base::Uuid::GenerateRandomV4();
|
||||
auto timeout_type =
|
||||
has_timeout
|
||||
? content::ServiceWorkerExternalRequestTimeoutType::kDefault
|
||||
: content::ServiceWorkerExternalRequestTimeoutType::kDoesNotTimeout;
|
||||
|
||||
content::ServiceWorkerExternalRequestResult start_result =
|
||||
service_worker_context_->StartingExternalRequest(
|
||||
version_id_, timeout_type, request_uuid);
|
||||
|
||||
details.Set("id", request_uuid.AsLowercaseString());
|
||||
details.Set("ok",
|
||||
start_result == content::ServiceWorkerExternalRequestResult::kOk);
|
||||
|
||||
return details;
|
||||
}
|
||||
|
||||
void ServiceWorkerMain::FinishExternalRequest(v8::Isolate* isolate,
|
||||
std::string uuid) {
|
||||
base::Uuid request_uuid = base::Uuid::ParseLowercase(uuid);
|
||||
if (!request_uuid.is_valid()) {
|
||||
isolate->ThrowException(v8::Exception::TypeError(
|
||||
gin::StringToV8(isolate, "Invalid external request UUID")));
|
||||
return;
|
||||
}
|
||||
|
||||
DCHECK(service_worker_context_);
|
||||
if (!service_worker_context_)
|
||||
return;
|
||||
|
||||
content::ServiceWorkerExternalRequestResult result =
|
||||
service_worker_context_->FinishedExternalRequest(version_id_,
|
||||
request_uuid);
|
||||
|
||||
std::string error;
|
||||
switch (result) {
|
||||
case content::ServiceWorkerExternalRequestResult::kOk:
|
||||
break;
|
||||
case content::ServiceWorkerExternalRequestResult::kBadRequestId:
|
||||
error = "Unknown external request UUID";
|
||||
break;
|
||||
case content::ServiceWorkerExternalRequestResult::kWorkerNotRunning:
|
||||
error = "Service worker is no longer running";
|
||||
break;
|
||||
case content::ServiceWorkerExternalRequestResult::kWorkerNotFound:
|
||||
error = "Service worker was not found";
|
||||
break;
|
||||
case content::ServiceWorkerExternalRequestResult::kNullContext:
|
||||
default:
|
||||
error = "Service worker context is unavailable and may be shutting down";
|
||||
break;
|
||||
}
|
||||
|
||||
if (!error.empty()) {
|
||||
isolate->ThrowException(
|
||||
v8::Exception::TypeError(gin::StringToV8(isolate, error)));
|
||||
}
|
||||
}
|
||||
|
||||
size_t ServiceWorkerMain::CountExternalRequestsForTest() {
|
||||
if (version_destroyed_)
|
||||
return 0;
|
||||
auto& storage_key = GetStorageKey();
|
||||
return service_worker_context_->CountExternalRequestsForTest(storage_key);
|
||||
}
|
||||
|
||||
int64_t ServiceWorkerMain::VersionID() const {
|
||||
return version_id_;
|
||||
}
|
||||
|
||||
GURL ServiceWorkerMain::ScopeURL() const {
|
||||
if (version_destroyed_)
|
||||
return GURL::EmptyGURL();
|
||||
return version_info()->scope;
|
||||
}
|
||||
|
||||
// static
|
||||
gin::Handle<ServiceWorkerMain> ServiceWorkerMain::New(v8::Isolate* isolate) {
|
||||
return gin::Handle<ServiceWorkerMain>();
|
||||
}
|
||||
|
||||
// static
|
||||
gin::Handle<ServiceWorkerMain> ServiceWorkerMain::From(
|
||||
v8::Isolate* isolate,
|
||||
content::ServiceWorkerContext* sw_context,
|
||||
const content::StoragePartition* storage_partition,
|
||||
int64_t version_id) {
|
||||
ServiceWorkerKey service_worker_key(version_id, storage_partition);
|
||||
|
||||
auto* service_worker = FromServiceWorkerKey(service_worker_key);
|
||||
if (service_worker)
|
||||
return gin::CreateHandle(isolate, service_worker);
|
||||
|
||||
// Ensure ServiceWorkerVersion exists and is not redundant (pending deletion)
|
||||
auto* live_version = GetLiveVersion(sw_context, version_id);
|
||||
if (!live_version || live_version->is_redundant()) {
|
||||
return gin::Handle<ServiceWorkerMain>();
|
||||
}
|
||||
|
||||
auto handle = gin::CreateHandle(
|
||||
isolate,
|
||||
new ServiceWorkerMain(sw_context, version_id, service_worker_key));
|
||||
|
||||
// Prevent garbage collection of worker until it has been deleted internally.
|
||||
handle->Pin(isolate);
|
||||
|
||||
return handle;
|
||||
}
|
||||
|
||||
// static
|
||||
void ServiceWorkerMain::FillObjectTemplate(
|
||||
v8::Isolate* isolate,
|
||||
v8::Local<v8::ObjectTemplate> templ) {
|
||||
gin_helper::ObjectTemplateBuilder(isolate, templ)
|
||||
.SetMethod("_send", &ServiceWorkerMain::Send)
|
||||
.SetMethod("isDestroyed", &ServiceWorkerMain::IsDestroyed)
|
||||
.SetMethod("_startExternalRequest",
|
||||
&ServiceWorkerMain::StartExternalRequest)
|
||||
.SetMethod("_finishExternalRequest",
|
||||
&ServiceWorkerMain::FinishExternalRequest)
|
||||
.SetMethod("_countExternalRequests",
|
||||
&ServiceWorkerMain::CountExternalRequestsForTest)
|
||||
.SetProperty("versionId", &ServiceWorkerMain::VersionID)
|
||||
.SetProperty("scope", &ServiceWorkerMain::ScopeURL)
|
||||
.Build();
|
||||
}
|
||||
|
||||
const char* ServiceWorkerMain::GetTypeName() {
|
||||
return GetClassName();
|
||||
}
|
||||
|
||||
} // namespace electron::api
|
||||
|
||||
namespace {
|
||||
|
||||
using electron::api::ServiceWorkerMain;
|
||||
|
||||
void Initialize(v8::Local<v8::Object> exports,
|
||||
v8::Local<v8::Value> unused,
|
||||
v8::Local<v8::Context> context,
|
||||
void* priv) {
|
||||
v8::Isolate* isolate = context->GetIsolate();
|
||||
gin_helper::Dictionary dict(isolate, exports);
|
||||
dict.Set("ServiceWorkerMain", ServiceWorkerMain::GetConstructor(context));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_service_worker_main,
|
||||
Initialize)
|
178
shell/browser/api/electron_api_service_worker_main.h
Normal file
178
shell/browser/api/electron_api_service_worker_main.h
Normal file
|
@ -0,0 +1,178 @@
|
|||
// Copyright (c) 2025 Salesforce, Inc.
|
||||
// Use of this source code is governed by the MIT license that can be
|
||||
// found in the LICENSE file.
|
||||
|
||||
#ifndef ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SERVICE_WORKER_MAIN_H_
|
||||
#define ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SERVICE_WORKER_MAIN_H_
|
||||
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "base/memory/raw_ptr.h"
|
||||
#include "base/memory/weak_ptr.h"
|
||||
#include "base/process/process.h"
|
||||
#include "content/public/browser/global_routing_id.h"
|
||||
#include "content/public/browser/service_worker_context.h"
|
||||
#include "content/public/browser/service_worker_version_base_info.h"
|
||||
#include "gin/wrappable.h"
|
||||
#include "mojo/public/cpp/bindings/associated_receiver.h"
|
||||
#include "mojo/public/cpp/bindings/associated_remote.h"
|
||||
#include "mojo/public/cpp/bindings/pending_receiver.h"
|
||||
#include "mojo/public/cpp/bindings/remote.h"
|
||||
#include "shell/browser/event_emitter_mixin.h"
|
||||
#include "shell/common/api/api.mojom.h"
|
||||
#include "shell/common/gin_helper/constructible.h"
|
||||
#include "shell/common/gin_helper/pinnable.h"
|
||||
#include "third_party/blink/public/common/service_worker/embedded_worker_status.h"
|
||||
|
||||
class GURL;
|
||||
|
||||
namespace content {
|
||||
class StoragePartition;
|
||||
}
|
||||
|
||||
namespace gin {
|
||||
class Arguments;
|
||||
} // namespace gin
|
||||
|
||||
namespace gin_helper {
|
||||
class Dictionary;
|
||||
template <typename T>
|
||||
class Handle;
|
||||
template <typename T>
|
||||
class Promise;
|
||||
} // namespace gin_helper
|
||||
|
||||
namespace electron::api {
|
||||
|
||||
// Key to uniquely identify a ServiceWorkerMain by its Version ID within the
|
||||
// associated StoragePartition.
|
||||
struct ServiceWorkerKey {
|
||||
int64_t version_id;
|
||||
raw_ptr<const content::StoragePartition> storage_partition;
|
||||
|
||||
ServiceWorkerKey(int64_t id, const content::StoragePartition* partition)
|
||||
: version_id(id), storage_partition(partition) {}
|
||||
|
||||
bool operator<(const ServiceWorkerKey& other) const {
|
||||
return std::tie(version_id, storage_partition) <
|
||||
std::tie(other.version_id, other.storage_partition);
|
||||
}
|
||||
|
||||
bool operator==(const ServiceWorkerKey& other) const {
|
||||
return version_id == other.version_id &&
|
||||
storage_partition == other.storage_partition;
|
||||
}
|
||||
|
||||
struct Hasher {
|
||||
std::size_t operator()(const ServiceWorkerKey& key) const {
|
||||
return std::hash<const content::StoragePartition*>()(
|
||||
key.storage_partition) ^
|
||||
std::hash<int64_t>()(key.version_id);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
// Creates a wrapper to align with the lifecycle of the non-public
|
||||
// content::ServiceWorkerVersion. Object instances are pinned for the lifetime
|
||||
// of the underlying SW such that registered IPC handlers continue to dispatch.
|
||||
//
|
||||
// Instances are uniquely identified by pairing their version ID and the
|
||||
// StoragePartition in which they're registered. In Electron, this is always
|
||||
// the default StoragePartition for the associated BrowserContext.
|
||||
class ServiceWorkerMain final
|
||||
: public gin::Wrappable<ServiceWorkerMain>,
|
||||
public gin_helper::EventEmitterMixin<ServiceWorkerMain>,
|
||||
public gin_helper::Pinnable<ServiceWorkerMain>,
|
||||
public gin_helper::Constructible<ServiceWorkerMain> {
|
||||
public:
|
||||
// Create a new ServiceWorkerMain and return the V8 wrapper of it.
|
||||
static gin::Handle<ServiceWorkerMain> New(v8::Isolate* isolate);
|
||||
|
||||
static gin::Handle<ServiceWorkerMain> From(
|
||||
v8::Isolate* isolate,
|
||||
content::ServiceWorkerContext* sw_context,
|
||||
const content::StoragePartition* storage_partition,
|
||||
int64_t version_id);
|
||||
static ServiceWorkerMain* FromVersionID(
|
||||
int64_t version_id,
|
||||
const content::StoragePartition* storage_partition);
|
||||
|
||||
// gin_helper::Constructible
|
||||
static void FillObjectTemplate(v8::Isolate*, v8::Local<v8::ObjectTemplate>);
|
||||
static const char* GetClassName() { return "ServiceWorkerMain"; }
|
||||
|
||||
// gin::Wrappable
|
||||
static gin::WrapperInfo kWrapperInfo;
|
||||
const char* GetTypeName() override;
|
||||
|
||||
// disable copy
|
||||
ServiceWorkerMain(const ServiceWorkerMain&) = delete;
|
||||
ServiceWorkerMain& operator=(const ServiceWorkerMain&) = delete;
|
||||
|
||||
void OnRunningStatusChanged(blink::EmbeddedWorkerStatus running_status);
|
||||
void OnVersionRedundant();
|
||||
|
||||
protected:
|
||||
explicit ServiceWorkerMain(content::ServiceWorkerContext* sw_context,
|
||||
int64_t version_id,
|
||||
const ServiceWorkerKey& key);
|
||||
~ServiceWorkerMain() override;
|
||||
|
||||
private:
|
||||
void Destroy();
|
||||
void MaybeDisconnectRemote();
|
||||
const blink::StorageKey GetStorageKey();
|
||||
|
||||
// Increments external requests for the service worker to keep it alive.
|
||||
gin_helper::Dictionary StartExternalRequest(v8::Isolate* isolate,
|
||||
bool has_timeout);
|
||||
void FinishExternalRequest(v8::Isolate* isolate, std::string uuid);
|
||||
size_t CountExternalRequestsForTest();
|
||||
|
||||
// Get or create a Mojo connection to the renderer process.
|
||||
mojom::ElectronRenderer* GetRendererApi();
|
||||
|
||||
// Send a message to the renderer process.
|
||||
void Send(v8::Isolate* isolate,
|
||||
bool internal,
|
||||
const std::string& channel,
|
||||
v8::Local<v8::Value> args);
|
||||
|
||||
void InvalidateVersionInfo();
|
||||
const content::ServiceWorkerVersionBaseInfo* version_info() const {
|
||||
return version_info_.get();
|
||||
}
|
||||
|
||||
bool IsDestroyed() const;
|
||||
|
||||
int64_t VersionID() const;
|
||||
GURL ScopeURL() const;
|
||||
|
||||
// Version ID unique only to the StoragePartition.
|
||||
int64_t version_id_;
|
||||
|
||||
// Unique identifier pairing the Version ID and StoragePartition.
|
||||
ServiceWorkerKey key_;
|
||||
|
||||
// Whether the Service Worker version has been destroyed.
|
||||
bool version_destroyed_ = false;
|
||||
|
||||
// Whether the Service Worker version's state is redundant.
|
||||
bool redundant_ = false;
|
||||
|
||||
// Store copy of version info so it's accessible when not running.
|
||||
std::unique_ptr<content::ServiceWorkerVersionBaseInfo> version_info_;
|
||||
|
||||
raw_ptr<content::ServiceWorkerContext> service_worker_context_;
|
||||
mojo::AssociatedRemote<mojom::ElectronRenderer> remote_;
|
||||
|
||||
std::unique_ptr<gin_helper::Promise<void>> start_worker_promise_;
|
||||
|
||||
base::WeakPtrFactory<ServiceWorkerMain> weak_factory_{this};
|
||||
};
|
||||
|
||||
} // namespace electron::api
|
||||
|
||||
#endif // ELECTRON_SHELL_BROWSER_API_ELECTRON_API_SERVICE_WORKER_MAIN_H_
|
Loading…
Add table
Add a link
Reference in a new issue