summaryrefslogtreecommitdiffstats
path: root/toolkit/components/bitsdownload/Bits.sys.mjs
blob: 3248d2effaa093160beed189b4c577ca6be605a6 (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
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
/* 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/. */

/**
 * This module is used to interact with the Windows BITS component (Background
 * Intelligent Transfer Service). This functionality cannot be used unless on
 * Windows.
 *
 * The reason for this file's existence is that the interfaces in nsIBits.idl
 * are asynchronous, but are unable to use Promises because they are implemented
 * in Rust, which does not yet support Promises. This file functions as a layer
 * between the Rust and the JS that provides access to the functionality
 * provided by nsIBits via Promises rather than callbacks.
 */

import { AppConstants } from "resource://gre/modules/AppConstants.sys.mjs";
import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";

const lazy = {};

// This conditional prevents errors if this file is imported from operating
// systems other than Windows. This is purely for convenient importing, because
// attempting to use anything in this file on platforms other than Windows will
// result in an error.
if (AppConstants.MOZ_BITS_DOWNLOAD) {
  XPCOMUtils.defineLazyServiceGetter(
    lazy,
    "gBits",
    "@mozilla.org/bits;1",
    "nsIBits"
  );
}

// This value exists to mitigate a very unlikely problem: If a BITS method
// catastrophically fails, it may never call its callback. This would result in
// methods in this file returning promises that never resolve. This could, in
// turn, lead to download code hanging altogether rather than being able to
// report errors and utilize fallback mechanisms.
// This problem is mitigated by giving these promises a timeout, the length of
// which will be determined by this value.
const kBitsMethodTimeoutMs = 10 * 60 * 1000; // 10 minutes

/**
 * This class will wrap the errors returned by the nsIBits interface to make
 * them more uniform and more easily consumable.
 *
 * The values of stored by this error type are entirely numeric. This should
 * make them easier to consume with JS and telemetry, but does make them fairly
 * unreadable. nsIBits.idl will need to be referenced to look up what errors
 * the values correspond to.
 *
 * The type of BitsError.code is dependent on the value of BitsError.codeType.
 * It may be null, a number (corresponding to an nsresult or hresult value),
 * a string, or an exception.
 */
export class BitsError extends Error {
  // If codeType == "none", code may be unspecified.
  constructor(type, action, stage, codeType, code) {
    let message =
      `${BitsError.name} {type: ${type}, action: ${action}, ` +
      `stage: ${stage}`;
    switch (codeType) {
      case lazy.gBits.ERROR_CODE_TYPE_NONE:
        code = null;
        message += ", codeType: none}";
        break;
      case lazy.gBits.ERROR_CODE_TYPE_NSRESULT:
        message += `, codeType: nsresult, code: ${code}}`;
        break;
      case lazy.gBits.ERROR_CODE_TYPE_HRESULT:
        message += `, codeType: hresult, code: ${code}}`;
        break;
      case lazy.gBits.ERROR_CODE_TYPE_STRING:
        message += `, codeType: string, code: ${JSON.stringify(code)}}`;
        break;
      case lazy.gBits.ERROR_CODE_TYPE_EXCEPTION:
        message += `, codeType: exception, code: ${code}}`;
        break;
      default:
        message += ", codeType: invalid}";
        break;
    }
    super(message);

    this.type = type;
    this.action = action;
    this.stage = stage;
    this.codeType = codeType;
    this.code = code;
    this.name = this.constructor.name;
    this.succeeded = false;
  }
}

// These specializations exist to make them easier to construct since they may
// need to be constructed outside of this file.
export class BitsVerificationError extends BitsError {
  constructor() {
    super(
      Ci.nsIBits.ERROR_TYPE_VERIFICATION_FAILURE,
      Ci.nsIBits.ERROR_ACTION_NONE,
      Ci.nsIBits.ERROR_STAGE_VERIFICATION,
      Ci.nsIBits.ERROR_CODE_TYPE_NONE
    );
  }
}

export class BitsUnknownError extends BitsError {
  constructor() {
    super(
      Ci.nsIBits.ERROR_TYPE_UNKNOWN,
      Ci.nsIBits.ERROR_ACTION_UNKNOWN,
      Ci.nsIBits.ERROR_STAGE_UNKNOWN,
      Ci.nsIBits.ERROR_CODE_TYPE_NONE
    );
  }
}

/**
 * Returns a timer object. If the timer expires, reject will be called with
 * a BitsError error. The timer's cancel method should be called if the promise
 * resolves or rejects without the timeout expiring.
 */
function makeTimeout(reject, errorAction) {
  let timer = Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
  timer.initWithCallback(
    () => {
      let error = new BitsError(
        lazy.gBits.ERROR_TYPE_METHOD_TIMEOUT,
        errorAction,
        lazy.gBits.ERROR_STAGE_UNKNOWN,
        lazy.gBits.ERROR_CODE_TYPE_NONE
      );
      reject(error);
    },
    kBitsMethodTimeoutMs,
    Ci.nsITimer.TYPE_ONE_SHOT
  );
  return timer;
}

/**
 * This function does all of the wrapping and error handling for an async
 * BitsRequest method. This allows the implementations for those methods to
 * simply call this function with a closure that executes appropriate
 * nsIBitsRequest method.
 *
 * Specifically, this function takes an nsBitsErrorAction and a function.
 * The nsBitsErrorAction will be used when constructing a BitsError, if the
 * wrapper encounters an error.
 * The function will be passed the callback function that should be passed to
 * the nsIBitsRequest method.
 */
async function requestPromise(errorAction, actionFn) {
  return new Promise((resolve, reject) => {
    let timer = makeTimeout(reject, errorAction);

    let callback = {
      QueryInterface: ChromeUtils.generateQI(["nsIBitsCallback"]),
      success() {
        timer.cancel();
        resolve();
      },
      failure(type, action, stage) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_NONE
        );
        reject(error);
      },
      failureNsresult(type, action, stage, code) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_NSRESULT,
          code
        );
        reject(error);
      },
      failureHresult(type, action, stage, code) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_HRESULT,
          code
        );
        reject(error);
      },
      failureString(type, action, stage, message) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_STRING,
          message
        );
        reject(error);
      },
    };

    try {
      actionFn(callback);
    } catch (e) {
      let error = new BitsError(
        lazy.gBits.ERROR_TYPE_METHOD_THREW,
        errorAction,
        lazy.gBits.ERROR_STAGE_PRETASK,
        lazy.gBits.ERROR_CODE_TYPE_EXCEPTION,
        e
      );
      reject(error);
    }
  });
}

/**
 * This class is a wrapper around nsIBitsRequest that converts functions taking
 * callbacks to asynchronous functions. This class implements nsIRequest.
 *
 * Note that once the request has been shutdown, calling methods on it will
 * cause an exception to be thrown. The request will be shutdown automatically
 * when the BITS job is successfully completed or cancelled. If the request is
 * no longer needed, but the transfer is still in progress, the shutdown method
 * should be called manually to prevent memory leaks.
 * Getter methods (except loadGroup and loadFlags) should continue to be
 * accessible, even after shutdown.
 */
export class BitsRequest {
  constructor(request) {
    this._request = request;
    this._request.QueryInterface(Ci.nsIBitsRequest);
  }

  /**
   * This function releases the Rust request that backs this wrapper. Calling
   * any method on this request after calling release will result in a BitsError
   * being thrown.
   *
   * This step is important, because otherwise a cycle exists that the cycle
   * collector doesn't know about. To break this cycle, either the Rust request
   * needs to let go of the observer, or the JS request wrapper needs to let go
   * of the Rust request (which is what we do here).
   *
   * Once there is support for cycle collection of cycles that extend through
   * Rust, this function may no longer be necessary.
   */
  shutdown() {
    if (this.hasShutdown) {
      return;
    }
    // Cache some values before we shut down so they are still available
    this._name = this._request.name;
    this._status = this._request.status;
    this._bitsId = this._request.bitsId;
    this._transferError = this._request.transferError;

    this._request = null;
  }

  /**
   * Allows consumers to determine if this request has been shutdown.
   */
  get hasShutdown() {
    return !this._request;
  }

  /**
   * This is the nsIRequest implementation. Since this._request is an
   * nsIRequest, these functions just call the corresponding method on it.
   *
   * Note that nsIBitsRequest does not yet properly implement load groups or
   * load flags. This class will still forward those calls, but they will have
   * not succeed.
   */
  get name() {
    if (!this._request) {
      return this._name;
    }
    return this._request.name;
  }
  isPending() {
    if (!this._request) {
      return false;
    }
    return this._request.isPending();
  }
  get status() {
    if (!this._request) {
      return this._status;
    }
    return this._request.status;
  }
  cancel(status) {
    return this.cancelAsync(status);
  }
  suspend() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_SUSPEND,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    return this._request.suspend();
  }
  resume() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_RESUME,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    return this._request.resume();
  }
  get loadGroup() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_NONE,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    return this._request.loadGroup;
  }
  set loadGroup(group) {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_NONE,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    this._request.loadGroup = group;
  }
  get loadFlags() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_NONE,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    return this._request.loadFlags;
  }
  set loadFlags(flags) {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_NONE,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    this._request.loadFlags = flags;
  }

  /**
   * This function wraps nsIBitsRequest::bitsId.
   */
  get bitsId() {
    if (!this._request) {
      return this._bitsId;
    }
    return this._request.bitsId;
  }

  /**
   * This function wraps nsIBitsRequest::transferError.
   *
   * Instead of simply returning the nsBitsErrorType value, however, it returns
   * a BitsError object, or null.
   */
  get transferError() {
    let result;
    if (this._request) {
      result = this._request.transferError;
    } else {
      result = this._transferError;
    }
    if (result == Ci.nsIBits.ERROR_TYPE_SUCCESS) {
      return null;
    }
    return new BitsError(
      result,
      Ci.nsIBits.ERROR_ACTION_NONE,
      Ci.nsIBits.ERROR_STAGE_MONITOR,
      Ci.nsIBits.ERROR_CODE_TYPE_NONE
    );
  }

  /**
   * This function wraps nsIBitsRequest::changeMonitorInterval.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   */
  async changeMonitorInterval(monitorIntervalMs) {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_CHANGE_MONITOR_INTERVAL,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    let action = lazy.gBits.ERROR_ACTION_CHANGE_MONITOR_INTERVAL;
    return requestPromise(action, callback => {
      this._request.changeMonitorInterval(monitorIntervalMs, callback);
    });
  }

  /**
   * This function wraps nsIBitsRequest::cancelAsync.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   *
   * Adds a default status of NS_ERROR_ABORT if one is not provided.
   */
  async cancelAsync(status) {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_CANCEL,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    if (status === undefined) {
      status = Cr.NS_ERROR_ABORT;
    }
    let action = lazy.gBits.ERROR_ACTION_CANCEL;
    return requestPromise(action, callback => {
      this._request.cancelAsync(status, callback);
    }).then(() => this.shutdown());
  }

  /**
   * This function wraps nsIBitsRequest::setPriorityHigh.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   */
  async setPriorityHigh() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_SET_PRIORITY,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    let action = lazy.gBits.ERROR_ACTION_SET_PRIORITY;
    return requestPromise(action, callback => {
      this._request.setPriorityHigh(callback);
    });
  }

  /**
   * This function wraps nsIBitsRequest::setPriorityLow.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   */
  async setPriorityLow() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_SET_PRIORITY,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    let action = lazy.gBits.ERROR_ACTION_SET_PRIORITY;
    return requestPromise(action, callback => {
      this._request.setPriorityLow(callback);
    });
  }

  /**
   * This function wraps nsIBitsRequest::setNoProgressTimeout.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   */
  async setNoProgressTimeout(timeoutSecs) {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_SET_NO_PROGRESS_TIMEOUT,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    let action = lazy.gBits.ERROR_ACTION_SET_NO_PROGRESS_TIMEOUT;
    return requestPromise(action, callback => {
      this._request.setNoProgressTimeout(timeoutSecs, callback);
    });
  }

  /**
   * This function wraps nsIBitsRequest::complete.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   */
  async complete() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_COMPLETE,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    let action = lazy.gBits.ERROR_ACTION_COMPLETE;
    return requestPromise(action, callback => {
      this._request.complete(callback);
    }).then(() => this.shutdown());
  }

  /**
   * This function wraps nsIBitsRequest::suspendAsync.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   */
  async suspendAsync() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_SUSPEND,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    let action = lazy.gBits.ERROR_ACTION_SUSPEND;
    return requestPromise(action, callback => {
      this._request.suspendAsync(callback);
    });
  }

  /**
   * This function wraps nsIBitsRequest::resumeAsync.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with no data, or rejects with a BitsError.
   */
  async resumeAsync() {
    if (!this._request) {
      throw new BitsError(
        Ci.nsIBits.ERROR_TYPE_USE_AFTER_REQUEST_SHUTDOWN,
        Ci.nsIBits.ERROR_ACTION_RESUME,
        Ci.nsIBits.ERROR_STAGE_PRETASK,
        Ci.nsIBits.ERROR_CODE_TYPE_NONE
      );
    }
    let action = lazy.gBits.ERROR_ACTION_RESUME;
    return requestPromise(action, callback => {
      this._request.resumeAsync(callback);
    });
  }
}

BitsRequest.prototype.QueryInterface = ChromeUtils.generateQI(["nsIRequest"]);

/**
 * This function does all of the wrapping and error handling for an async
 * Bits Service method. This allows the implementations for those methods to
 * simply call this function with a closure that executes appropriate
 * nsIBits method.
 *
 * Specifically, this function takes an nsBitsErrorAction, an observer and a
 * function.
 * The nsBitsErrorAction will be used when constructing a BitsError, if the
 * wrapper encounters an error.
 * The observer should be the one that the caller passed to the Bits Interface
 * method. It will be wrapped so that its methods are passed a BitsRequest
 * rather than an nsIBitsRequest.
 * The function will be passed the callback function and the wrapped observer,
 * both of which should be passed to the nsIBitsRequest method.
 */
async function servicePromise(errorAction, observer, actionFn) {
  return new Promise((resolve, reject) => {
    if (!observer) {
      let error = new BitsError(
        lazy.gBits.ERROR_TYPE_NULL_ARGUMENT,
        errorAction,
        lazy.gBits.ERROR_STAGE_PRETASK,
        lazy.gBits.ERROR_CODE_TYPE_NONE
      );
      reject(error);
      return;
    }
    try {
      observer.QueryInterface(Ci.nsIRequestObserver);
    } catch (e) {
      let error = new BitsError(
        lazy.gBits.ERROR_TYPE_INVALID_ARGUMENT,
        errorAction,
        lazy.gBits.ERROR_STAGE_PRETASK,
        lazy.gBits.ERROR_CODE_TYPE_EXCEPTION,
        e
      );
      reject(error);
      return;
    }
    let isProgressEventSink = false;
    try {
      observer.QueryInterface(Ci.nsIProgressEventSink);
      isProgressEventSink = true;
    } catch (e) {}

    // Check if we are not late in creating new requests.
    if (
      Services &&
      Services.startup &&
      Services.startup.isInOrBeyondShutdownPhase(
        Ci.nsIAppStartup.SHUTDOWN_PHASE_APPSHUTDOWNCONFIRMED
      )
    ) {
      let error = new BitsError(
        lazy.gBits.ERROR_TYPE_BROWSER_SHUTTING_DOWN,
        errorAction,
        lazy.gBits.ERROR_STAGE_PRETASK,
        lazy.gBits.ERROR_CODE_TYPE_NONE
      );
      reject(error);
      return;
    }

    // This will be set to the BitsRequest (wrapping the nsIBitsRequest), once
    // it is available. This prevents a new wrapper from having to be made every
    // time an observer function is called.
    let wrappedRequest;

    let wrappedObserver = {
      onStartRequest: function wrappedObserver_onStartRequest(request) {
        if (!wrappedRequest) {
          wrappedRequest = new BitsRequest(request);
        }
        observer.onStartRequest(wrappedRequest);
      },
      onStopRequest: function wrappedObserver_onStopRequest(request, status) {
        if (!wrappedRequest) {
          wrappedRequest = new BitsRequest(request);
        }
        observer.onStopRequest(wrappedRequest, status);
      },
      onProgress: function wrappedObserver_onProgress(
        request,
        progress,
        progressMax
      ) {
        if (isProgressEventSink) {
          if (!wrappedRequest) {
            wrappedRequest = new BitsRequest(request);
          }
          observer.onProgress(wrappedRequest, progress, progressMax);
        }
      },
      onStatus: function wrappedObserver_onStatus(request, status, statusArg) {
        if (isProgressEventSink) {
          if (!wrappedRequest) {
            wrappedRequest = new BitsRequest(request);
          }
          observer.onStatus(wrappedRequest, status, statusArg);
        }
      },
      QueryInterface: ChromeUtils.generateQI([
        "nsIRequestObserver",
        "nsIProgressEventSink",
      ]),
    };

    let timer = makeTimeout(reject, errorAction);
    let callback = {
      QueryInterface: ChromeUtils.generateQI(["nsIBitsNewRequestCallback"]),
      success(request) {
        timer.cancel();
        if (!wrappedRequest) {
          wrappedRequest = new BitsRequest(request);
        }
        resolve(wrappedRequest);
      },
      failure(type, action, stage) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_NONE
        );
        reject(error);
      },
      failureNsresult(type, action, stage, code) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_NSRESULT,
          code
        );
        reject(error);
      },
      failureHresult(type, action, stage, code) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_HRESULT,
          code
        );
        reject(error);
      },
      failureString(type, action, stage, message) {
        timer.cancel();
        let error = new BitsError(
          type,
          action,
          stage,
          lazy.gBits.ERROR_CODE_TYPE_STRING,
          message
        );
        reject(error);
      },
    };

    try {
      actionFn(wrappedObserver, callback);
    } catch (e) {
      let error = new BitsError(
        lazy.gBits.ERROR_TYPE_METHOD_THREW,
        errorAction,
        lazy.gBits.ERROR_STAGE_PRETASK,
        lazy.gBits.ERROR_CODE_TYPE_EXCEPTION,
        e
      );
      reject(error);
    }
  });
}

export var Bits = {
  /**
   * This function wraps nsIBits::initialized.
   */
  get initialized() {
    return lazy.gBits.initialized;
  },

  /**
   * This function wraps nsIBits::init.
   */
  init(jobName, savePathPrefix, monitorTimeoutMs) {
    return lazy.gBits.init(jobName, savePathPrefix, monitorTimeoutMs);
  },

  /**
   * This function wraps nsIBits::startDownload.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with a BitsRequest (which is also an
   * nsIRequest), or rejects with a BitsError.
   */
  async startDownload(
    downloadURL,
    saveRelPath,
    proxy,
    noProgressTimeoutSecs,
    monitorIntervalMs,
    observer,
    context
  ) {
    let action = lazy.gBits.ERROR_ACTION_START_DOWNLOAD;
    return servicePromise(action, observer, (wrappedObserver, callback) => {
      lazy.gBits.startDownload(
        downloadURL,
        saveRelPath,
        proxy,
        noProgressTimeoutSecs,
        monitorIntervalMs,
        wrappedObserver,
        context,
        callback
      );
    });
  },

  /**
   * This function wraps nsIBits::monitorDownload.
   *
   * Instead of taking a callback, the function is asynchronous.
   * This method either resolves with a BitsRequest (which is also an
   * nsIRequest), or rejects with a BitsError.
   */
  async monitorDownload(id, monitorIntervalMs, observer, context) {
    let action = lazy.gBits.ERROR_ACTION_MONITOR_DOWNLOAD;
    return servicePromise(action, observer, (wrappedObserver, callback) => {
      lazy.gBits.monitorDownload(
        id,
        monitorIntervalMs,
        wrappedObserver,
        context,
        callback
      );
    });
  },
};