summaryrefslogtreecommitdiffstats
path: root/dom/workers/WorkerRunnable.cpp
blob: ff2178d16e7d054a3216e82ada280e99a2d9e0b2 (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
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
/* -*- 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/. */

#include "WorkerRunnable.h"

#include "WorkerScope.h"
#include "js/RootingAPI.h"
#include "jsapi.h"
#include "jsfriendapi.h"
#include "mozilla/AlreadyAddRefed.h"
#include "mozilla/AppShutdown.h"
#include "mozilla/Assertions.h"
#include "mozilla/CycleCollectedJSContext.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/ErrorResult.h"
#include "mozilla/Logging.h"
#include "mozilla/Maybe.h"
#include "mozilla/Telemetry.h"
#include "mozilla/TelemetryHistogramEnums.h"
#include "mozilla/TimeStamp.h"
#include "mozilla/Unused.h"
#include "mozilla/dom/ScriptSettings.h"
#include "mozilla/dom/Worker.h"
#include "mozilla/dom/WorkerCommon.h"
#include "nsDebug.h"
#include "nsGlobalWindowInner.h"
#include "nsID.h"
#include "nsIEventTarget.h"
#include "nsIGlobalObject.h"
#include "nsIRunnable.h"
#include "nsThreadUtils.h"
#include "nsWrapperCacheInlines.h"

namespace mozilla::dom {

static mozilla::LazyLogModule sWorkerRunnableLog("WorkerRunnable");

#ifdef LOG
#  undef LOG
#endif
#define LOG(args) MOZ_LOG(sWorkerRunnableLog, LogLevel::Verbose, args);

namespace {

const nsIID kWorkerRunnableIID = {
    0x320cc0b5,
    0xef12,
    0x4084,
    {0x88, 0x6e, 0xca, 0x6a, 0x81, 0xe4, 0x1d, 0x68}};

}  // namespace

#ifdef DEBUG
WorkerRunnable::WorkerRunnable(WorkerPrivate* aWorkerPrivate, const char* aName,
                               Target aTarget)
    : mWorkerPrivate(aWorkerPrivate),
      mTarget(aTarget),
#  ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
      mName(aName),
#  endif
      mCallingCancelWithinRun(false) {
  LOG(("WorkerRunnable::WorkerRunnable [%p]", this));
  MOZ_ASSERT(aWorkerPrivate);
}
#endif

bool WorkerRunnable::IsDebuggerRunnable() const { return false; }

nsIGlobalObject* WorkerRunnable::DefaultGlobalObject() const {
  if (IsDebuggerRunnable()) {
    return mWorkerPrivate->DebuggerGlobalScope();
  } else {
    return mWorkerPrivate->GlobalScope();
  }
}

bool WorkerRunnable::PreDispatch(WorkerPrivate* aWorkerPrivate) {
#ifdef DEBUG
  MOZ_ASSERT(aWorkerPrivate);

  switch (mTarget) {
    case ParentThread:
      aWorkerPrivate->AssertIsOnWorkerThread();
      break;

    case WorkerThread:
      aWorkerPrivate->AssertIsOnParentThread();
      break;

    default:
      MOZ_ASSERT_UNREACHABLE("Unknown behavior!");
  }
#endif
  return true;
}

bool WorkerRunnable::Dispatch() {
  bool ok = PreDispatch(mWorkerPrivate);
  if (ok) {
    ok = DispatchInternal();
  }
  PostDispatch(mWorkerPrivate, ok);
  return ok;
}

bool WorkerRunnable::DispatchInternal() {
  LOG(("WorkerRunnable::DispatchInternal [%p]", this));
  RefPtr<WorkerRunnable> runnable(this);

  if (mTarget == WorkerThread) {
    if (IsDebuggerRunnable()) {
      return NS_SUCCEEDED(
          mWorkerPrivate->DispatchDebuggerRunnable(runnable.forget()));
    } else {
      return NS_SUCCEEDED(mWorkerPrivate->Dispatch(runnable.forget()));
    }
  }

  MOZ_ASSERT(mTarget == ParentThread);

  if (WorkerPrivate* parent = mWorkerPrivate->GetParent()) {
    return NS_SUCCEEDED(parent->Dispatch(runnable.forget()));
  }

  if (IsDebuggeeRunnable()) {
    RefPtr<WorkerDebuggeeRunnable> debuggeeRunnable =
        runnable.forget().downcast<WorkerDebuggeeRunnable>();
    return NS_SUCCEEDED(mWorkerPrivate->DispatchDebuggeeToMainThread(
        debuggeeRunnable.forget(), NS_DISPATCH_NORMAL));
  }

  return NS_SUCCEEDED(mWorkerPrivate->DispatchToMainThread(runnable.forget()));
}

void WorkerRunnable::PostDispatch(WorkerPrivate* aWorkerPrivate,
                                  bool aDispatchResult) {
  MOZ_ASSERT(aWorkerPrivate);

#ifdef DEBUG
  switch (mTarget) {
    case ParentThread:
      aWorkerPrivate->AssertIsOnWorkerThread();
      break;

    case WorkerThread:
      aWorkerPrivate->AssertIsOnParentThread();
      break;

    default:
      MOZ_ASSERT_UNREACHABLE("Unknown behavior!");
  }
#endif
}

bool WorkerRunnable::PreRun(WorkerPrivate* aWorkerPrivate) { return true; }

void WorkerRunnable::PostRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate,
                             bool aRunResult) {
  MOZ_ASSERT(aCx);
  MOZ_ASSERT(aWorkerPrivate);

#ifdef DEBUG
  switch (mTarget) {
    case ParentThread:
      aWorkerPrivate->AssertIsOnParentThread();
      break;

    case WorkerThread:
      aWorkerPrivate->AssertIsOnWorkerThread();
      break;

    default:
      MOZ_ASSERT_UNREACHABLE("Unknown behavior!");
  }
#endif
}

// static
WorkerRunnable* WorkerRunnable::FromRunnable(nsIRunnable* aRunnable) {
  MOZ_ASSERT(aRunnable);

  WorkerRunnable* runnable;
  nsresult rv = aRunnable->QueryInterface(kWorkerRunnableIID,
                                          reinterpret_cast<void**>(&runnable));
  if (NS_FAILED(rv)) {
    return nullptr;
  }

  MOZ_ASSERT(runnable);
  return runnable;
}

NS_IMPL_ADDREF(WorkerRunnable)
NS_IMPL_RELEASE(WorkerRunnable)

#ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
NS_IMETHODIMP
WorkerRunnable::GetName(nsACString& aName) {
  if (mName) {
    aName.AssignASCII(mName);
  } else {
    aName.Truncate();
  }
  return NS_OK;
}
#endif

NS_INTERFACE_MAP_BEGIN(WorkerRunnable)
  NS_INTERFACE_MAP_ENTRY(nsIRunnable)
#ifdef MOZ_COLLECTING_RUNNABLE_TELEMETRY
  NS_INTERFACE_MAP_ENTRY(nsINamed)
#endif
  NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIRunnable)
  // kWorkerRunnableIID is special in that it does not AddRef its result.
  if (aIID.Equals(kWorkerRunnableIID)) {
    *aInstancePtr = this;
    return NS_OK;
  } else
NS_INTERFACE_MAP_END

NS_IMETHODIMP
WorkerRunnable::Run() {
  LOG(("WorkerRunnable::Run [%p]", this));
  bool targetIsWorkerThread = mTarget == WorkerThread;

  if (targetIsWorkerThread) {
    // On a worker thread, a WorkerRunnable should only run when there is an
    // underlying WorkerThreadPrimaryRunnable active, which means we should
    // find a CycleCollectedJSContext.
    if (!CycleCollectedJSContext::Get()) {
#if (defined(MOZ_COLLECTING_RUNNABLE_TELEMETRY) && defined(NIGHTLY_BUILD))
      // We will only leak the static name string of the WorkerRunnable type
      // we are trying to execute.
      MOZ_CRASH_UNSAFE_PRINTF(
          "Runnable '%s' executed after WorkerThreadPrimaryRunnable ended.",
          this->mName);
#endif
      return NS_OK;
    }
  }

#ifdef DEBUG
  if (targetIsWorkerThread) {
    mWorkerPrivate->AssertIsOnWorkerThread();
  } else {
    MOZ_ASSERT(mTarget == ParentThread);
    mWorkerPrivate->AssertIsOnParentThread();
  }
#endif

  if (targetIsWorkerThread && !mCallingCancelWithinRun &&
      mWorkerPrivate->CancelBeforeWorkerScopeConstructed()) {
    mCallingCancelWithinRun = true;
    Cancel();
    mCallingCancelWithinRun = false;
    return NS_OK;
  }

  bool result = PreRun(mWorkerPrivate);
  if (!result) {
    MOZ_ASSERT(targetIsWorkerThread,
               "The only PreRun implementation that can fail is "
               "ScriptExecutorRunnable");
    mWorkerPrivate->AssertIsOnWorkerThread();
    MOZ_ASSERT(!JS_IsExceptionPending(mWorkerPrivate->GetJSContext()));
    // We can't enter a useful realm on the JSContext here; just pass it
    // in as-is.
    PostRun(mWorkerPrivate->GetJSContext(), mWorkerPrivate, false);
    return NS_ERROR_FAILURE;
  }

  // Track down the appropriate global, if any, to use for the AutoEntryScript.
  nsCOMPtr<nsIGlobalObject> globalObject;
  bool isMainThread = !targetIsWorkerThread && !mWorkerPrivate->GetParent();
  MOZ_ASSERT(isMainThread == NS_IsMainThread());
  RefPtr<WorkerPrivate> kungFuDeathGrip;
  if (targetIsWorkerThread) {
    globalObject = mWorkerPrivate->GetCurrentEventLoopGlobal();
    if (!globalObject) {
      globalObject = DefaultGlobalObject();
      // Our worker thread may not be in a good state here if there is no
      // JSContext avaliable.  The way this manifests itself is that
      // globalObject ends up null (though it's not clear to me how we can be
      // running runnables at all when DefaultGlobalObject() is returning
      // false!) and then when we try to init the AutoJSAPI either
      // CycleCollectedJSContext::Get() returns null or it has a null JSContext.
      // In any case, we used to have a check for
      // GetCurrentWorkerThreadJSContext() being non-null here and that seems to
      // avoid the problem, so let's keep doing that check even if we don't need
      // the JSContext here at all.
      if (NS_WARN_IF(!globalObject && !GetCurrentWorkerThreadJSContext())) {
        return NS_ERROR_FAILURE;
      }
    }

    // We may still not have a globalObject here: in the case of
    // CompileScriptRunnable, we don't actually create the global object until
    // we have the script data, which happens in a syncloop under
    // CompileScriptRunnable::WorkerRun, so we can't assert that it got created
    // in the PreRun call above.
  } else {
    kungFuDeathGrip = mWorkerPrivate;
    if (isMainThread) {
      globalObject = nsGlobalWindowInner::Cast(mWorkerPrivate->GetWindow());
    } else {
      globalObject = mWorkerPrivate->GetParent()->GlobalScope();
    }
  }

  // We might run script as part of WorkerRun, so we need an AutoEntryScript.
  // This is part of the HTML spec for workers at:
  // http://www.whatwg.org/specs/web-apps/current-work/#run-a-worker
  // If we don't have a globalObject we have to use an AutoJSAPI instead, but
  // this is OK as we won't be running script in these circumstances.
  Maybe<mozilla::dom::AutoJSAPI> maybeJSAPI;
  Maybe<mozilla::dom::AutoEntryScript> aes;
  JSContext* cx;
  AutoJSAPI* jsapi;
  if (globalObject) {
    aes.emplace(globalObject, "Worker runnable", isMainThread);
    jsapi = aes.ptr();
    cx = aes->cx();
  } else {
    maybeJSAPI.emplace();
    maybeJSAPI->Init();
    jsapi = maybeJSAPI.ptr();
    cx = jsapi->cx();
  }

  // Note that we can't assert anything about
  // mWorkerPrivate->ParentEventTargetRef()->GetWrapper()
  // existing, since it may in fact have been GCed (and we may be one of the
  // runnables cleaning up the worker as a result).

  // If we are on the parent thread and that thread is not the main thread,
  // then we must be a dedicated worker (because there are no
  // Shared/ServiceWorkers whose parent is itself a worker) and then we
  // definitely have a globalObject.  If it _is_ the main thread, globalObject
  // can be null for workers started from JSMs or other non-window contexts,
  // sadly.
  MOZ_ASSERT_IF(!targetIsWorkerThread && !isMainThread,
                mWorkerPrivate->IsDedicatedWorker() && globalObject);

  // If we're on the parent thread we might be in a null realm in the
  // situation described above when globalObject is null.  Make sure to enter
  // the realm of the worker's reflector if there is one.  There might
  // not be one if we're just starting to compile the script for this worker.
  Maybe<JSAutoRealm> ar;
  if (!targetIsWorkerThread && mWorkerPrivate->IsDedicatedWorker() &&
      mWorkerPrivate->ParentEventTargetRef()->GetWrapper()) {
    JSObject* wrapper = mWorkerPrivate->ParentEventTargetRef()->GetWrapper();

    // If we're on the parent thread and have a reflector and a globalObject,
    // then the realms of cx, globalObject, and the worker's reflector
    // should all match.
    MOZ_ASSERT_IF(globalObject,
                  js::GetNonCCWObjectRealm(wrapper) == js::GetContextRealm(cx));
    MOZ_ASSERT_IF(globalObject,
                  js::GetNonCCWObjectRealm(wrapper) ==
                      js::GetNonCCWObjectRealm(
                          globalObject->GetGlobalJSObjectPreserveColor()));

    // If we're on the parent thread and have a reflector, then our
    // JSContext had better be either in the null realm (and hence
    // have no globalObject) or in the realm of our reflector.
    MOZ_ASSERT(!js::GetContextRealm(cx) ||
                   js::GetNonCCWObjectRealm(wrapper) == js::GetContextRealm(cx),
               "Must either be in the null compartment or in our reflector "
               "compartment");

    ar.emplace(cx, wrapper);
  }

  MOZ_ASSERT(!jsapi->HasException());
  result = WorkerRun(cx, mWorkerPrivate);
  jsapi->ReportException();

  // We can't even assert that this didn't create our global, since in the case
  // of CompileScriptRunnable it _does_.

  // It would be nice to avoid passing a JSContext to PostRun, but in the case
  // of ScriptExecutorRunnable we need to know the current compartment on the
  // JSContext (the one we set up based on the global returned from PreRun) so
  // that we can sanely do exception reporting.  In particular, we want to make
  // sure that we do our JS_SetPendingException while still in that compartment,
  // because otherwise we might end up trying to create a cross-compartment
  // wrapper when we try to move the JS exception from our runnable's
  // ErrorResult to the JSContext, and that's not desirable in this case.
  //
  // We _could_ skip passing a JSContext here and then in
  // ScriptExecutorRunnable::PostRun end up grabbing it from the WorkerPrivate
  // and looking at its current compartment.  But that seems like slightly weird
  // action-at-a-distance...
  //
  // In any case, we do NOT try to change the compartment on the JSContext at
  // this point; in the one case in which we could do that
  // (CompileScriptRunnable) it actually doesn't matter which compartment we're
  // in for PostRun.
  PostRun(cx, mWorkerPrivate, result);
  MOZ_ASSERT(!jsapi->HasException());

  return result ? NS_OK : NS_ERROR_FAILURE;
}

nsresult WorkerRunnable::Cancel() {
  LOG(("WorkerRunnable::Cancel [%p]", this));
  return NS_OK;
}

void WorkerDebuggerRunnable::PostDispatch(WorkerPrivate* aWorkerPrivate,
                                          bool aDispatchResult) {}

WorkerSyncRunnable::WorkerSyncRunnable(WorkerPrivate* aWorkerPrivate,
                                       nsIEventTarget* aSyncLoopTarget,
                                       const char* aName)
    : WorkerRunnable(aWorkerPrivate, aName, WorkerThread),
      mSyncLoopTarget(aSyncLoopTarget) {
#ifdef DEBUG
  if (mSyncLoopTarget) {
    mWorkerPrivate->AssertValidSyncLoop(mSyncLoopTarget);
  }
#endif
}

WorkerSyncRunnable::WorkerSyncRunnable(
    WorkerPrivate* aWorkerPrivate, nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget,
    const char* aName)
    : WorkerRunnable(aWorkerPrivate, aName, WorkerThread),
      mSyncLoopTarget(std::move(aSyncLoopTarget)) {
#ifdef DEBUG
  if (mSyncLoopTarget) {
    mWorkerPrivate->AssertValidSyncLoop(mSyncLoopTarget);
  }
#endif
}

WorkerSyncRunnable::~WorkerSyncRunnable() = default;

bool WorkerSyncRunnable::DispatchInternal() {
  if (mSyncLoopTarget) {
    RefPtr<WorkerSyncRunnable> runnable(this);
    return NS_SUCCEEDED(
        mSyncLoopTarget->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL));
  }

  return WorkerRunnable::DispatchInternal();
}

void MainThreadWorkerSyncRunnable::PostDispatch(WorkerPrivate* aWorkerPrivate,
                                                bool aDispatchResult) {}

MainThreadStopSyncLoopRunnable::MainThreadStopSyncLoopRunnable(
    WorkerPrivate* aWorkerPrivate, nsCOMPtr<nsIEventTarget>&& aSyncLoopTarget,
    nsresult aResult)
    : WorkerSyncRunnable(aWorkerPrivate, std::move(aSyncLoopTarget)),
      mResult(aResult) {
  LOG(("MainThreadStopSyncLoopRunnable::MainThreadStopSyncLoopRunnable [%p]",
       this));

  AssertIsOnMainThread();
#ifdef DEBUG
  mWorkerPrivate->AssertValidSyncLoop(mSyncLoopTarget);
#endif
}

nsresult MainThreadStopSyncLoopRunnable::Cancel() {
  LOG(("MainThreadStopSyncLoopRunnable::Cancel [%p]", this));
  nsresult rv = Run();
  NS_WARNING_ASSERTION(NS_SUCCEEDED(rv), "Run() failed");

  return rv;
}

bool MainThreadStopSyncLoopRunnable::WorkerRun(JSContext* aCx,
                                               WorkerPrivate* aWorkerPrivate) {
  aWorkerPrivate->AssertIsOnWorkerThread();
  MOZ_ASSERT(mSyncLoopTarget);

  nsCOMPtr<nsIEventTarget> syncLoopTarget;
  mSyncLoopTarget.swap(syncLoopTarget);

  aWorkerPrivate->StopSyncLoop(syncLoopTarget, mResult);
  return true;
}

bool MainThreadStopSyncLoopRunnable::DispatchInternal() {
  MOZ_ASSERT(mSyncLoopTarget);

  RefPtr<MainThreadStopSyncLoopRunnable> runnable(this);
  return NS_SUCCEEDED(
      mSyncLoopTarget->Dispatch(runnable.forget(), NS_DISPATCH_NORMAL));
}

void MainThreadStopSyncLoopRunnable::PostDispatch(WorkerPrivate* aWorkerPrivate,
                                                  bool aDispatchResult) {}

#ifdef DEBUG
WorkerControlRunnable::WorkerControlRunnable(WorkerPrivate* aWorkerPrivate,
                                             const char* aName, Target aTarget)
    : WorkerRunnable(aWorkerPrivate, aName, aTarget) {
  MOZ_ASSERT(aWorkerPrivate);
}
#endif

nsresult WorkerControlRunnable::Cancel() {
  LOG(("WorkerControlRunnable::Cancel [%p]", this));
  if (NS_FAILED(Run())) {
    NS_WARNING("WorkerControlRunnable::Run() failed.");
  }

  return NS_OK;
}

bool WorkerControlRunnable::DispatchInternal() {
  RefPtr<WorkerControlRunnable> runnable(this);

  if (mTarget == WorkerThread) {
    return NS_SUCCEEDED(
        mWorkerPrivate->DispatchControlRunnable(runnable.forget()));
  }

  if (WorkerPrivate* parent = mWorkerPrivate->GetParent()) {
    return NS_SUCCEEDED(parent->DispatchControlRunnable(runnable.forget()));
  }

  return NS_SUCCEEDED(mWorkerPrivate->DispatchToMainThread(runnable.forget()));
}

WorkerMainThreadRunnable::WorkerMainThreadRunnable(
    WorkerPrivate* aWorkerPrivate, const nsACString& aTelemetryKey)
    : mozilla::Runnable("dom::WorkerMainThreadRunnable"),
      mWorkerPrivate(aWorkerPrivate),
      mTelemetryKey(aTelemetryKey) {
  mWorkerPrivate->AssertIsOnWorkerThread();
}

WorkerMainThreadRunnable::~WorkerMainThreadRunnable() = default;

void WorkerMainThreadRunnable::Dispatch(WorkerStatus aFailStatus,
                                        mozilla::ErrorResult& aRv) {
  mWorkerPrivate->AssertIsOnWorkerThread();

  TimeStamp startTime = TimeStamp::NowLoRes();

  AutoSyncLoopHolder syncLoop(mWorkerPrivate, aFailStatus);

  mSyncLoopTarget = syncLoop.GetSerialEventTarget();
  if (!mSyncLoopTarget) {
    // SyncLoop creation can fail if the worker is shutting down.
    aRv.Throw(NS_ERROR_DOM_INVALID_STATE_ERR);
    return;
  }

  DebugOnly<nsresult> rv = mWorkerPrivate->DispatchToMainThread(this);
  MOZ_ASSERT(
      NS_SUCCEEDED(rv),
      "Should only fail after xpcom-shutdown-threads and we're gone by then");

  bool success = NS_SUCCEEDED(syncLoop.Run());

  Telemetry::Accumulate(
      Telemetry::SYNC_WORKER_OPERATION, mTelemetryKey,
      static_cast<uint32_t>(
          (TimeStamp::NowLoRes() - startTime).ToMilliseconds()));

  Unused << startTime;  // Shut the compiler up.

  if (!success) {
    aRv.ThrowUncatchableException();
  }
}

NS_IMETHODIMP
WorkerMainThreadRunnable::Run() {
  AssertIsOnMainThread();

  // This shouldn't be necessary once we're better about making sure no workers
  // are created during shutdown in earlier phases.
  if (AppShutdown::IsInOrBeyond(ShutdownPhase::XPCOMShutdownThreads)) {
    return NS_ERROR_ILLEGAL_DURING_SHUTDOWN;
  }

  bool runResult = MainThreadRun();

  RefPtr<MainThreadStopSyncLoopRunnable> response =
      new MainThreadStopSyncLoopRunnable(mWorkerPrivate,
                                         std::move(mSyncLoopTarget),
                                         runResult ? NS_OK : NS_ERROR_FAILURE);

  MOZ_ALWAYS_TRUE(response->Dispatch());

  return NS_OK;
}

bool WorkerSameThreadRunnable::PreDispatch(WorkerPrivate* aWorkerPrivate) {
  aWorkerPrivate->AssertIsOnWorkerThread();
  return true;
}

void WorkerSameThreadRunnable::PostDispatch(WorkerPrivate* aWorkerPrivate,
                                            bool aDispatchResult) {
  aWorkerPrivate->AssertIsOnWorkerThread();
}

WorkerProxyToMainThreadRunnable::WorkerProxyToMainThreadRunnable()
    : mozilla::Runnable("dom::WorkerProxyToMainThreadRunnable") {}

WorkerProxyToMainThreadRunnable::~WorkerProxyToMainThreadRunnable() = default;

bool WorkerProxyToMainThreadRunnable::Dispatch(WorkerPrivate* aWorkerPrivate) {
  MOZ_ASSERT(aWorkerPrivate);
  aWorkerPrivate->AssertIsOnWorkerThread();

  RefPtr<StrongWorkerRef> workerRef = StrongWorkerRef::Create(
      aWorkerPrivate, "WorkerProxyToMainThreadRunnable");
  if (NS_WARN_IF(!workerRef)) {
    RunBackOnWorkerThreadForCleanup(aWorkerPrivate);
    return false;
  }

  MOZ_ASSERT(!mWorkerRef);
  mWorkerRef = new ThreadSafeWorkerRef(workerRef);

  if (ForMessaging()
          ? NS_WARN_IF(NS_FAILED(
                aWorkerPrivate->DispatchToMainThreadForMessaging(this)))
          : NS_WARN_IF(NS_FAILED(aWorkerPrivate->DispatchToMainThread(this)))) {
    ReleaseWorker();
    RunBackOnWorkerThreadForCleanup(aWorkerPrivate);
    return false;
  }

  return true;
}

NS_IMETHODIMP
WorkerProxyToMainThreadRunnable::Run() {
  AssertIsOnMainThread();
  RunOnMainThread(mWorkerRef->Private());
  PostDispatchOnMainThread();
  return NS_OK;
}

void WorkerProxyToMainThreadRunnable::PostDispatchOnMainThread() {
  class ReleaseRunnable final : public MainThreadWorkerControlRunnable {
    RefPtr<WorkerProxyToMainThreadRunnable> mRunnable;

   public:
    ReleaseRunnable(WorkerPrivate* aWorkerPrivate,
                    WorkerProxyToMainThreadRunnable* aRunnable)
        : MainThreadWorkerControlRunnable(aWorkerPrivate),
          mRunnable(aRunnable) {
      MOZ_ASSERT(aRunnable);
    }

    virtual nsresult Cancel() override {
      Unused << WorkerRun(nullptr, mWorkerPrivate);
      return NS_OK;
    }

    virtual bool WorkerRun(JSContext* aCx,
                           WorkerPrivate* aWorkerPrivate) override {
      MOZ_ASSERT(aWorkerPrivate);
      aWorkerPrivate->AssertIsOnWorkerThread();

      if (mRunnable) {
        mRunnable->RunBackOnWorkerThreadForCleanup(aWorkerPrivate);

        // Let's release the worker thread.
        mRunnable->ReleaseWorker();
        mRunnable = nullptr;
      }

      return true;
    }

   private:
    ~ReleaseRunnable() = default;
  };

  RefPtr<WorkerControlRunnable> runnable =
      new ReleaseRunnable(mWorkerRef->Private(), this);
  Unused << NS_WARN_IF(!runnable->Dispatch());
}

void WorkerProxyToMainThreadRunnable::ReleaseWorker() { mWorkerRef = nullptr; }

bool WorkerDebuggeeRunnable::PreDispatch(WorkerPrivate* aWorkerPrivate) {
  if (mTarget == ParentThread) {
    RefPtr<StrongWorkerRef> strongRef = StrongWorkerRef::Create(
        aWorkerPrivate, "WorkerDebuggeeRunnable::mSender");
    if (!strongRef) {
      return false;
    }

    mSender = new ThreadSafeWorkerRef(strongRef);
  }

  return WorkerRunnable::PreDispatch(aWorkerPrivate);
}

}  // namespace mozilla::dom