File: FetchConsumer.cpp

package info (click to toggle)
thunderbird 1:60.8.0-1~deb9u1
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 2,339,208 kB
  • sloc: cpp: 5,456,704; ansic: 2,360,384; python: 596,095; asm: 340,963; java: 326,291; xml: 258,664; sh: 84,366; makefile: 23,702; perl: 17,317; objc: 3,768; yacc: 1,766; ada: 1,681; lex: 1,364; pascal: 1,264; cs: 879; exp: 527; php: 436; lisp: 258; ruby: 153; awk: 152; sed: 53; csh: 27
file content (736 lines) | stat: -rw-r--r-- 22,040 bytes parent folder | download | duplicates (7)
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
/* -*- 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 "Fetch.h"
#include "FetchConsumer.h"

#include "mozilla/dom/WorkerCommon.h"
#include "mozilla/dom/WorkerPrivate.h"
#include "mozilla/dom/WorkerRunnable.h"
#include "mozilla/dom/WorkerScope.h"
#include "mozilla/ipc/PBackgroundSharedTypes.h"
#include "nsIInputStreamPump.h"
#include "nsIThreadRetargetableRequest.h"
#include "nsProxyRelease.h"

namespace mozilla {
namespace dom {

namespace {

template <class Derived>
class FetchBodyWorkerHolder final : public WorkerHolder {
  RefPtr<FetchBodyConsumer<Derived>> mConsumer;
  bool mWasNotified;

 public:
  explicit FetchBodyWorkerHolder(FetchBodyConsumer<Derived>* aConsumer)
      : WorkerHolder("FetchBodyWorkerHolder"),
        mConsumer(aConsumer),
        mWasNotified(false) {
    MOZ_ASSERT(aConsumer);
  }

  ~FetchBodyWorkerHolder() = default;

  bool Notify(WorkerStatus aStatus) override {
    MOZ_ASSERT(aStatus > Running);
    if (!mWasNotified) {
      mWasNotified = true;
      mConsumer->ShutDownMainThreadConsuming();
    }

    return true;
  }
};

template <class Derived>
class BeginConsumeBodyRunnable final : public Runnable {
  RefPtr<FetchBodyConsumer<Derived>> mFetchBodyConsumer;

 public:
  explicit BeginConsumeBodyRunnable(FetchBodyConsumer<Derived>* aConsumer)
      : Runnable("BeginConsumeBodyRunnable"), mFetchBodyConsumer(aConsumer) {}

  NS_IMETHOD
  Run() override {
    mFetchBodyConsumer->BeginConsumeBodyMainThread();
    return NS_OK;
  }
};

/*
 * Called on successfully reading the complete stream.
 */
template <class Derived>
class ContinueConsumeBodyRunnable final : public MainThreadWorkerRunnable {
  RefPtr<FetchBodyConsumer<Derived>> mFetchBodyConsumer;
  nsresult mStatus;
  uint32_t mLength;
  uint8_t* mResult;

 public:
  ContinueConsumeBodyRunnable(FetchBodyConsumer<Derived>* aFetchBodyConsumer,
                              nsresult aStatus, uint32_t aLength,
                              uint8_t* aResult)
      : MainThreadWorkerRunnable(aFetchBodyConsumer->GetWorkerPrivate()),
        mFetchBodyConsumer(aFetchBodyConsumer),
        mStatus(aStatus),
        mLength(aLength),
        mResult(aResult) {
    MOZ_ASSERT(NS_IsMainThread());
  }

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    mFetchBodyConsumer->ContinueConsumeBody(mStatus, mLength, mResult);
    return true;
  }
};

// ControlRunnable used to complete the releasing of resources on the worker
// thread when already shutting down.
template <class Derived>
class ContinueConsumeBodyControlRunnable final
    : public MainThreadWorkerControlRunnable {
  RefPtr<FetchBodyConsumer<Derived>> mFetchBodyConsumer;

 public:
  explicit ContinueConsumeBodyControlRunnable(
      FetchBodyConsumer<Derived>* aFetchBodyConsumer)
      : MainThreadWorkerControlRunnable(aFetchBodyConsumer->GetWorkerPrivate()),
        mFetchBodyConsumer(aFetchBodyConsumer) {
    MOZ_ASSERT(NS_IsMainThread());
  }

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    mFetchBodyConsumer->ContinueConsumeBody(NS_BINDING_ABORTED, 0, nullptr,
                                            true /* shutting down */);
    return true;
  }
};

template <class Derived>
class FailConsumeBodyWorkerRunnable : public MainThreadWorkerControlRunnable {
  RefPtr<FetchBodyConsumer<Derived>> mBodyConsumer;

 public:
  explicit FailConsumeBodyWorkerRunnable(
      FetchBodyConsumer<Derived>* aBodyConsumer)
      : MainThreadWorkerControlRunnable(aBodyConsumer->GetWorkerPrivate()),
        mBodyConsumer(aBodyConsumer) {
    AssertIsOnMainThread();
  }

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    mBodyConsumer->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr);
    return true;
  }
};

/*
 * In case of failure to create a stream pump or dispatch stream completion to
 * worker, ensure we cleanup properly. Thread agnostic.
 */
template <class Derived>
class MOZ_STACK_CLASS AutoFailConsumeBody final {
  RefPtr<FetchBodyConsumer<Derived>> mBodyConsumer;

 public:
  explicit AutoFailConsumeBody(FetchBodyConsumer<Derived>* aBodyConsumer)
      : mBodyConsumer(aBodyConsumer) {}

  ~AutoFailConsumeBody() {
    AssertIsOnMainThread();

    if (mBodyConsumer) {
      if (mBodyConsumer->GetWorkerPrivate()) {
        RefPtr<FailConsumeBodyWorkerRunnable<Derived>> r =
            new FailConsumeBodyWorkerRunnable<Derived>(mBodyConsumer);
        if (!r->Dispatch()) {
          MOZ_CRASH("We are going to leak");
        }
      } else {
        mBodyConsumer->ContinueConsumeBody(NS_ERROR_FAILURE, 0, nullptr);
      }
    }
  }

  void DontFail() { mBodyConsumer = nullptr; }
};

/*
 * Called on successfully reading the complete stream for Blob.
 */
template <class Derived>
class ContinueConsumeBlobBodyRunnable final : public MainThreadWorkerRunnable {
  RefPtr<FetchBodyConsumer<Derived>> mFetchBodyConsumer;
  RefPtr<BlobImpl> mBlobImpl;

 public:
  ContinueConsumeBlobBodyRunnable(
      FetchBodyConsumer<Derived>* aFetchBodyConsumer, BlobImpl* aBlobImpl)
      : MainThreadWorkerRunnable(aFetchBodyConsumer->GetWorkerPrivate()),
        mFetchBodyConsumer(aFetchBodyConsumer),
        mBlobImpl(aBlobImpl) {
    MOZ_ASSERT(NS_IsMainThread());
    MOZ_ASSERT(mBlobImpl);
  }

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    mFetchBodyConsumer->ContinueConsumeBlobBody(mBlobImpl);
    return true;
  }
};

// ControlRunnable used to complete the releasing of resources on the worker
// thread when already shutting down.
template <class Derived>
class ContinueConsumeBlobBodyControlRunnable final
    : public MainThreadWorkerControlRunnable {
  RefPtr<FetchBodyConsumer<Derived>> mFetchBodyConsumer;

 public:
  explicit ContinueConsumeBlobBodyControlRunnable(
      FetchBodyConsumer<Derived>* aFetchBodyConsumer)
      : MainThreadWorkerControlRunnable(aFetchBodyConsumer->GetWorkerPrivate()),
        mFetchBodyConsumer(aFetchBodyConsumer) {
    MOZ_ASSERT(NS_IsMainThread());
  }

  bool WorkerRun(JSContext* aCx, WorkerPrivate* aWorkerPrivate) override {
    mFetchBodyConsumer->ContinueConsumeBlobBody(nullptr,
                                                true /* shutting down */);
    return true;
  }
};

template <class Derived>
class ConsumeBodyDoneObserver : public nsIStreamLoaderObserver,
                                public MutableBlobStorageCallback {
  RefPtr<FetchBodyConsumer<Derived>> mFetchBodyConsumer;

 public:
  NS_DECL_THREADSAFE_ISUPPORTS

  explicit ConsumeBodyDoneObserver(
      FetchBodyConsumer<Derived>* aFetchBodyConsumer)
      : mFetchBodyConsumer(aFetchBodyConsumer) {}

  NS_IMETHOD
  OnStreamComplete(nsIStreamLoader* aLoader, nsISupports* aCtxt,
                   nsresult aStatus, uint32_t aResultLength,
                   const uint8_t* aResult) override {
    MOZ_ASSERT(NS_IsMainThread());

    // The loading is completed. Let's nullify the pump before continuing the
    // consuming of the body.
    mFetchBodyConsumer->NullifyConsumeBodyPump();

    uint8_t* nonconstResult = const_cast<uint8_t*>(aResult);
    if (!mFetchBodyConsumer->GetWorkerPrivate()) {
      mFetchBodyConsumer->ContinueConsumeBody(aStatus, aResultLength,
                                              nonconstResult);
      // FetchBody is responsible for data.
      return NS_SUCCESS_ADOPTED_DATA;
    }

    {
      RefPtr<ContinueConsumeBodyRunnable<Derived>> r =
          new ContinueConsumeBodyRunnable<Derived>(
              mFetchBodyConsumer, aStatus, aResultLength, nonconstResult);
      if (r->Dispatch()) {
        // FetchBody is responsible for data.
        return NS_SUCCESS_ADOPTED_DATA;
      }
    }

    // The worker is shutting down. Let's use a control runnable to complete the
    // shutting down procedure.

    RefPtr<ContinueConsumeBodyControlRunnable<Derived>> r =
        new ContinueConsumeBodyControlRunnable<Derived>(mFetchBodyConsumer);
    if (NS_WARN_IF(!r->Dispatch())) {
      return NS_ERROR_FAILURE;
    }

    return NS_OK;
  }

  virtual void BlobStoreCompleted(MutableBlobStorage* aBlobStorage, Blob* aBlob,
                                  nsresult aRv) override {
    // On error.
    if (NS_FAILED(aRv)) {
      OnStreamComplete(nullptr, nullptr, aRv, 0, nullptr);
      return;
    }

    // The loading is completed. Let's nullify the pump before continuing the
    // consuming of the body.
    mFetchBodyConsumer->NullifyConsumeBodyPump();

    MOZ_ASSERT(aBlob);

    if (!mFetchBodyConsumer->GetWorkerPrivate()) {
      mFetchBodyConsumer->ContinueConsumeBlobBody(aBlob->Impl());
      return;
    }

    {
      RefPtr<ContinueConsumeBlobBodyRunnable<Derived>> r =
          new ContinueConsumeBlobBodyRunnable<Derived>(mFetchBodyConsumer,
                                                       aBlob->Impl());

      if (r->Dispatch()) {
        return;
      }
    }

    // The worker is shutting down. Let's use a control runnable to complete the
    // shutting down procedure.

    RefPtr<ContinueConsumeBlobBodyControlRunnable<Derived>> r =
        new ContinueConsumeBlobBodyControlRunnable<Derived>(mFetchBodyConsumer);

    Unused << NS_WARN_IF(!r->Dispatch());
  }

 private:
  virtual ~ConsumeBodyDoneObserver() {}
};

template <class Derived>
NS_IMPL_ADDREF(ConsumeBodyDoneObserver<Derived>)
template <class Derived>
NS_IMPL_RELEASE(ConsumeBodyDoneObserver<Derived>)
template <class Derived>
NS_INTERFACE_MAP_BEGIN(ConsumeBodyDoneObserver<Derived>)
NS_INTERFACE_MAP_ENTRY(nsIStreamLoaderObserver)
    NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, nsIStreamLoaderObserver)
NS_INTERFACE_MAP_END

}  // anonymous

template <class Derived>
/* static */ already_AddRefed<Promise> FetchBodyConsumer<Derived>::Create(
    nsIGlobalObject* aGlobal, nsIEventTarget* aMainThreadEventTarget,
    FetchBody<Derived>* aBody, AbortSignal* aSignal, FetchConsumeType aType,
    ErrorResult& aRv) {
  MOZ_ASSERT(aBody);
  MOZ_ASSERT(aMainThreadEventTarget);

  nsCOMPtr<nsIInputStream> bodyStream;
  aBody->DerivedClass()->GetBody(getter_AddRefs(bodyStream));
  if (!bodyStream) {
    aRv = NS_NewCStringInputStream(getter_AddRefs(bodyStream), EmptyCString());
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  }

  RefPtr<Promise> promise = Promise::Create(aGlobal, aRv);
  if (aRv.Failed()) {
    return nullptr;
  }

  WorkerPrivate* workerPrivate = nullptr;
  if (!NS_IsMainThread()) {
    workerPrivate = GetCurrentThreadWorkerPrivate();
    MOZ_ASSERT(workerPrivate);
  }

  RefPtr<FetchBodyConsumer<Derived>> consumer = new FetchBodyConsumer<Derived>(
      aMainThreadEventTarget, aGlobal, workerPrivate, aBody, bodyStream,
      promise, aType);

  if (!NS_IsMainThread()) {
    MOZ_ASSERT(workerPrivate);
    if (NS_WARN_IF(!consumer->RegisterWorkerHolder())) {
      aRv.Throw(NS_ERROR_FAILURE);
      return nullptr;
    }
  } else {
    nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
    if (NS_WARN_IF(!os)) {
      aRv.Throw(NS_ERROR_FAILURE);
      return nullptr;
    }

    aRv = os->AddObserver(consumer, DOM_WINDOW_DESTROYED_TOPIC, true);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }

    aRv = os->AddObserver(consumer, DOM_WINDOW_FROZEN_TOPIC, true);
    if (NS_WARN_IF(aRv.Failed())) {
      return nullptr;
    }
  }

  nsCOMPtr<nsIRunnable> r = new BeginConsumeBodyRunnable<Derived>(consumer);
  aRv = aMainThreadEventTarget->Dispatch(r.forget(), NS_DISPATCH_NORMAL);
  if (NS_WARN_IF(aRv.Failed())) {
    return nullptr;
  }

  if (aSignal) {
    consumer->Follow(aSignal);
  }

  return promise.forget();
}

template <class Derived>
void FetchBodyConsumer<Derived>::ReleaseObject() {
  AssertIsOnTargetThread();

  if (NS_IsMainThread()) {
    nsCOMPtr<nsIObserverService> os = mozilla::services::GetObserverService();
    if (os) {
      os->RemoveObserver(this, DOM_WINDOW_DESTROYED_TOPIC);
      os->RemoveObserver(this, DOM_WINDOW_FROZEN_TOPIC);
    }
  }

  mGlobal = nullptr;
  mWorkerHolder = nullptr;

#ifdef DEBUG
  mBody = nullptr;
#endif

  Unfollow();
}

template <class Derived>
FetchBodyConsumer<Derived>::FetchBodyConsumer(
    nsIEventTarget* aMainThreadEventTarget, nsIGlobalObject* aGlobalObject,
    WorkerPrivate* aWorkerPrivate, FetchBody<Derived>* aBody,
    nsIInputStream* aBodyStream, Promise* aPromise, FetchConsumeType aType)
    : mTargetThread(NS_GetCurrentThread()),
      mMainThreadEventTarget(aMainThreadEventTarget)
#ifdef DEBUG
      ,
      mBody(aBody)
#endif
      ,
      mBodyStream(aBodyStream),
      mBlobStorageType(MutableBlobStorage::eOnlyInMemory),
      mGlobal(aGlobalObject),
      mWorkerPrivate(aWorkerPrivate),
      mConsumeType(aType),
      mConsumePromise(aPromise),
      mBodyConsumed(false),
      mShuttingDown(false) {
  MOZ_ASSERT(aMainThreadEventTarget);
  MOZ_ASSERT(aBody);
  MOZ_ASSERT(aBodyStream);
  MOZ_ASSERT(aPromise);

  const mozilla::UniquePtr<mozilla::ipc::PrincipalInfo>& principalInfo =
      aBody->DerivedClass()->GetPrincipalInfo();
  // We support temporary file for blobs only if the principal is known and
  // it's system or content not in private Browsing.
  if (principalInfo &&
      (principalInfo->type() ==
           mozilla::ipc::PrincipalInfo::TSystemPrincipalInfo ||
       (principalInfo->type() ==
            mozilla::ipc::PrincipalInfo::TContentPrincipalInfo &&
        principalInfo->get_ContentPrincipalInfo().attrs().mPrivateBrowsingId ==
            0))) {
    mBlobStorageType = MutableBlobStorage::eCouldBeInTemporaryFile;
  }

  mBodyMimeType = aBody->MimeType();
}

template <class Derived>
FetchBodyConsumer<Derived>::~FetchBodyConsumer() {}

template <class Derived>
void FetchBodyConsumer<Derived>::AssertIsOnTargetThread() const {
  MOZ_ASSERT(NS_GetCurrentThread() == mTargetThread);
}

template <class Derived>
bool FetchBodyConsumer<Derived>::RegisterWorkerHolder() {
  MOZ_ASSERT(mWorkerPrivate);
  mWorkerPrivate->AssertIsOnWorkerThread();

  MOZ_ASSERT(!mWorkerHolder);
  mWorkerHolder.reset(new FetchBodyWorkerHolder<Derived>(this));

  if (!mWorkerHolder->HoldWorker(mWorkerPrivate, Closing)) {
    NS_WARNING("Failed to add workerHolder");
    mWorkerHolder = nullptr;
    return false;
  }

  return true;
}

/*
 * BeginConsumeBodyMainThread() will automatically reject the consume promise
 * and clean up on any failures, so there is no need for callers to do so,
 * reflected in a lack of error return code.
 */
template <class Derived>
void FetchBodyConsumer<Derived>::BeginConsumeBodyMainThread() {
  AssertIsOnMainThread();

  AutoFailConsumeBody<Derived> autoReject(this);

  if (mShuttingDown) {
    // We haven't started yet, but we have been terminated. AutoFailConsumeBody
    // will dispatch a runnable to release resources.
    return;
  }

  nsCOMPtr<nsIInputStreamPump> pump;
  nsresult rv =
      NS_NewInputStreamPump(getter_AddRefs(pump), mBodyStream.forget(), 0, 0,
                            false, mMainThreadEventTarget);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  RefPtr<ConsumeBodyDoneObserver<Derived>> p =
      new ConsumeBodyDoneObserver<Derived>(this);

  nsCOMPtr<nsIStreamListener> listener;
  if (mConsumeType == CONSUME_BLOB) {
    listener = new MutableBlobStreamListener(
        mBlobStorageType, nullptr, mBodyMimeType, p, mMainThreadEventTarget);
  } else {
    nsCOMPtr<nsIStreamLoader> loader;
    rv = NS_NewStreamLoader(getter_AddRefs(loader), p);
    if (NS_WARN_IF(NS_FAILED(rv))) {
      return;
    }

    listener = loader;
  }

  rv = pump->AsyncRead(listener, nullptr);
  if (NS_WARN_IF(NS_FAILED(rv))) {
    return;
  }

  // Now that everything succeeded, we can assign the pump to a pointer that
  // stays alive for the lifetime of the FetchConsumer.
  mConsumeBodyPump = pump;

  // It is ok for retargeting to fail and reads to happen on the main thread.
  autoReject.DontFail();

  // Try to retarget, otherwise fall back to main thread.
  nsCOMPtr<nsIThreadRetargetableRequest> rr = do_QueryInterface(pump);
  if (rr) {
    nsCOMPtr<nsIEventTarget> sts =
        do_GetService(NS_STREAMTRANSPORTSERVICE_CONTRACTID);
    rv = rr->RetargetDeliveryTo(sts);
    if (NS_FAILED(rv)) {
      NS_WARNING("Retargeting failed");
    }
  }
}

template <class Derived>
void FetchBodyConsumer<Derived>::ContinueConsumeBody(nsresult aStatus,
                                                     uint32_t aResultLength,
                                                     uint8_t* aResult,
                                                     bool aShuttingDown) {
  AssertIsOnTargetThread();

  if (mBodyConsumed) {
    return;
  }
  mBodyConsumed = true;

  // Just a precaution to ensure ContinueConsumeBody is not called out of
  // sync with a body read.
  MOZ_ASSERT(mBody->BodyUsed());

  auto autoFree = mozilla::MakeScopeExit([&] { free(aResult); });

  MOZ_ASSERT(mConsumePromise);
  RefPtr<Promise> localPromise = mConsumePromise.forget();

  RefPtr<FetchBodyConsumer<Derived>> self = this;
  auto autoReleaseObject =
      mozilla::MakeScopeExit([&] { self->ReleaseObject(); });

  if (aShuttingDown) {
    // If shutting down, we don't want to resolve any promise.
    return;
  }

  if (NS_WARN_IF(NS_FAILED(aStatus))) {
    localPromise->MaybeReject(NS_ERROR_DOM_ABORT_ERR);
  }

  // Don't warn here since we warned above.
  if (NS_FAILED(aStatus)) {
    return;
  }

  // Finish successfully consuming body according to type.
  MOZ_ASSERT(aResult);

  AutoJSAPI jsapi;
  if (!jsapi.Init(mGlobal)) {
    localPromise->MaybeReject(NS_ERROR_UNEXPECTED);
    return;
  }

  JSContext* cx = jsapi.cx();
  ErrorResult error;

  switch (mConsumeType) {
    case CONSUME_ARRAYBUFFER: {
      JS::Rooted<JSObject*> arrayBuffer(cx);
      BodyUtil::ConsumeArrayBuffer(cx, &arrayBuffer, aResultLength, aResult,
                                   error);

      if (!error.Failed()) {
        JS::Rooted<JS::Value> val(cx);
        val.setObjectOrNull(arrayBuffer);

        localPromise->MaybeResolve(cx, val);
        // ArrayBuffer takes over ownership.
        aResult = nullptr;
      }
      break;
    }
    case CONSUME_BLOB: {
      MOZ_CRASH("This should not happen.");
      break;
    }
    case CONSUME_FORMDATA: {
      nsCString data;
      data.Adopt(reinterpret_cast<char*>(aResult), aResultLength);
      aResult = nullptr;

      RefPtr<dom::FormData> fd =
          BodyUtil::ConsumeFormData(mGlobal, mBodyMimeType, data, error);
      if (!error.Failed()) {
        localPromise->MaybeResolve(fd);
      }
      break;
    }
    case CONSUME_TEXT:
      // fall through handles early exit.
    case CONSUME_JSON: {
      nsString decoded;
      if (NS_SUCCEEDED(
              BodyUtil::ConsumeText(aResultLength, aResult, decoded))) {
        if (mConsumeType == CONSUME_TEXT) {
          localPromise->MaybeResolve(decoded);
        } else {
          JS::Rooted<JS::Value> json(cx);
          BodyUtil::ConsumeJson(cx, &json, decoded, error);
          if (!error.Failed()) {
            localPromise->MaybeResolve(cx, json);
          }
        }
      };
      break;
    }
    default:
      NS_NOTREACHED("Unexpected consume body type");
  }

  error.WouldReportJSException();
  if (error.Failed()) {
    localPromise->MaybeReject(error);
  }
}

template <class Derived>
void FetchBodyConsumer<Derived>::ContinueConsumeBlobBody(BlobImpl* aBlobImpl,
                                                         bool aShuttingDown) {
  AssertIsOnTargetThread();
  MOZ_ASSERT(mConsumeType == CONSUME_BLOB);

  if (mBodyConsumed) {
    return;
  }
  mBodyConsumed = true;

  // Just a precaution to ensure ContinueConsumeBody is not called out of
  // sync with a body read.
  MOZ_ASSERT(mBody->BodyUsed());

  if (!aShuttingDown) {
    MOZ_ASSERT(mConsumePromise);
    RefPtr<Promise> localPromise = mConsumePromise.forget();

    RefPtr<dom::Blob> blob = dom::Blob::Create(mGlobal, aBlobImpl);
    MOZ_ASSERT(blob);

    localPromise->MaybeResolve(blob);
  }

  ReleaseObject();
}

template <class Derived>
void FetchBodyConsumer<Derived>::ShutDownMainThreadConsuming() {
  if (!NS_IsMainThread()) {
    RefPtr<FetchBodyConsumer<Derived>> self = this;

    nsCOMPtr<nsIRunnable> r = NS_NewRunnableFunction(
        "FetchBodyConsumer::ShutDownMainThreadConsuming",
        [self]() { self->ShutDownMainThreadConsuming(); });

    mMainThreadEventTarget->Dispatch(r.forget(), NS_DISPATCH_NORMAL);
    return;
  }

  // We need this because maybe, mConsumeBodyPump has not been created yet. We
  // must be sure that we don't try to do it.
  mShuttingDown = true;

  if (mConsumeBodyPump) {
    mConsumeBodyPump->Cancel(NS_BINDING_ABORTED);
    mConsumeBodyPump = nullptr;
  }
}

template <class Derived>
NS_IMETHODIMP FetchBodyConsumer<Derived>::Observe(nsISupports* aSubject,
                                                  const char* aTopic,
                                                  const char16_t* aData) {
  AssertIsOnMainThread();

  MOZ_ASSERT((strcmp(aTopic, DOM_WINDOW_FROZEN_TOPIC) == 0) ||
             (strcmp(aTopic, DOM_WINDOW_DESTROYED_TOPIC) == 0));

  nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(mGlobal);
  if (SameCOMIdentity(aSubject, window)) {
    ContinueConsumeBody(NS_BINDING_ABORTED, 0, nullptr);
  }

  return NS_OK;
}

template <class Derived>
void FetchBodyConsumer<Derived>::Abort() {
  AssertIsOnTargetThread();
  ContinueConsumeBody(NS_ERROR_DOM_ABORT_ERR, 0, nullptr);
}

template <class Derived>
NS_IMPL_ADDREF(FetchBodyConsumer<Derived>)

template <class Derived>
NS_IMPL_RELEASE(FetchBodyConsumer<Derived>)

template <class Derived>
NS_IMPL_QUERY_INTERFACE(FetchBodyConsumer<Derived>, nsIObserver,
                        nsISupportsWeakReference)

}  // namespace dom
}  // namespace mozilla