electron_api_service_worker_main.cc 11 KB

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