electron_api_service_worker_main.cc 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // Copyright (c) 2025 Salesforce, Inc.
  2. // Use of this source code is governed by the MIT license that can be
  3. // found in the LICENSE file.
  4. #include "shell/browser/api/electron_api_service_worker_main.h"
  5. #include <string>
  6. #include <unordered_map>
  7. #include <utility>
  8. #include "base/logging.h"
  9. #include "base/no_destructor.h"
  10. #include "content/browser/service_worker/service_worker_context_wrapper.h" // nogncheck
  11. #include "content/browser/service_worker/service_worker_version.h" // nogncheck
  12. #include "gin/handle.h"
  13. #include "gin/object_template_builder.h"
  14. #include "services/service_manager/public/cpp/interface_provider.h"
  15. #include "shell/browser/api/message_port.h"
  16. #include "shell/browser/browser.h"
  17. #include "shell/browser/javascript_environment.h"
  18. #include "shell/common/api/api.mojom.h"
  19. #include "shell/common/gin_converters/blink_converter.h"
  20. #include "shell/common/gin_converters/gurl_converter.h"
  21. #include "shell/common/gin_converters/value_converter.h"
  22. #include "shell/common/gin_helper/dictionary.h"
  23. #include "shell/common/gin_helper/error_thrower.h"
  24. #include "shell/common/gin_helper/object_template_builder.h"
  25. #include "shell/common/gin_helper/promise.h"
  26. #include "shell/common/node_includes.h"
  27. #include "shell/common/v8_util.h"
  28. namespace {
  29. // Use private API to get the live version of the service worker. This will
  30. // exist while in starting, stopping, or stopped running status.
  31. content::ServiceWorkerVersion* GetLiveVersion(
  32. content::ServiceWorkerContext* service_worker_context,
  33. int64_t version_id) {
  34. auto* wrapper = static_cast<content::ServiceWorkerContextWrapper*>(
  35. service_worker_context);
  36. return wrapper->GetLiveVersion(version_id);
  37. }
  38. // Get a public ServiceWorkerVersionBaseInfo object directly from the service
  39. // worker.
  40. std::optional<content::ServiceWorkerVersionBaseInfo> GetLiveVersionInfo(
  41. content::ServiceWorkerContext* service_worker_context,
  42. int64_t version_id) {
  43. auto* version = GetLiveVersion(service_worker_context, version_id);
  44. if (version) {
  45. return version->GetInfo();
  46. }
  47. return std::nullopt;
  48. }
  49. } // namespace
  50. namespace electron::api {
  51. // ServiceWorkerKey -> ServiceWorkerMain*
  52. typedef std::unordered_map<ServiceWorkerKey,
  53. ServiceWorkerMain*,
  54. ServiceWorkerKey::Hasher>
  55. VersionIdMap;
  56. VersionIdMap& GetVersionIdMap() {
  57. static base::NoDestructor<VersionIdMap> instance;
  58. return *instance;
  59. }
  60. ServiceWorkerMain* FromServiceWorkerKey(const ServiceWorkerKey& key) {
  61. VersionIdMap& version_map = GetVersionIdMap();
  62. auto iter = version_map.find(key);
  63. auto* service_worker = iter == version_map.end() ? nullptr : iter->second;
  64. return service_worker;
  65. }
  66. // static
  67. ServiceWorkerMain* ServiceWorkerMain::FromVersionID(
  68. int64_t version_id,
  69. const content::StoragePartition* storage_partition) {
  70. ServiceWorkerKey key(version_id, storage_partition);
  71. return FromServiceWorkerKey(key);
  72. }
  73. gin::WrapperInfo ServiceWorkerMain::kWrapperInfo = {gin::kEmbedderNativeGin};
  74. ServiceWorkerMain::ServiceWorkerMain(content::ServiceWorkerContext* sw_context,
  75. int64_t version_id,
  76. const ServiceWorkerKey& key)
  77. : version_id_(version_id), key_(key), service_worker_context_(sw_context) {
  78. GetVersionIdMap().emplace(key_, this);
  79. InvalidateVersionInfo();
  80. }
  81. ServiceWorkerMain::~ServiceWorkerMain() {
  82. Destroy();
  83. }
  84. void ServiceWorkerMain::Destroy() {
  85. version_destroyed_ = true;
  86. InvalidateVersionInfo();
  87. MaybeDisconnectRemote();
  88. GetVersionIdMap().erase(key_);
  89. Unpin();
  90. }
  91. void ServiceWorkerMain::MaybeDisconnectRemote() {
  92. if (remote_.is_bound() &&
  93. (version_destroyed_ ||
  94. (!service_worker_context_->IsLiveStartingServiceWorker(version_id_) &&
  95. !service_worker_context_->IsLiveRunningServiceWorker(version_id_)))) {
  96. remote_.reset();
  97. }
  98. }
  99. mojom::ElectronRenderer* ServiceWorkerMain::GetRendererApi() {
  100. if (!remote_.is_bound()) {
  101. if (!service_worker_context_->IsLiveRunningServiceWorker(version_id_)) {
  102. return nullptr;
  103. }
  104. service_worker_context_->GetRemoteAssociatedInterfaces(version_id_)
  105. .GetInterface(&remote_);
  106. }
  107. return remote_.get();
  108. }
  109. void ServiceWorkerMain::Send(v8::Isolate* isolate,
  110. bool internal,
  111. const std::string& channel,
  112. v8::Local<v8::Value> args) {
  113. blink::CloneableMessage message;
  114. if (!gin::ConvertFromV8(isolate, args, &message)) {
  115. isolate->ThrowException(v8::Exception::Error(
  116. gin::StringToV8(isolate, "Failed to serialize arguments")));
  117. return;
  118. }
  119. auto* renderer_api_remote = GetRendererApi();
  120. if (!renderer_api_remote) {
  121. return;
  122. }
  123. renderer_api_remote->Message(internal, channel, std::move(message));
  124. }
  125. void ServiceWorkerMain::InvalidateVersionInfo() {
  126. if (version_info_ != nullptr) {
  127. version_info_.reset();
  128. }
  129. if (version_destroyed_)
  130. return;
  131. auto version_info = GetLiveVersionInfo(service_worker_context_, version_id_);
  132. if (version_info) {
  133. version_info_ =
  134. std::make_unique<content::ServiceWorkerVersionBaseInfo>(*version_info);
  135. } else {
  136. // When ServiceWorkerContextCore::RemoveLiveVersion is called, it posts a
  137. // task to notify that the service worker has stopped. At this point, the
  138. // live version will no longer exist.
  139. Destroy();
  140. }
  141. }
  142. void ServiceWorkerMain::OnRunningStatusChanged(
  143. blink::EmbeddedWorkerStatus running_status) {
  144. // Disconnect remote when content::ServiceWorkerHost has terminated.
  145. MaybeDisconnectRemote();
  146. InvalidateVersionInfo();
  147. // Redundant worker has been marked for deletion. Now that it's stopped, let's
  148. // destroy our wrapper.
  149. if (redundant_ && running_status == blink::EmbeddedWorkerStatus::kStopped) {
  150. Destroy();
  151. }
  152. }
  153. void ServiceWorkerMain::OnVersionRedundant() {
  154. // Redundant service workers have been either unregistered or replaced. A new
  155. // ServiceWorkerMain will need to be created.
  156. // Set internal state to mark it for deletion once it has fully stopped.
  157. redundant_ = true;
  158. }
  159. bool ServiceWorkerMain::IsDestroyed() const {
  160. return version_destroyed_;
  161. }
  162. const blink::StorageKey ServiceWorkerMain::GetStorageKey() {
  163. const GURL& scope = version_info_ ? version_info()->scope : GURL::EmptyGURL();
  164. return blink::StorageKey::CreateFirstParty(url::Origin::Create(scope));
  165. }
  166. gin_helper::Dictionary ServiceWorkerMain::StartExternalRequest(
  167. v8::Isolate* isolate,
  168. bool has_timeout) {
  169. auto details = gin_helper::Dictionary::CreateEmpty(isolate);
  170. if (version_destroyed_) {
  171. isolate->ThrowException(v8::Exception::TypeError(
  172. gin::StringToV8(isolate, "ServiceWorkerMain is destroyed")));
  173. return details;
  174. }
  175. auto request_uuid = base::Uuid::GenerateRandomV4();
  176. auto timeout_type =
  177. has_timeout
  178. ? content::ServiceWorkerExternalRequestTimeoutType::kDefault
  179. : content::ServiceWorkerExternalRequestTimeoutType::kDoesNotTimeout;
  180. content::ServiceWorkerExternalRequestResult start_result =
  181. service_worker_context_->StartingExternalRequest(
  182. version_id_, timeout_type, request_uuid);
  183. details.Set("id", request_uuid.AsLowercaseString());
  184. details.Set("ok",
  185. start_result == content::ServiceWorkerExternalRequestResult::kOk);
  186. return details;
  187. }
  188. void ServiceWorkerMain::FinishExternalRequest(v8::Isolate* isolate,
  189. std::string uuid) {
  190. base::Uuid request_uuid = base::Uuid::ParseLowercase(uuid);
  191. if (!request_uuid.is_valid()) {
  192. isolate->ThrowException(v8::Exception::TypeError(
  193. gin::StringToV8(isolate, "Invalid external request UUID")));
  194. return;
  195. }
  196. DCHECK(service_worker_context_);
  197. if (!service_worker_context_)
  198. return;
  199. content::ServiceWorkerExternalRequestResult result =
  200. service_worker_context_->FinishedExternalRequest(version_id_,
  201. request_uuid);
  202. std::string error;
  203. switch (result) {
  204. case content::ServiceWorkerExternalRequestResult::kOk:
  205. break;
  206. case content::ServiceWorkerExternalRequestResult::kBadRequestId:
  207. error = "Unknown external request UUID";
  208. break;
  209. case content::ServiceWorkerExternalRequestResult::kWorkerNotRunning:
  210. error = "Service worker is no longer running";
  211. break;
  212. case content::ServiceWorkerExternalRequestResult::kWorkerNotFound:
  213. error = "Service worker was not found";
  214. break;
  215. case content::ServiceWorkerExternalRequestResult::kNullContext:
  216. default:
  217. error = "Service worker context is unavailable and may be shutting down";
  218. break;
  219. }
  220. if (!error.empty()) {
  221. isolate->ThrowException(
  222. v8::Exception::TypeError(gin::StringToV8(isolate, error)));
  223. }
  224. }
  225. size_t ServiceWorkerMain::CountExternalRequestsForTest() {
  226. if (version_destroyed_)
  227. return 0;
  228. auto& storage_key = GetStorageKey();
  229. return service_worker_context_->CountExternalRequestsForTest(storage_key);
  230. }
  231. int64_t ServiceWorkerMain::VersionID() const {
  232. return version_id_;
  233. }
  234. GURL ServiceWorkerMain::ScopeURL() const {
  235. if (version_destroyed_)
  236. return {};
  237. return version_info()->scope;
  238. }
  239. // static
  240. gin::Handle<ServiceWorkerMain> ServiceWorkerMain::New(v8::Isolate* isolate) {
  241. return gin::Handle<ServiceWorkerMain>();
  242. }
  243. // static
  244. gin::Handle<ServiceWorkerMain> ServiceWorkerMain::From(
  245. v8::Isolate* isolate,
  246. content::ServiceWorkerContext* sw_context,
  247. const content::StoragePartition* storage_partition,
  248. int64_t version_id) {
  249. ServiceWorkerKey service_worker_key(version_id, storage_partition);
  250. auto* service_worker = FromServiceWorkerKey(service_worker_key);
  251. if (service_worker)
  252. return gin::CreateHandle(isolate, service_worker);
  253. // Ensure ServiceWorkerVersion exists and is not redundant (pending deletion)
  254. auto* live_version = GetLiveVersion(sw_context, version_id);
  255. if (!live_version || live_version->is_redundant()) {
  256. return gin::Handle<ServiceWorkerMain>();
  257. }
  258. auto handle = gin::CreateHandle(
  259. isolate,
  260. new ServiceWorkerMain(sw_context, version_id, service_worker_key));
  261. // Prevent garbage collection of worker until it has been deleted internally.
  262. handle->Pin(isolate);
  263. return handle;
  264. }
  265. // static
  266. void ServiceWorkerMain::FillObjectTemplate(
  267. v8::Isolate* isolate,
  268. v8::Local<v8::ObjectTemplate> templ) {
  269. gin_helper::ObjectTemplateBuilder(isolate, templ)
  270. .SetMethod("_send", &ServiceWorkerMain::Send)
  271. .SetMethod("isDestroyed", &ServiceWorkerMain::IsDestroyed)
  272. .SetMethod("_startExternalRequest",
  273. &ServiceWorkerMain::StartExternalRequest)
  274. .SetMethod("_finishExternalRequest",
  275. &ServiceWorkerMain::FinishExternalRequest)
  276. .SetMethod("_countExternalRequests",
  277. &ServiceWorkerMain::CountExternalRequestsForTest)
  278. .SetProperty("versionId", &ServiceWorkerMain::VersionID)
  279. .SetProperty("scope", &ServiceWorkerMain::ScopeURL)
  280. .Build();
  281. }
  282. const char* ServiceWorkerMain::GetTypeName() {
  283. return GetClassName();
  284. }
  285. } // namespace electron::api
  286. namespace {
  287. using electron::api::ServiceWorkerMain;
  288. void Initialize(v8::Local<v8::Object> exports,
  289. v8::Local<v8::Value> unused,
  290. v8::Local<v8::Context> context,
  291. void* priv) {
  292. v8::Isolate* isolate = context->GetIsolate();
  293. gin_helper::Dictionary dict(isolate, exports);
  294. dict.Set("ServiceWorkerMain", ServiceWorkerMain::GetConstructor(context));
  295. }
  296. } // namespace
  297. NODE_LINKED_BINDING_CONTEXT_AWARE(electron_browser_service_worker_main,
  298. Initialize)