gecko-dev/services/settings/Utils.jsm

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

128 lines
4.6 KiB
JavaScript
Raw Normal View History

/* 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/. */
var EXPORTED_SYMBOLS = [
"Utils",
];
Bug 1514594: Part 3 - Change ChromeUtils.import API. *** Bug 1514594: Part 3a - Change ChromeUtils.import to return an exports object; not pollute global. r=mccr8 This changes the behavior of ChromeUtils.import() to return an exports object, rather than a module global, in all cases except when `null` is passed as a second argument, and changes the default behavior not to pollute the global scope with the module's exports. Thus, the following code written for the old model: ChromeUtils.import("resource://gre/modules/Services.jsm"); is approximately the same as the following, in the new model: var {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm"); Since the two behaviors are mutually incompatible, this patch will land with a scripted rewrite to update all existing callers to use the new model rather than the old. *** Bug 1514594: Part 3b - Mass rewrite all JS code to use the new ChromeUtils.import API. rs=Gijs This was done using the followng script: https://bitbucket.org/kmaglione/m-c-rewrites/src/tip/processors/cu-import-exports.jsm *** Bug 1514594: Part 3c - Update ESLint plugin for ChromeUtils.import API changes. r=Standard8 Differential Revision: https://phabricator.services.mozilla.com/D16747 *** Bug 1514594: Part 3d - Remove/fix hundreds of duplicate imports from sync tests. r=Gijs Differential Revision: https://phabricator.services.mozilla.com/D16748 *** Bug 1514594: Part 3e - Remove no-op ChromeUtils.import() calls. r=Gijs Differential Revision: https://phabricator.services.mozilla.com/D16749 *** Bug 1514594: Part 3f.1 - Cleanup various test corner cases after mass rewrite. r=Gijs *** Bug 1514594: Part 3f.2 - Cleanup various non-test corner cases after mass rewrite. r=Gijs Differential Revision: https://phabricator.services.mozilla.com/D16750 --HG-- extra : rebase_source : 359574ee3064c90f33bf36c2ebe3159a24cc8895 extra : histedit_source : b93c8f42808b1599f9122d7842d2c0b3e656a594%2C64a3a4e3359dc889e2ab2b49461bab9e27fc10a7
2019-01-17 18:18:31 +00:00
const {Services} = ChromeUtils.import("resource://gre/modules/Services.jsm");
const {XPCOMUtils} = ChromeUtils.import("resource://gre/modules/XPCOMUtils.jsm");
XPCOMUtils.defineLazyGlobalGetters(this, ["fetch"]);
var Utils = {
/**
* Check if local data exist for the specified client.
*
* @param {RemoteSettingsClient} client
* @return {bool} Whether it exists or not.
*/
async hasLocalData(client) {
const kintoCol = await client.openCollection();
const timestamp = await kintoCol.db.getLastModified();
return timestamp !== null;
},
/**
* Check if we ship a JSON dump for the specified bucket and collection.
*
* @param {String} bucket
* @param {String} collection
* @return {bool} Whether it is present or not.
*/
async hasLocalDump(bucket, collection) {
try {
await fetch(`resource://app/defaults/settings/${bucket}/${collection}.json`);
return true;
} catch (e) {
return false;
}
},
/**
* Fetch the list of remote collections and their timestamp.
* @param {String} url The poll URL (eg. `http://${server}{pollingEndpoint}`)
* @param {int} expectedTimestamp The timestamp that the server is supposed to return.
* We obtained it from the Megaphone notification payload,
* and we use it only for cache busting (Bug 1497159).
* @param {String} lastEtag (optional) The Etag of the latest poll to be matched
* by the server (eg. `"123456789"`).
* @param {Object} filters
*/
async fetchLatestChanges(url, options = {}) {
const { expectedTimestamp, lastEtag = "", filters = {} } = options;
//
// Fetch the list of changes objects from the server that looks like:
// {"data":[
// {
// "host":"kinto-ota.dev.mozaws.net",
// "last_modified":1450717104423,
// "bucket":"blocklists",
// "collection":"certificates"
// }]}
// Use ETag to obtain a `304 Not modified` when no change occurred,
// and `?_since` parameter to only keep entries that weren't processed yet.
const headers = {};
const params = { ...filters };
if (lastEtag != "") {
headers["If-None-Match"] = lastEtag;
params._since = lastEtag;
}
if (expectedTimestamp) {
params._expected = expectedTimestamp;
}
if (params) {
url += "?" + Object.entries(params).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
}
const response = await fetch(url, { headers });
let changes = [];
// If no changes since last time, go on with empty list of changes.
if (response.status != 304) {
const ct = response.headers.get("Content-Type");
if (!ct || !ct.includes("application/json")) {
throw new Error(`Unexpected content-type "${ct}"`);
}
let payload;
try {
payload = await response.json();
} catch (e) {
payload = e.message;
}
if (!payload.hasOwnProperty("data")) {
// If the server is failing, the JSON response might not contain the
// expected data. For example, real server errors (Bug 1259145)
// or dummy local server for tests (Bug 1481348)
const is404FromCustomServer = response.status == 404 && Services.prefs.prefHasUserValue("services.settings.server");
if (!is404FromCustomServer) {
throw new Error(`Server error ${response.status} ${response.statusText}: ${JSON.stringify(payload)}`);
}
} else {
changes = payload.data;
}
}
// The server should always return ETag. But we've had situations where the CDN
// was interfering.
const currentEtag = response.headers.has("ETag") ? response.headers.get("ETag") : undefined;
let serverTimeMillis = Date.parse(response.headers.get("Date"));
// Since the response is served via a CDN, the Date header value could have been cached.
const ageSeconds = response.headers.has("Age") ? parseInt(response.headers.get("Age"), 10) : 0;
serverTimeMillis += ageSeconds * 1000;
// Check if the server asked the clients to back off.
let backoffSeconds;
if (response.headers.has("Backoff")) {
const value = parseInt(response.headers.get("Backoff"), 10);
if (!isNaN(value)) {
backoffSeconds = value;
}
}
return { changes, currentEtag, serverTimeMillis, backoffSeconds };
},
};