summaryrefslogtreecommitdiffstats
path: root/dom/workers/ScriptLoader.h
blob: 010f3d831657878e9c6b28525a8ce7289a116a63 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

#ifndef mozilla_dom_workers_scriptloader_h__
#define mozilla_dom_workers_scriptloader_h__

#include "js/loader/ScriptLoadRequest.h"
#include "js/loader/ModuleLoadRequest.h"
#include "js/loader/ModuleLoaderBase.h"
#include "mozilla/dom/WorkerBinding.h"
#include "mozilla/dom/WorkerCommon.h"
#include "mozilla/dom/WorkerLoadContext.h"
#include "mozilla/dom/WorkerRef.h"
#include "mozilla/dom/workerinternals/WorkerModuleLoader.h"
#include "mozilla/Maybe.h"
#include "nsIContentPolicy.h"
#include "nsStringFwd.h"
#include "nsTArrayForwardDeclare.h"

class nsIChannel;
class nsICookieJarSettings;
class nsILoadGroup;
class nsIPrincipal;
class nsIReferrerInfo;
class nsIURI;

namespace mozilla {

class ErrorResult;

namespace dom {

class ClientInfo;
class Document;
struct WorkerLoadInfo;
class WorkerPrivate;
class SerializedStackHolder;

enum WorkerScriptType { WorkerScript, DebuggerScript };

namespace workerinternals {

namespace loader {
class ScriptExecutorRunnable;
class ScriptLoaderRunnable;
class CachePromiseHandler;
class CacheLoadHandler;
class CacheCreator;
class NetworkLoadHandler;

/*
 * [DOMDOC] WorkerScriptLoader
 *
 * The WorkerScriptLoader is the primary class responsible for loading all
 * Workers, including: ServiceWorkers, SharedWorkers, RemoteWorkers, and
 * dedicated Workers. Our implementation also includes a subtype of dedicated
 * workers: ChromeWorker, which exposes information that isn't normally
 * accessible on a dedicated worker. See [1] for more information.
 *
 * Due to constraints around fetching, this class currently delegates the
 * "Fetch" portion of its work load to the main thread. Unlike the DOM
 * ScriptLoader, the WorkerScriptLoader is not persistent and is not reused for
 * subsequent loads. That means for each iteration of loading (for example,
 * loading the main script, followed by a load triggered by ImportScripts), we
 * recreate this class, and handle the case independently.
 *
 * The flow of requests across the boundaries looks like this:
 *
 *    +----------------------------+
 *    | new WorkerScriptLoader(..) |
 *    +----------------------------+
 *                   |
 *                   V
 *            +-------------------------------------------+
 *            | WorkerScriptLoader::DispatchLoadScripts() |
 *            +-------------------------------------------+
 *                   |
 *                   V
 *            +............................+
 *            | new ScriptLoaderRunnable() |
 *            +............................+
 *                   :
 *                   V
 *  #####################################################################
 *                             Enter Main thread
 *  #####################################################################
 *                   :
 *                   V
 *  +.............................+     For each: Is a normal Worker?
 *  | ScriptLoaderRunnable::Run() |----------------------------------+
 *  +.............................+                                  |
 *                   |                                               V
 *                   |               +----------------------------------+
 *                   |               | WorkerScriptLoader::LoadScript() |
 *                   |               +----------------------------------+
 *                   |                                               |
 *                   | For each request: Is a ServiceWorker?         |
 *                   |                                               |
 *                   V                                               V
 *   +==================+   No script in cache?   +====================+
 *   | CacheLoadHandler |------------------------>| NetworkLoadHandler |
 *   +==================+                         +====================+
 *      :                                                    :
 *      : Loaded from Cache                                  : Loaded by Network
 *      :   +..........................................+     :
 *      +---| ScriptLoaderRunnable::OnStreamComplete() |<----+
 *          +..........................................+
 *                             |
 *                             | A request is ready, is it in post order?
 *                             |
 *                             | call DispatchPendingProcessRequests()
 *                             | This creates ScriptExecutorRunnable
 *            +..............................+
 *            | new ScriptLoaderExecutable() |
 *            +..............................+
 *                             :
 *                             V
 *  #####################################################################
 *                           Enter worker thread
 *  #####################################################################
 *                             :
 *                             V
 *          +...............................+         All Scripts Executed?
 *          | ScriptLoaderExecutable::Run() | -------------+
 *          +...............................+              :
 *                                                         :
 *                                                         : yes. Do execution
 *                                                         : then shutdown.
 *                                                         :
 *                                                         V
 *                       +--------------------------------------------+
 *                       | WorkerScriptLoader::ShutdownScriptLoader() |
 *                       +--------------------------------------------+
 */

class WorkerScriptLoader : public JS::loader::ScriptLoaderInterface,
                           public nsINamed {
  friend class ScriptExecutorRunnable;
  friend class ScriptLoaderRunnable;
  friend class CachePromiseHandler;
  friend class CacheLoadHandler;
  friend class CacheCreator;
  friend class NetworkLoadHandler;
  friend class WorkerModuleLoader;

  RefPtr<ThreadSafeWorkerRef> mWorkerRef;
  UniquePtr<SerializedStackHolder> mOriginStack;
  nsString mOriginStackJSON;
  nsCOMPtr<nsISerialEventTarget> mSyncLoopTarget;
  ScriptLoadRequestList mLoadingRequests;
  ScriptLoadRequestList mLoadedRequests;
  Maybe<ServiceWorkerDescriptor> mController;
  WorkerScriptType mWorkerScriptType;
  ErrorResult& mRv;
  bool mExecutionAborted = false;
  bool mMutedErrorFlag = false;

  // Count of loading module requests. mLoadingRequests doesn't keep track of
  // child module requests.
  // This member should be accessed on worker thread.
  uint32_t mLoadingModuleRequestCount;

  // Worker cancellation related Mutex
  //
  // Modified on the worker thread.
  // It is ok to *read* this without a lock on the worker.
  // Main thread must always acquire a lock.
  bool mCleanedUp MOZ_GUARDED_BY(
      mCleanUpLock);  // To specify if the cleanUp() has been done.

  Mutex& CleanUpLock() MOZ_RETURN_CAPABILITY(mCleanUpLock) {
    return mCleanUpLock;
  }

  bool CleanedUp() const MOZ_REQUIRES(mCleanUpLock) {
    mCleanUpLock.AssertCurrentThreadOwns();
    return mCleanedUp;
  }

  // Ensure the worker and the main thread won't race to access |mCleanedUp|.
  // Should be a MutexSingleWriter, but that causes a lot of issues when you
  // expose the lock via Lock().
  Mutex mCleanUpLock;

 public:
  NS_DECL_THREADSAFE_ISUPPORTS

  static already_AddRefed<WorkerScriptLoader> Create(
      WorkerPrivate* aWorkerPrivate,
      UniquePtr<SerializedStackHolder> aOriginStack,
      nsISerialEventTarget* aSyncLoopTarget, WorkerScriptType aWorkerScriptType,
      ErrorResult& aRv);

  bool CreateScriptRequests(const nsTArray<nsString>& aScriptURLs,
                            const mozilla::Encoding* aDocumentEncoding,
                            bool aIsMainScript);

  ScriptLoadRequest* GetMainScript();

  already_AddRefed<ScriptLoadRequest> CreateScriptLoadRequest(
      const nsString& aScriptURL, const mozilla::Encoding* aDocumentEncoding,
      bool aIsMainScript);

  bool DispatchLoadScript(ScriptLoadRequest* aRequest);

  bool DispatchLoadScripts();

  void TryShutdown();

  WorkerScriptType GetWorkerScriptType() { return mWorkerScriptType; }

 protected:
  nsIURI* GetBaseURI() const override;

  nsIURI* GetInitialBaseURI();

  nsIGlobalObject* GetGlobal();

  void MaybeMoveToLoadedList(ScriptLoadRequest* aRequest);

  bool StoreCSP();

  bool ProcessPendingRequests(JSContext* aCx);

  bool AllScriptsExecuted() {
    return mLoadingRequests.isEmpty() && mLoadedRequests.isEmpty();
  }

  bool IsDebuggerScript() const { return mWorkerScriptType == DebuggerScript; }

  void SetController(const Maybe<ServiceWorkerDescriptor>& aDescriptor) {
    mController = aDescriptor;
  }

  Maybe<ServiceWorkerDescriptor>& GetController() { return mController; }

  nsresult LoadScript(ThreadSafeRequestHandle* aRequestHandle);

  void ShutdownScriptLoader(bool aResult, bool aMutedError);

 private:
  WorkerScriptLoader(UniquePtr<SerializedStackHolder> aOriginStack,
                     nsISerialEventTarget* aSyncLoopTarget,
                     WorkerScriptType aWorkerScriptType, ErrorResult& aRv);

  ~WorkerScriptLoader() = default;

  NS_IMETHOD
  GetName(nsACString& aName) override {
    aName.AssignLiteral("WorkerScriptLoader");
    return NS_OK;
  }

  void InitModuleLoader();

  nsTArray<RefPtr<ThreadSafeRequestHandle>> GetLoadingList();

  bool IsDynamicImport(ScriptLoadRequest* aRequest);

  nsContentPolicyType GetContentPolicyType(ScriptLoadRequest* aRequest);

  bool EvaluateScript(JSContext* aCx, ScriptLoadRequest* aRequest);

  nsresult FillCompileOptionsForRequest(
      JSContext* cx, ScriptLoadRequest* aRequest, JS::CompileOptions* aOptions,
      JS::MutableHandle<JSScript*> aIntroductionScript) override;

  void ReportErrorToConsole(ScriptLoadRequest* aRequest,
                            nsresult aResult) const override;

  // Only used by import maps, crash if we get here.
  void ReportWarningToConsole(
      ScriptLoadRequest* aRequest, const char* aMessageName,
      const nsTArray<nsString>& aParams = nsTArray<nsString>()) const override {
    MOZ_CRASH("Import maps have not been implemented for this context");
  }

  void LogExceptionToConsole(JSContext* aCx, WorkerPrivate* aWorkerPrivate);

  bool AllModuleRequestsLoaded() const;
  void IncreaseLoadingModuleRequestCount();
  void DecreaseLoadingModuleRequestCount();
};

/* ScriptLoaderRunnable
 *
 * Responsibilities of this class:
 *   - the actual dispatch
 *   - delegating the load back to WorkerScriptLoader
 *   - handling the collections of scripts being requested
 *   - handling main thread cancellation
 *   - dispatching back to the worker thread
 */
class ScriptLoaderRunnable final : public nsIRunnable, public nsINamed {
  RefPtr<WorkerScriptLoader> mScriptLoader;
  RefPtr<ThreadSafeWorkerRef> mWorkerRef;
  nsTArrayView<RefPtr<ThreadSafeRequestHandle>> mLoadingRequests;
  Maybe<nsresult> mCancelMainThread;
  RefPtr<CacheCreator> mCacheCreator;

 public:
  NS_DECL_THREADSAFE_ISUPPORTS

  explicit ScriptLoaderRunnable(
      WorkerScriptLoader* aScriptLoader,
      nsTArray<RefPtr<ThreadSafeRequestHandle>> aLoadingRequests);

  nsresult OnStreamComplete(ThreadSafeRequestHandle* aRequestHandle,
                            nsresult aStatus);

  void LoadingFinished(ThreadSafeRequestHandle* aRequestHandle, nsresult aRv);

  void MaybeExecuteFinishedScripts(ThreadSafeRequestHandle* aRequestHandle);

  bool IsCancelled() { return mCancelMainThread.isSome(); }

  nsresult GetCancelResult() {
    return (IsCancelled()) ? mCancelMainThread.ref() : NS_OK;
  }

  void CancelMainThreadWithBindingAborted();

  CacheCreator* GetCacheCreator() { return mCacheCreator; };

 private:
  ~ScriptLoaderRunnable() = default;

  void CancelMainThread(nsresult aCancelResult);

  void DispatchProcessPendingRequests();

  NS_IMETHOD
  Run() override;

  NS_IMETHOD
  GetName(nsACString& aName) override {
    aName.AssignLiteral("ScriptLoaderRunnable");
    return NS_OK;
  }
};

}  // namespace loader

nsresult ChannelFromScriptURLMainThread(
    nsIPrincipal* aPrincipal, Document* aParentDoc, nsILoadGroup* aLoadGroup,
    nsIURI* aScriptURL, const WorkerType& aWorkerType,
    const RequestCredentials& aCredentials,
    const Maybe<ClientInfo>& aClientInfo,
    nsContentPolicyType aContentPolicyType,
    nsICookieJarSettings* aCookieJarSettings, nsIReferrerInfo* aReferrerInfo,
    nsIChannel** aChannel);

nsresult ChannelFromScriptURLWorkerThread(
    JSContext* aCx, WorkerPrivate* aParent, const nsAString& aScriptURL,
    const WorkerType& aWorkerType, const RequestCredentials& aCredentials,
    WorkerLoadInfo& aLoadInfo);

void ReportLoadError(ErrorResult& aRv, nsresult aLoadResult,
                     const nsAString& aScriptURL);

void LoadMainScript(WorkerPrivate* aWorkerPrivate,
                    UniquePtr<SerializedStackHolder> aOriginStack,
                    const nsAString& aScriptURL,
                    WorkerScriptType aWorkerScriptType, ErrorResult& aRv,
                    const mozilla::Encoding* aDocumentEncoding);

void Load(WorkerPrivate* aWorkerPrivate,
          UniquePtr<SerializedStackHolder> aOriginStack,
          const nsTArray<nsString>& aScriptURLs,
          WorkerScriptType aWorkerScriptType, ErrorResult& aRv);

}  // namespace workerinternals

}  // namespace dom
}  // namespace mozilla

#endif /* mozilla_dom_workers_scriptloader_h__ */