services/settings/RemoteSettingsWorker.jsm
author Dorel Luca <dluca@mozilla.com>
Sat, 20 Apr 2019 00:46:59 +0300
changeset 470285 b330e84e1458ac4e11343638f622329a48bb952b
parent 456101 73a91e84dbec4fe4cd6881c0bdb377f7b0137e42
child 473088 7e1942ace2b27c0905642f3c2ea83c848ba947b1
permissions -rw-r--r--
Merge mozilla-central to inbound

/* 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/. */

"use strict";

/**
 * Interface to a dedicated thread handling for Remote Settings heavy operations.
 */

// ChromeUtils.import("resource://gre/modules/PromiseWorker.jsm", this);

var EXPORTED_SYMBOLS = ["RemoteSettingsWorker"];

class Worker {
  constructor(source) {
    this.worker = new ChromeWorker(source);
    this.worker.onmessage = this._onWorkerMessage.bind(this);

    this.callbacks = new Map();
    this.lastCallbackId = 0;
  }

  async _execute(method, args = []) {
    return new Promise(async (resolve, reject) => {
      const callbackId = ++this.lastCallbackId;
      this.callbacks.set(callbackId, [resolve, reject]);
      this.worker.postMessage({ callbackId, method, args });
    });
  }

  _onWorkerMessage(event) {
    const { callbackId, result, error } = event.data;
    const [resolve, reject] = this.callbacks.get(callbackId);
    if (error) {
      reject(new Error(error));
    } else {
      resolve(result);
    }
    this.callbacks.delete(callbackId);
  }

  async canonicalStringify(localRecords, remoteRecords, timestamp) {
    return this._execute("canonicalStringify", [localRecords, remoteRecords, timestamp]);
  }

  async importJSONDump(bucket, collection) {
    return this._execute("importJSONDump", [bucket, collection]);
  }
}

var RemoteSettingsWorker = new Worker("resource://services-settings/RemoteSettingsWorker.js");