Backed out changeset b462e7b742d8 (bug 1908261) for causing multiple reftest failures...
[gecko.git] / dom / workers / WorkerRunnable.h
blob036703e41d6bef1fcd6893999dfaab94464ed0c2
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #ifndef mozilla_dom_workers_workerrunnable_h__
8 #define mozilla_dom_workers_workerrunnable_h__
10 #include <cstdint>
11 #include <utility>
12 #include "MainThreadUtils.h"
13 #include "mozilla/Atomics.h"
14 #include "mozilla/RefPtr.h"
15 #include "mozilla/ThreadSafeWeakPtr.h"
16 #include "mozilla/dom/WorkerPrivate.h"
17 #include "mozilla/dom/WorkerRef.h"
18 #include "mozilla/dom/WorkerStatus.h"
19 #include "mozilla/dom/quota/CheckedUnsafePtr.h"
20 #include "nsCOMPtr.h"
21 #include "nsIRunnable.h"
22 #include "nsISupports.h"
23 #include "nsStringFwd.h"
24 #include "nsThreadUtils.h"
25 #include "nscore.h"
27 struct JSContext;
28 class nsIEventTarget;
29 class nsIGlobalObject;
31 namespace mozilla {
33 class ErrorResult;
35 namespace dom {
37 class Worker;
39 class WorkerRunnable : public nsIRunnable
40 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
42 public nsINamed
43 #endif
45 protected:
46 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
47 const char* mName = nullptr;
48 #endif
50 public:
51 NS_DECL_THREADSAFE_ISUPPORTS
52 #ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
53 NS_DECL_NSINAMED
54 #endif
56 virtual nsresult Cancel() = 0;
58 // The return value is true if and only if both PreDispatch and
59 // DispatchInternal return true.
60 virtual bool Dispatch(WorkerPrivate* aWorkerPrivate);
62 // True if this runnable is handled by running JavaScript in some global that
63 // could possibly be a debuggee, and thus needs to be deferred when the target
64 // is paused in the debugger, until the JavaScript invocation in progress has
65 // run to completion. Examples are MessageEventRunnable and
66 // ReportErrorRunnable. These runnables are segregated into separate
67 // ThrottledEventQueues, which the debugger pauses.
69 // Note that debugger runnables do not fall in this category, since we don't
70 // support debugging the debugger server at the moment.
71 virtual bool IsDebuggeeRunnable() const { return false; }
73 // True if this runnable needs to be dispatched to
74 // WorkerPrivate::mControlEventTareget.
75 virtual bool IsControlRunnable() const { return false; }
77 // True if this runnable should be dispatched to the debugger queue,
78 // and false otherwise.
79 virtual bool IsDebuggerRunnable() const { return false; }
81 static WorkerRunnable* FromRunnable(nsIRunnable* aRunnable);
83 protected:
84 explicit WorkerRunnable(const char* aName = "WorkerRunnable")
85 #ifdef DEBUG
87 #else
88 # ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
89 : mName(aName)
90 # endif
93 #endif
95 // This class is reference counted.
96 virtual ~WorkerRunnable() = default;
98 // Calling Run() directly is not supported. Just call Dispatch() and
99 // WorkerRun() will be called on the correct thread automatically.
100 NS_DECL_NSIRUNNABLE
102 // By default asserts that Dispatch() is being called on the right thread
103 virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) = 0;
105 // By default asserts that Dispatch() is being called on the right thread
106 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
107 bool aDispatchResult) = 0;
109 virtual bool DispatchInternal(WorkerPrivate* aWorkerPrivate) = 0;
111 // May be implemented by subclasses if desired if they need to do some sort of
112 // setup before we try to set up our JSContext and compartment for real.
113 // Typically the only thing that should go in here is creation of the worker's
114 // global.
116 // If false is returned, WorkerRun will not be called at all. PostRun will
117 // still be called, with false passed for aRunResult.
118 virtual bool PreRun(WorkerPrivate* aWorkerPrivate) = 0;
120 // Must be implemented by subclasses. Called on the target thread. The return
121 // value will be passed to PostRun(). The JSContext passed in here comes from
122 // an AutoJSAPI (or AutoEntryScript) that we set up on the stack.
124 // If the runnable is for parent thread, aCx is in the compartment of
125 // mWorkerPrivate's reflector (i.e. the worker object in the parent thread),
126 // unless that reflector is null, in which case it's in the compartment of the
127 // parent global (which is the compartment reflector would have been in), or
128 // in the null compartment if there is no parent global.
130 // For runnables on the worker thread, aCx is in whatever
131 // compartment GetCurrentWorkerThreadJSContext() was in when
132 // nsIRunnable::Run() got called. This is actually important for cases when a
133 // runnable spins a syncloop and wants everything that happens during the
134 // syncloop to happen in the compartment that runnable set up (which may, for
135 // example, be a debugger sandbox compartment!). If aCx wasn't in a
136 // compartment to start with, aCx will be in either the debugger global's
137 // compartment or the worker's global's compartment depending on whether
138 // IsDebuggerRunnable() is true.
140 // Immediately after WorkerRun returns, the caller will assert that either it
141 // returns false or there is no exception pending on aCx. Then it will report
142 // any pending exceptions on aCx.
143 virtual bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) = 0;
145 // By default asserts that Run() (and WorkerRun()) were called on the correct
146 // thread.
148 // The aCx passed here is the same one as was passed to WorkerRun and is
149 // still in the same compartment. PostRun implementations must NOT leave an
150 // exception on the JSContext and must not run script, because the incoming
151 // JSContext may be in the null compartment.
152 virtual void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
153 bool aRunResult) = 0;
156 class WorkerParentThreadRunnable : public WorkerRunnable {
157 public:
158 NS_INLINE_DECL_REFCOUNTING_INHERITED(WorkerParentThreadRunnable,
159 WorkerRunnable)
161 virtual nsresult Cancel() override;
163 protected:
164 explicit WorkerParentThreadRunnable(
165 const char* aName = "WorkerParentThreadRunnable");
167 // This class is reference counted.
168 virtual ~WorkerParentThreadRunnable();
170 virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override;
172 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
173 bool aDispatchResult) override;
175 virtual bool PreRun(WorkerPrivate* aWorkerPrivate) override;
177 virtual bool WorkerRun(JSContext* aCx,
178 WorkerPrivate* aWorkerPrivate) override = 0;
180 virtual void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
181 bool aRunResult) override;
183 virtual bool DispatchInternal(WorkerPrivate* aWorkerPrivate) final;
185 // Calling Run() directly is not supported. Just call Dispatch() and
186 // WorkerRun() will be called on the correct thread automatically.
187 NS_DECL_NSIRUNNABLE
189 private:
190 RefPtr<WorkerParentRef> mWorkerParentRef;
193 class WorkerParentControlRunnable : public WorkerParentThreadRunnable {
194 friend class WorkerPrivate;
196 protected:
197 explicit WorkerParentControlRunnable(
198 const char* aName = "WorkerParentControlRunnable");
200 virtual ~WorkerParentControlRunnable();
202 nsresult Cancel() override;
204 public:
205 NS_INLINE_DECL_REFCOUNTING_INHERITED(WorkerParentControlRunnable,
206 WorkerParentThreadRunnable)
208 private:
209 bool IsControlRunnable() const override { return true; }
211 // Should only be called by WorkerPrivate::DoRunLoop.
212 using WorkerParentThreadRunnable::Cancel;
215 class WorkerParentDebuggeeRunnable : public WorkerParentThreadRunnable {
216 protected:
217 explicit WorkerParentDebuggeeRunnable(
218 const char* aName = "WorkerParentDebuggeeRunnable")
219 : WorkerParentThreadRunnable(aName) {}
221 private:
222 // This override is deliberately private: it doesn't make sense to call it if
223 // we know statically that we are a WorkerDebuggeeRunnable.
224 bool IsDebuggeeRunnable() const override { return true; }
227 class WorkerThreadRunnable : public WorkerRunnable {
228 friend class WorkerPrivate;
230 public:
231 NS_INLINE_DECL_REFCOUNTING_INHERITED(WorkerThreadRunnable, WorkerRunnable)
233 virtual nsresult Cancel() override;
235 protected:
236 explicit WorkerThreadRunnable(const char* aName = "WorkerThreadRunnable");
238 // This class is reference counted.
239 virtual ~WorkerThreadRunnable() = default;
241 nsIGlobalObject* DefaultGlobalObject(WorkerPrivate* aWorkerPrivate) const;
243 virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override;
245 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
246 bool aDispatchResult) override;
248 virtual bool PreRun(WorkerPrivate* aWorkerPrivate) override;
250 virtual bool WorkerRun(JSContext* aCx,
251 WorkerPrivate* aWorkerPrivate) override = 0;
253 virtual void PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
254 bool aRunResult) override;
256 virtual bool DispatchInternal(WorkerPrivate* aWorkerPrivate) override;
258 // Calling Run() directly is not supported. Just call Dispatch() and
259 // WorkerRun() will be called on the correct thread automatically.
260 NS_DECL_NSIRUNNABLE
262 // Whether or not Cancel() is currently being called from inside the Run()
263 // method. Avoids infinite recursion when a subclass calls Run() from inside
264 // Cancel(). Only checked and modified on the target thread.
265 bool mCallingCancelWithinRun;
267 bool mCleanPreStartDispatching{false};
270 // This runnable is used to send a message to a worker debugger.
271 class WorkerDebuggerRunnable : public WorkerThreadRunnable {
272 protected:
273 explicit WorkerDebuggerRunnable(const char* aName = "WorkerDebuggerRunnable")
274 : WorkerThreadRunnable(aName) {}
276 virtual ~WorkerDebuggerRunnable() = default;
278 private:
279 virtual bool IsDebuggerRunnable() const override { return true; }
281 bool PreDispatch(WorkerPrivate* aWorkerPrivate) final {
282 AssertIsOnMainThread();
284 return true;
287 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
288 bool aDispatchResult) override;
291 // This runnable is used to send a message directly to a worker's sync loop.
292 class WorkerSyncRunnable : public WorkerThreadRunnable {
293 protected:
294 nsCOMPtr<nsIEventTarget> mSyncLoopTarget;
296 // Passing null for aSyncLoopTarget is allowed and will result in the behavior
297 // of a normal WorkerThreadRunnable.
298 explicit WorkerSyncRunnable(nsIEventTarget* aSyncLoopTarget,
299 const char* aName = "WorkerSyncRunnable");
301 explicit WorkerSyncRunnable(nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget,
302 const char* aName = "WorkerSyncRunnable");
304 virtual ~WorkerSyncRunnable();
306 virtual bool DispatchInternal(WorkerPrivate* aWorkerPrivate) override;
309 // This runnable is identical to WorkerSyncRunnable except it is meant to be
310 // created on and dispatched from the main thread only. Its WorkerRun/PostRun
311 // will run on the worker thread.
312 class MainThreadWorkerSyncRunnable : public WorkerSyncRunnable {
313 protected:
314 // Passing null for aSyncLoopTarget is allowed and will result in the behavior
315 // of a normal WorkerThreadRunnable.
316 explicit MainThreadWorkerSyncRunnable(
317 nsIEventTarget* aSyncLoopTarget,
318 const char* aName = "MainThreadWorkerSyncRunnable")
319 : WorkerSyncRunnable(aSyncLoopTarget, aName) {
320 AssertIsOnMainThread();
323 explicit MainThreadWorkerSyncRunnable(
324 nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget,
325 const char* aName = "MainThreadWorkerSyncRunnable")
326 : WorkerSyncRunnable(std::move(aSyncLoopTarget), aName) {
327 AssertIsOnMainThread();
330 virtual ~MainThreadWorkerSyncRunnable() = default;
332 private:
333 virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override {
334 AssertIsOnMainThread();
335 return true;
338 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
339 bool aDispatchResult) override;
342 // This runnable is processed as soon as it is received by the worker,
343 // potentially running before previously queued runnables and perhaps even with
344 // other JS code executing on the stack. These runnables must not alter the
345 // state of the JS runtime and should only twiddle state values.
346 class WorkerControlRunnable : public WorkerThreadRunnable {
347 friend class WorkerPrivate;
349 protected:
350 explicit WorkerControlRunnable(const char* aName = "WorkerControlRunnable");
352 virtual ~WorkerControlRunnable() = default;
354 nsresult Cancel() override;
356 public:
357 NS_INLINE_DECL_REFCOUNTING_INHERITED(WorkerControlRunnable,
358 WorkerThreadRunnable)
360 private:
361 bool IsControlRunnable() const override { return true; }
363 // Should only be called by WorkerPrivate::DoRunLoop.
364 using WorkerThreadRunnable::Cancel;
367 // A convenience class for WorkerThreadRunnables that are originated on the main
368 // thread.
369 class MainThreadWorkerRunnable : public WorkerThreadRunnable {
370 protected:
371 explicit MainThreadWorkerRunnable(
372 const char* aName = "MainThreadWorkerRunnable")
373 : WorkerThreadRunnable(aName) {
374 AssertIsOnMainThread();
377 virtual ~MainThreadWorkerRunnable() = default;
379 virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override {
380 AssertIsOnMainThread();
381 return true;
384 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
385 bool aDispatchResult) override {
386 AssertIsOnMainThread();
390 // A convenience class for WorkerControlRunnables that originate on the main
391 // thread.
392 class MainThreadWorkerControlRunnable : public WorkerControlRunnable {
393 protected:
394 explicit MainThreadWorkerControlRunnable(
395 const char* aName = "MainThreadWorkerControlRunnable")
396 : WorkerControlRunnable(aName) {}
398 virtual ~MainThreadWorkerControlRunnable() = default;
400 virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override {
401 AssertIsOnMainThread();
402 return true;
405 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
406 bool aDispatchResult) override {
407 AssertIsOnMainThread();
411 // A WorkerThreadRunnable that should be dispatched from the worker to itself
412 // for async tasks.
414 // Async tasks will almost always want to use this since
415 // a WorkerSameThreadRunnable keeps the Worker from being GCed.
416 class WorkerSameThreadRunnable : public WorkerThreadRunnable {
417 protected:
418 explicit WorkerSameThreadRunnable(
419 const char* aName = "WorkerSameThreadRunnable")
420 : WorkerThreadRunnable(aName) {}
422 virtual ~WorkerSameThreadRunnable() = default;
424 virtual bool PreDispatch(WorkerPrivate* aWorkerPrivate) override;
426 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
427 bool aDispatchResult) override;
429 // We just delegate PostRun to WorkerThreadRunnable, since it does exactly
430 // what we want.
433 // Base class for the runnable objects, which makes a synchronous call to
434 // dispatch the tasks from the worker thread to the main thread.
436 // Note that the derived class must override MainThreadRun.
437 class WorkerMainThreadRunnable : public Runnable {
438 protected:
439 RefPtr<ThreadSafeWorkerRef> mWorkerRef;
440 nsCOMPtr<nsISerialEventTarget> mSyncLoopTarget;
441 const nsCString mTelemetryKey;
442 const char* mName;
444 explicit WorkerMainThreadRunnable(
445 WorkerPrivate* aWorkerPrivate, const nsACString& aTelemetryKey,
446 const char* aName = "WorkerMainThreadRunnable");
448 ~WorkerMainThreadRunnable();
450 virtual bool MainThreadRun() = 0;
452 public:
453 // Dispatch the runnable to the main thread. If dispatch to main thread
454 // fails, or if the worker is in a state equal or greater of aFailStatus, an
455 // error will be reported on aRv. Normally you want to use 'Canceling' for
456 // aFailStatus, except if you want an infallible runnable. In this case, use
457 // 'Killing'.
458 // In that case the error MUST be propagated out to script.
459 void Dispatch(WorkerPrivate* aWorkerPrivate, WorkerStatus aFailStatus,
460 ErrorResult& aRv);
462 private:
463 NS_IMETHOD Run() override;
466 // This runnable is an helper class for dispatching something from a worker
467 // thread to the main-thread and back to the worker-thread. During this
468 // operation, this class will keep the worker alive.
469 // The purpose of RunBackOnWorkerThreadForCleanup() must be used, as the name
470 // says, only to release resources, no JS has to be executed, no timers, or
471 // other things. The reason of such limitations is that, in order to execute
472 // this method in any condition (also when the worker is shutting down), a
473 // Control Runnable is used, and, this could generate a reordering of existing
474 // runnables.
475 class WorkerProxyToMainThreadRunnable : public Runnable {
476 protected:
477 WorkerProxyToMainThreadRunnable();
479 virtual ~WorkerProxyToMainThreadRunnable();
481 // First this method is called on the main-thread.
482 virtual void RunOnMainThread(WorkerPrivate* aWorkerPrivate) = 0;
484 // After this second method is called on the worker-thread.
485 virtual void RunBackOnWorkerThreadForCleanup(
486 WorkerPrivate* aWorkerPrivate) = 0;
488 public:
489 bool Dispatch(WorkerPrivate* aWorkerPrivate);
491 virtual bool ForMessaging() const { return false; }
493 private:
494 NS_IMETHOD Run() override;
496 void PostDispatchOnMainThread();
498 void ReleaseWorker();
500 RefPtr<ThreadSafeWorkerRef> mWorkerRef;
503 // This runnable is used to stop a sync loop and it's meant to be used on the
504 // main-thread only.
505 class MainThreadStopSyncLoopRunnable : public WorkerSyncRunnable {
506 nsresult mResult;
508 public:
509 // Passing null for aSyncLoopTarget is not allowed.
510 MainThreadStopSyncLoopRunnable(nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget,
511 nsresult aResult);
513 // By default StopSyncLoopRunnables cannot be canceled since they could leave
514 // a sync loop spinning forever.
515 nsresult Cancel() override;
517 protected:
518 virtual ~MainThreadStopSyncLoopRunnable() = default;
520 private:
521 bool PreDispatch(WorkerPrivate* aWorkerPrivate) final {
522 AssertIsOnMainThread();
523 return true;
526 virtual void PostDispatch(WorkerPrivate* aWorkerPrivate,
527 bool aDispatchResult) override;
529 virtual bool WorkerRun(JSContext* aCx,
530 WorkerPrivate* aWorkerPrivate) override;
532 bool DispatchInternal(WorkerPrivate* aWorkerPrivate) final;
535 // Runnables handled by content JavaScript (MessageEventRunnable, JavaScript
536 // error reports, and so on) must not be delivered while that content is in the
537 // midst of being debugged; the debuggee must be allowed to complete its current
538 // JavaScript invocation and return to its own event loop. Only then is it
539 // prepared for messages sent from the worker.
541 // Runnables that need to be deferred in this way should inherit from this
542 // class. They will be routed to mMainThreadDebuggeeEventTarget, which is paused
543 // while the window is suspended, as it is whenever the debugger spins its
544 // nested event loop. When the debugger leaves its nested event loop, it resumes
545 // the window, so that mMainThreadDebuggeeEventTarget will resume delivering
546 // runnables from the worker when control returns to the main event loop.
548 // When a page enters the bfcache, it freezes all its workers. Since a frozen
549 // worker processes only control runnables, it doesn't take any special
550 // consideration to prevent WorkerDebuggeeRunnables sent from child to parent
551 // workers from running; they'll never run anyway. But WorkerDebuggeeRunnables
552 // from a top-level frozen worker to its parent window must not be delivered
553 // either, even as the main thread event loop continues to spin. Thus, freezing
554 // a top-level worker also pauses mMainThreadDebuggeeEventTarget.
555 class WorkerDebuggeeRunnable : public WorkerThreadRunnable {
556 protected:
557 explicit WorkerDebuggeeRunnable(const char* aName = "WorkerDebuggeeRunnable")
558 : WorkerThreadRunnable(aName) {}
560 private:
561 // This override is deliberately private: it doesn't make sense to call it if
562 // we know statically that we are a WorkerDebuggeeRunnable.
563 bool IsDebuggeeRunnable() const override { return true; }
566 } // namespace dom
567 } // namespace mozilla
569 #endif // mozilla_dom_workers_workerrunnable_h__