2012-05-21 15:12:37 +04:00
|
|
|
/* 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/. */
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2018-02-23 22:50:01 +03:00
|
|
|
var EXPORTED_SYMBOLS = [
|
2012-09-15 03:02:32 +04:00
|
|
|
"WBORecord",
|
|
|
|
"RecordManager",
|
|
|
|
"CryptoWrapper",
|
2012-09-15 03:02:33 +04:00
|
|
|
"CollectionKeyManager",
|
2012-09-15 03:02:32 +04:00
|
|
|
"Collection",
|
|
|
|
];
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2011-04-19 23:35:04 +04:00
|
|
|
const CRYPTO_COLLECTION = "crypto";
|
|
|
|
const KEYS_WBO = "keys";
|
|
|
|
|
2019-01-17 21:18:31 +03:00
|
|
|
const { Log } = ChromeUtils.import("resource://gre/modules/Log.jsm");
|
|
|
|
const {
|
|
|
|
DEFAULT_DOWNLOAD_BATCH_SIZE,
|
|
|
|
DEFAULT_KEYBUNDLE_NAME,
|
|
|
|
} = ChromeUtils.import("resource://services-sync/constants.js");
|
|
|
|
const { BulkKeyBundle } = ChromeUtils.import(
|
|
|
|
"resource://services-sync/keys.js"
|
|
|
|
);
|
|
|
|
const { Weave } = ChromeUtils.import("resource://services-sync/main.js");
|
|
|
|
const { Resource } = ChromeUtils.import("resource://services-sync/resource.js");
|
|
|
|
const { Utils } = ChromeUtils.import("resource://services-sync/util.js");
|
|
|
|
const { Async } = ChromeUtils.import("resource://services-common/async.js");
|
|
|
|
const { CommonUtils } = ChromeUtils.import(
|
|
|
|
"resource://services-common/utils.js"
|
|
|
|
);
|
2011-01-19 03:23:30 +03:00
|
|
|
|
2018-02-23 22:50:01 +03:00
|
|
|
function WBORecord(collection, id) {
|
2011-01-19 03:23:30 +03:00
|
|
|
this.data = {};
|
|
|
|
this.payload = {};
|
2017-10-26 13:47:01 +03:00
|
|
|
this.collection = collection; // Optional.
|
|
|
|
this.id = id; // Optional.
|
2018-02-23 22:50:01 +03:00
|
|
|
}
|
2011-01-19 03:23:30 +03:00
|
|
|
WBORecord.prototype = {
|
2011-06-13 22:42:18 +04:00
|
|
|
_logName: "Sync.Record.WBO",
|
2011-01-19 03:23:30 +03:00
|
|
|
|
|
|
|
get sortindex() {
|
2018-08-06 16:42:31 +03:00
|
|
|
if (this.data.sortindex) {
|
2011-01-19 03:23:30 +03:00
|
|
|
return this.data.sortindex;
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2011-01-19 03:23:30 +03:00
|
|
|
return 0;
|
|
|
|
},
|
|
|
|
|
|
|
|
// Get thyself from your URI, then deserialize.
|
|
|
|
// Set thine 'response' field.
|
2017-04-11 16:40:53 +03:00
|
|
|
async fetch(resource) {
|
2016-12-13 00:50:10 +03:00
|
|
|
if (!(resource instanceof Resource)) {
|
2012-09-15 03:02:32 +04:00
|
|
|
throw new Error("First argument must be a Resource instance.");
|
|
|
|
}
|
|
|
|
|
2017-04-11 16:40:53 +03:00
|
|
|
let r = await resource.get();
|
2011-01-19 03:23:30 +03:00
|
|
|
if (r.success) {
|
2018-03-17 03:38:17 +03:00
|
|
|
this.deserialize(r.obj); // Warning! Muffles exceptions!
|
2011-01-19 03:23:30 +03:00
|
|
|
}
|
|
|
|
this.response = r;
|
|
|
|
return this;
|
|
|
|
},
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2017-04-11 16:40:53 +03:00
|
|
|
upload(resource) {
|
2016-12-13 00:50:10 +03:00
|
|
|
if (!(resource instanceof Resource)) {
|
2012-09-15 03:02:32 +04:00
|
|
|
throw new Error("First argument must be a Resource instance.");
|
|
|
|
}
|
|
|
|
|
|
|
|
return resource.put(this);
|
2011-01-19 03:23:30 +03:00
|
|
|
},
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2011-01-19 03:23:30 +03:00
|
|
|
// Take a base URI string, with trailing slash, and return the URI of this
|
|
|
|
// WBO based on collection and ID.
|
2017-01-10 20:09:02 +03:00
|
|
|
uri(base) {
|
2012-03-12 22:12:47 +04:00
|
|
|
if (this.collection && this.id) {
|
2017-08-25 08:41:44 +03:00
|
|
|
let url = CommonUtils.makeURI(base + this.collection + "/" + this.id);
|
2012-03-12 22:12:47 +04:00
|
|
|
url.QueryInterface(Ci.nsIURL);
|
|
|
|
return url;
|
|
|
|
}
|
2011-01-19 03:23:30 +03:00
|
|
|
return null;
|
|
|
|
},
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2011-01-19 03:23:30 +03:00
|
|
|
deserialize: function deserialize(json) {
|
2018-03-17 03:38:17 +03:00
|
|
|
if (!json || typeof json !== "object") {
|
|
|
|
throw new TypeError("Can't deserialize record from: " + json);
|
|
|
|
}
|
|
|
|
this.data = json;
|
2011-01-19 03:23:30 +03:00
|
|
|
try {
|
|
|
|
// The payload is likely to be JSON, but if not, keep it as a string
|
|
|
|
this.payload = JSON.parse(this.payload);
|
2017-01-10 20:09:02 +03:00
|
|
|
} catch (ex) {}
|
2011-01-19 03:23:30 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
toJSON: function toJSON() {
|
|
|
|
// Copy fields from data to be stringified, making sure payload is a string
|
|
|
|
let obj = {};
|
2018-08-06 16:42:31 +03:00
|
|
|
for (let [key, val] of Object.entries(this.data)) {
|
2011-01-19 03:23:30 +03:00
|
|
|
obj[key] = key == "payload" ? JSON.stringify(val) : val;
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
|
|
|
if (this.ttl) {
|
2011-01-19 03:23:30 +03:00
|
|
|
obj.ttl = this.ttl;
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2011-01-19 03:23:30 +03:00
|
|
|
return obj;
|
|
|
|
},
|
|
|
|
|
2011-12-14 02:54:17 +04:00
|
|
|
toString: function toString() {
|
|
|
|
return (
|
|
|
|
"{ " +
|
2017-01-10 20:09:02 +03:00
|
|
|
"id: " +
|
|
|
|
this.id +
|
|
|
|
" " +
|
|
|
|
"index: " +
|
|
|
|
this.sortindex +
|
|
|
|
" " +
|
|
|
|
"modified: " +
|
|
|
|
this.modified +
|
|
|
|
" " +
|
|
|
|
"ttl: " +
|
|
|
|
this.ttl +
|
2019-07-05 11:58:22 +03:00
|
|
|
" " +
|
2017-01-10 20:09:02 +03:00
|
|
|
"payload: " +
|
|
|
|
JSON.stringify(this.payload) +
|
2011-12-14 02:54:17 +04:00
|
|
|
" }"
|
|
|
|
);
|
2018-08-31 08:59:17 +03:00
|
|
|
},
|
2011-01-19 03:23:30 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
Utils.deferGetSet(WBORecord, "data", [
|
|
|
|
"id",
|
|
|
|
"modified",
|
|
|
|
"sortindex",
|
|
|
|
"payload",
|
|
|
|
]);
|
|
|
|
|
2018-02-23 22:50:01 +03:00
|
|
|
function CryptoWrapper(collection, id) {
|
2010-03-17 02:31:56 +03:00
|
|
|
this.cleartext = {};
|
2010-11-30 03:41:17 +03:00
|
|
|
WBORecord.call(this, collection, id);
|
2010-02-12 02:25:31 +03:00
|
|
|
this.ciphertext = null;
|
2010-11-30 03:41:17 +03:00
|
|
|
this.id = id;
|
2018-02-23 22:50:01 +03:00
|
|
|
}
|
2008-11-04 01:37:51 +03:00
|
|
|
CryptoWrapper.prototype = {
|
|
|
|
__proto__: WBORecord.prototype,
|
2011-06-13 22:42:18 +04:00
|
|
|
_logName: "Sync.Record.CryptoWrapper",
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
ciphertextHMAC: function ciphertextHMAC(keyBundle) {
|
2011-03-02 01:29:41 +03:00
|
|
|
let hasher = keyBundle.sha256HMACHasher;
|
2012-03-23 02:49:50 +04:00
|
|
|
if (!hasher) {
|
2017-07-23 04:55:43 +03:00
|
|
|
throw new Error("Cannot compute HMAC without an HMAC key.");
|
2012-03-23 02:49:50 +04:00
|
|
|
}
|
2011-03-02 01:29:41 +03:00
|
|
|
|
2018-01-25 04:09:16 +03:00
|
|
|
return CommonUtils.bytesAsHex(Utils.digestBytes(this.ciphertext, hasher));
|
2010-08-13 00:19:39 +04:00
|
|
|
},
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
/*
|
|
|
|
* Don't directly use the sync key. Instead, grab a key for this
|
|
|
|
* collection, which is decrypted with the sync key.
|
|
|
|
*
|
|
|
|
* Cache those keys; invalidate the cache if the time on the keys collection
|
|
|
|
* changes, or other auth events occur.
|
|
|
|
*
|
|
|
|
* Optional key bundle overrides the collection key lookup.
|
|
|
|
*/
|
2017-09-16 05:21:31 +03:00
|
|
|
async encrypt(keyBundle) {
|
2012-03-23 02:49:50 +04:00
|
|
|
if (!keyBundle) {
|
2012-09-15 03:02:33 +04:00
|
|
|
throw new Error("A key bundle must be supplied to encrypt.");
|
2012-03-23 02:49:50 +04:00
|
|
|
}
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2017-05-29 20:24:01 +03:00
|
|
|
this.IV = Weave.Crypto.generateRandomIV();
|
2017-09-16 05:21:31 +03:00
|
|
|
this.ciphertext = await Weave.Crypto.encrypt(
|
|
|
|
JSON.stringify(this.cleartext),
|
|
|
|
keyBundle.encryptionKeyB64,
|
|
|
|
this.IV
|
|
|
|
);
|
2010-11-30 03:41:17 +03:00
|
|
|
this.hmac = this.ciphertextHMAC(keyBundle);
|
2008-12-02 05:08:59 +03:00
|
|
|
this.cleartext = null;
|
2008-11-04 01:37:51 +03:00
|
|
|
},
|
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// Optional key bundle.
|
2017-09-16 05:21:31 +03:00
|
|
|
async decrypt(keyBundle) {
|
2010-11-30 03:41:17 +03:00
|
|
|
if (!this.ciphertext) {
|
2017-07-23 04:55:43 +03:00
|
|
|
throw new Error("No ciphertext: nothing to decrypt?");
|
2010-11-30 03:41:17 +03:00
|
|
|
}
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2012-03-23 02:49:50 +04:00
|
|
|
if (!keyBundle) {
|
2012-09-15 03:02:33 +04:00
|
|
|
throw new Error("A key bundle must be supplied to decrypt.");
|
2012-03-23 02:49:50 +04:00
|
|
|
}
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2010-03-17 02:31:56 +03:00
|
|
|
// Authenticate the encrypted blob with the expected HMAC
|
2010-11-30 03:41:17 +03:00
|
|
|
let computedHMAC = this.ciphertextHMAC(keyBundle);
|
2010-03-17 02:31:56 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
if (computedHMAC != this.hmac) {
|
2010-12-09 21:32:03 +03:00
|
|
|
Utils.throwHMACMismatch(this.hmac, computedHMAC);
|
2010-11-30 03:41:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// Handle invalid data here. Elsewhere we assume that cleartext is an object.
|
2017-09-16 05:21:31 +03:00
|
|
|
let cleartext = await Weave.Crypto.decrypt(
|
|
|
|
this.ciphertext,
|
|
|
|
keyBundle.encryptionKeyB64,
|
|
|
|
this.IV
|
|
|
|
);
|
2011-03-02 01:29:41 +03:00
|
|
|
let json_result = JSON.parse(cleartext);
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
if (json_result && json_result instanceof Object) {
|
|
|
|
this.cleartext = json_result;
|
2011-03-02 01:29:41 +03:00
|
|
|
this.ciphertext = null;
|
|
|
|
} else {
|
2017-07-23 04:55:43 +03:00
|
|
|
throw new Error(
|
|
|
|
`Decryption failed: result is <${json_result}>, not an object.`
|
|
|
|
);
|
2010-11-30 03:41:17 +03:00
|
|
|
}
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// Verify that the encrypted id matches the requested record's id.
|
2018-08-06 16:42:31 +03:00
|
|
|
if (this.cleartext.id != this.id) {
|
2017-07-23 04:55:43 +03:00
|
|
|
throw new Error(`Record id mismatch: ${this.cleartext.id} != ${this.id}`);
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2010-03-17 02:31:56 +03:00
|
|
|
|
2009-06-05 06:06:57 +04:00
|
|
|
return this.cleartext;
|
2009-01-24 02:08:12 +03:00
|
|
|
},
|
|
|
|
|
2017-07-11 22:15:37 +03:00
|
|
|
cleartextToString() {
|
|
|
|
return JSON.stringify(this.cleartext);
|
|
|
|
},
|
|
|
|
|
2011-12-14 02:54:17 +04:00
|
|
|
toString: function toString() {
|
2017-07-11 22:15:37 +03:00
|
|
|
let payload = this.deleted ? "DELETED" : this.cleartextToString();
|
2011-12-14 02:54:17 +04:00
|
|
|
|
|
|
|
return (
|
|
|
|
"{ " +
|
2017-01-10 20:09:02 +03:00
|
|
|
"id: " +
|
|
|
|
this.id +
|
|
|
|
" " +
|
|
|
|
"index: " +
|
|
|
|
this.sortindex +
|
|
|
|
" " +
|
|
|
|
"modified: " +
|
|
|
|
this.modified +
|
|
|
|
" " +
|
|
|
|
"ttl: " +
|
|
|
|
this.ttl +
|
|
|
|
" " +
|
|
|
|
"payload: " +
|
|
|
|
payload +
|
2019-07-05 11:58:22 +03:00
|
|
|
" " +
|
2011-12-14 02:54:17 +04:00
|
|
|
"collection: " +
|
|
|
|
(this.collection || "undefined") +
|
|
|
|
" }"
|
|
|
|
);
|
|
|
|
},
|
2010-03-17 02:31:56 +03:00
|
|
|
|
|
|
|
// The custom setter below masks the parent's getter, so explicitly call it :(
|
2015-09-23 12:40:53 +03:00
|
|
|
get id() {
|
|
|
|
return WBORecord.prototype.__lookupGetter__("id").call(this);
|
|
|
|
},
|
2010-03-17 02:31:56 +03:00
|
|
|
|
|
|
|
// Keep both plaintext and encrypted versions of the id to verify integrity
|
|
|
|
set id(val) {
|
|
|
|
WBORecord.prototype.__lookupSetter__("id").call(this, val);
|
|
|
|
return (this.cleartext.id = val);
|
|
|
|
},
|
2008-11-04 01:37:51 +03:00
|
|
|
};
|
|
|
|
|
2010-08-13 00:19:39 +04:00
|
|
|
Utils.deferGetSet(CryptoWrapper, "payload", ["ciphertext", "IV", "hmac"]);
|
2010-03-17 02:31:56 +03:00
|
|
|
Utils.deferGetSet(CryptoWrapper, "cleartext", "deleted");
|
2009-04-14 01:39:29 +04:00
|
|
|
|
2014-12-10 05:02:24 +03:00
|
|
|
/**
|
|
|
|
* An interface and caching layer for records.
|
|
|
|
*/
|
2018-02-23 22:50:01 +03:00
|
|
|
function RecordManager(service) {
|
2014-12-10 05:02:24 +03:00
|
|
|
this.service = service;
|
|
|
|
|
|
|
|
this._log = Log.repository.getLogger(this._logName);
|
|
|
|
this._records = {};
|
2018-02-23 22:50:01 +03:00
|
|
|
}
|
2014-12-10 05:02:24 +03:00
|
|
|
RecordManager.prototype = {
|
|
|
|
_recordType: CryptoWrapper,
|
|
|
|
_logName: "Sync.RecordManager",
|
|
|
|
|
2017-04-11 16:40:53 +03:00
|
|
|
async import(url) {
|
2014-12-10 05:02:24 +03:00
|
|
|
this._log.trace("Importing record: " + (url.spec ? url.spec : url));
|
|
|
|
try {
|
|
|
|
// Clear out the last response with empty object if GET fails
|
|
|
|
this.response = {};
|
2017-04-11 16:40:53 +03:00
|
|
|
this.response = await this.service.resource(url).get();
|
2014-12-10 05:02:24 +03:00
|
|
|
|
|
|
|
// Don't parse and save the record on failure
|
2018-08-06 16:42:31 +03:00
|
|
|
if (!this.response.success) {
|
2014-12-10 05:02:24 +03:00
|
|
|
return null;
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2014-12-10 05:02:24 +03:00
|
|
|
|
|
|
|
let record = new this._recordType(url);
|
2018-03-17 03:38:17 +03:00
|
|
|
record.deserialize(this.response.obj);
|
2014-12-10 05:02:24 +03:00
|
|
|
|
|
|
|
return this.set(url, record);
|
2016-01-26 18:13:31 +03:00
|
|
|
} catch (ex) {
|
|
|
|
if (Async.isShutdownException(ex)) {
|
|
|
|
throw ex;
|
|
|
|
}
|
2016-01-07 09:09:00 +03:00
|
|
|
this._log.debug("Failed to import record", ex);
|
2014-12-10 05:02:24 +03:00
|
|
|
return null;
|
|
|
|
}
|
|
|
|
},
|
|
|
|
|
2017-04-11 16:40:53 +03:00
|
|
|
get(url) {
|
2014-12-10 05:02:24 +03:00
|
|
|
// Use a url string as the key to the hash
|
|
|
|
let spec = url.spec ? url.spec : url;
|
2018-08-06 16:42:31 +03:00
|
|
|
if (spec in this._records) {
|
2017-04-11 16:40:53 +03:00
|
|
|
return Promise.resolve(this._records[spec]);
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2014-12-10 05:02:24 +03:00
|
|
|
return this.import(url);
|
|
|
|
},
|
|
|
|
|
|
|
|
set: function RecordMgr_set(url, record) {
|
|
|
|
let spec = url.spec ? url.spec : url;
|
|
|
|
return (this._records[spec] = record);
|
|
|
|
},
|
|
|
|
|
|
|
|
contains: function RecordMgr_contains(url) {
|
2018-08-06 16:42:31 +03:00
|
|
|
if ((url.spec || url) in this._records) {
|
2014-12-10 05:02:24 +03:00
|
|
|
return true;
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2014-12-10 05:02:24 +03:00
|
|
|
return false;
|
|
|
|
},
|
|
|
|
|
|
|
|
clearCache: function recordMgr_clearCache() {
|
|
|
|
this._records = {};
|
|
|
|
},
|
|
|
|
|
|
|
|
del: function RecordMgr_del(url) {
|
|
|
|
delete this._records[url];
|
2018-08-31 08:59:17 +03:00
|
|
|
},
|
2014-12-10 05:02:24 +03:00
|
|
|
};
|
2010-11-30 03:41:17 +03:00
|
|
|
|
|
|
|
/**
|
2012-03-23 02:49:50 +04:00
|
|
|
* Keeps track of mappings between collection names ('tabs') and KeyBundles.
|
2010-11-30 03:41:17 +03:00
|
|
|
*
|
|
|
|
* You can update this thing simply by giving it /info/collections. It'll
|
|
|
|
* use the last modified time to bring itself up to date.
|
|
|
|
*/
|
2018-02-23 22:50:01 +03:00
|
|
|
function CollectionKeyManager(lastModified, default_, collections) {
|
2016-09-08 21:21:18 +03:00
|
|
|
this.lastModified = lastModified || 0;
|
|
|
|
this._default = default_ || null;
|
|
|
|
this._collections = collections || {};
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2013-08-26 22:55:58 +04:00
|
|
|
this._log = Log.repository.getLogger("Sync.CollectionKeyManager");
|
2018-02-23 22:50:01 +03:00
|
|
|
}
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// TODO: persist this locally as an Identity. Bug 610913.
|
|
|
|
// Note that the last modified time needs to be preserved.
|
|
|
|
CollectionKeyManager.prototype = {
|
2016-09-08 21:21:18 +03:00
|
|
|
/**
|
|
|
|
* Generate a new CollectionKeyManager that has the same attributes
|
|
|
|
* as this one.
|
|
|
|
*/
|
|
|
|
clone() {
|
|
|
|
const newCollections = {};
|
|
|
|
for (let c in this._collections) {
|
|
|
|
newCollections[c] = this._collections[c];
|
|
|
|
}
|
|
|
|
|
|
|
|
return new CollectionKeyManager(
|
|
|
|
this.lastModified,
|
|
|
|
this._default,
|
|
|
|
newCollections
|
|
|
|
);
|
|
|
|
},
|
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
// Return information about old vs new keys:
|
|
|
|
// * same: true if two collections are equal
|
|
|
|
// * changed: an array of collection names that changed.
|
|
|
|
_compareKeyBundleCollections: function _compareKeyBundleCollections(m1, m2) {
|
|
|
|
let changed = [];
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
function process(m1, m2) {
|
|
|
|
for (let k1 in m1) {
|
|
|
|
let v1 = m1[k1];
|
|
|
|
let v2 = m2[k1];
|
2018-08-06 16:42:31 +03:00
|
|
|
if (!(v1 && v2 && v1.equals(v2))) {
|
2010-12-09 21:32:03 +03:00
|
|
|
changed.push(k1);
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2010-12-09 21:32:03 +03:00
|
|
|
}
|
|
|
|
}
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
// Diffs both ways.
|
|
|
|
process(m1, m2);
|
|
|
|
process(m2, m1);
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
// Return a sorted, unique array.
|
|
|
|
changed.sort();
|
|
|
|
let last;
|
2015-10-18 21:52:58 +03:00
|
|
|
changed = changed.filter(x => x != last && (last = x));
|
2010-12-09 21:32:03 +03:00
|
|
|
return { same: changed.length == 0, changed };
|
|
|
|
},
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
get isClear() {
|
|
|
|
return !this._default;
|
|
|
|
},
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-08 03:30:06 +03:00
|
|
|
clear: function clear() {
|
2012-09-15 03:02:33 +04:00
|
|
|
this._log.info("Clearing collection keys...");
|
2011-04-19 23:35:04 +04:00
|
|
|
this.lastModified = 0;
|
2010-12-08 03:30:06 +03:00
|
|
|
this._collections = {};
|
|
|
|
this._default = null;
|
|
|
|
},
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2017-01-10 20:09:02 +03:00
|
|
|
keyForCollection(collection) {
|
2018-08-06 16:42:31 +03:00
|
|
|
if (collection && this._collections[collection]) {
|
2010-11-30 03:41:17 +03:00
|
|
|
return this._collections[collection];
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
return this._default;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* If `collections` (an array of strings) is provided, iterate
|
|
|
|
* over it and generate random keys for each collection.
|
2011-04-19 23:35:04 +04:00
|
|
|
* Create a WBO for the given data.
|
|
|
|
*/
|
2017-01-10 20:09:02 +03:00
|
|
|
_makeWBO(collections, defaultBundle) {
|
2011-04-19 23:35:04 +04:00
|
|
|
let wbo = new CryptoWrapper(CRYPTO_COLLECTION, KEYS_WBO);
|
|
|
|
let c = {};
|
|
|
|
for (let k in collections) {
|
2012-03-23 02:49:50 +04:00
|
|
|
c[k] = collections[k].keyPairB64;
|
2011-04-19 23:35:04 +04:00
|
|
|
}
|
|
|
|
wbo.cleartext = {
|
2012-03-23 02:49:50 +04:00
|
|
|
default: defaultBundle ? defaultBundle.keyPairB64 : null,
|
2011-04-19 23:35:04 +04:00
|
|
|
collections: c,
|
|
|
|
collection: CRYPTO_COLLECTION,
|
2018-08-31 08:59:17 +03:00
|
|
|
id: KEYS_WBO,
|
2011-04-19 23:35:04 +04:00
|
|
|
};
|
|
|
|
return wbo;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a WBO for the current keys.
|
|
|
|
*/
|
2017-01-10 20:09:02 +03:00
|
|
|
asWBO(collection, id) {
|
2015-09-23 12:40:53 +03:00
|
|
|
return this._makeWBO(this._collections, this._default);
|
|
|
|
},
|
2011-04-19 23:35:04 +04:00
|
|
|
|
|
|
|
/**
|
|
|
|
* Compute a new default key, and new keys for any specified collections.
|
2010-11-30 03:41:17 +03:00
|
|
|
*/
|
2017-09-16 05:21:31 +03:00
|
|
|
async newKeys(collections) {
|
|
|
|
let newDefaultKeyBundle = await this.newDefaultKeyBundle();
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
let newColls = {};
|
|
|
|
if (collections) {
|
2017-09-16 05:21:31 +03:00
|
|
|
for (let c of collections) {
|
2012-03-23 02:49:50 +04:00
|
|
|
let b = new BulkKeyBundle(c);
|
2017-09-16 05:21:31 +03:00
|
|
|
await b.generateRandom();
|
2010-11-30 03:41:17 +03:00
|
|
|
newColls[c] = b;
|
2017-09-16 05:21:31 +03:00
|
|
|
}
|
2010-11-30 03:41:17 +03:00
|
|
|
}
|
2016-09-08 21:21:18 +03:00
|
|
|
return [newDefaultKeyBundle, newColls];
|
2010-11-30 03:41:17 +03:00
|
|
|
},
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2011-04-19 23:35:04 +04:00
|
|
|
/**
|
|
|
|
* Generates new keys, but does not replace our local copy. Use this to
|
|
|
|
* verify an upload before storing.
|
|
|
|
*/
|
2017-09-16 05:21:31 +03:00
|
|
|
async generateNewKeysWBO(collections) {
|
2011-04-19 23:35:04 +04:00
|
|
|
let newDefaultKey, newColls;
|
2017-09-16 05:21:31 +03:00
|
|
|
[newDefaultKey, newColls] = await this.newKeys(collections);
|
2011-04-19 23:35:04 +04:00
|
|
|
|
|
|
|
return this._makeWBO(newColls, newDefaultKey);
|
2010-07-03 22:13:40 +04:00
|
|
|
},
|
|
|
|
|
2016-09-08 21:21:18 +03:00
|
|
|
/**
|
|
|
|
* Create a new default key.
|
|
|
|
*
|
|
|
|
* @returns {BulkKeyBundle}
|
|
|
|
*/
|
2017-09-16 05:21:31 +03:00
|
|
|
async newDefaultKeyBundle() {
|
2016-09-08 21:21:18 +03:00
|
|
|
const key = new BulkKeyBundle(DEFAULT_KEYBUNDLE_NAME);
|
2017-09-16 05:21:31 +03:00
|
|
|
await key.generateRandom();
|
2016-09-08 21:21:18 +03:00
|
|
|
return key;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new default key and store it as this._default, since without one you cannot use setContents.
|
|
|
|
*/
|
2017-09-16 05:21:31 +03:00
|
|
|
async generateDefaultKey() {
|
|
|
|
this._default = await this.newDefaultKeyBundle();
|
2016-09-08 21:21:18 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return true if keys are already present for each of the given
|
|
|
|
* collections.
|
|
|
|
*/
|
|
|
|
hasKeysFor(collections) {
|
|
|
|
// We can't use filter() here because sometimes collections is an iterator.
|
|
|
|
for (let collection of collections) {
|
|
|
|
if (!this._collections[collection]) {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return true;
|
|
|
|
},
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Return a new CollectionKeyManager that has keys for each of the
|
|
|
|
* given collections (creating new ones for collections where we
|
|
|
|
* don't already have keys).
|
|
|
|
*/
|
2017-09-16 05:21:31 +03:00
|
|
|
async ensureKeysFor(collections) {
|
2016-09-08 21:21:18 +03:00
|
|
|
const newKeys = Object.assign({}, this._collections);
|
|
|
|
for (let c of collections) {
|
|
|
|
if (newKeys[c]) {
|
2017-10-26 13:47:01 +03:00
|
|
|
continue; // don't replace existing keys
|
2016-09-08 21:21:18 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
const b = new BulkKeyBundle(c);
|
2017-09-16 05:21:31 +03:00
|
|
|
await b.generateRandom();
|
2016-09-08 21:21:18 +03:00
|
|
|
newKeys[c] = b;
|
|
|
|
}
|
|
|
|
return new CollectionKeyManager(this.lastModified, this._default, newKeys);
|
|
|
|
},
|
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// Take the fetched info/collections WBO, checking the change
|
|
|
|
// time of the crypto collection.
|
2017-01-10 20:09:02 +03:00
|
|
|
updateNeeded(info_collections) {
|
2011-04-19 23:35:04 +04:00
|
|
|
this._log.info(
|
|
|
|
"Testing for updateNeeded. Last modified: " + this.lastModified
|
|
|
|
);
|
2010-03-26 05:23:44 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// No local record of modification time? Need an update.
|
2018-08-06 16:42:31 +03:00
|
|
|
if (!this.lastModified) {
|
2010-11-30 03:41:17 +03:00
|
|
|
return true;
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2010-03-17 02:31:56 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// No keys on the server? We need an update, though our
|
|
|
|
// update handling will be a little more drastic...
|
2018-08-06 16:42:31 +03:00
|
|
|
if (!(CRYPTO_COLLECTION in info_collections)) {
|
2010-11-30 03:41:17 +03:00
|
|
|
return true;
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2010-03-17 02:31:56 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// Otherwise, we need an update if our modification time is stale.
|
2011-04-19 23:35:04 +04:00
|
|
|
return info_collections[CRYPTO_COLLECTION] > this.lastModified;
|
2008-11-08 13:00:33 +03:00
|
|
|
},
|
|
|
|
|
2011-04-19 23:33:47 +04:00
|
|
|
//
|
2010-12-09 21:32:03 +03:00
|
|
|
// Set our keys and modified time to the values fetched from the server.
|
|
|
|
// Returns one of three values:
|
2011-04-19 23:33:47 +04:00
|
|
|
//
|
2010-12-09 21:32:03 +03:00
|
|
|
// * If the default key was modified, return true.
|
|
|
|
// * If the default key was not modified, but per-collection keys were,
|
|
|
|
// return an array of such.
|
|
|
|
// * Otherwise, return false -- we were up-to-date.
|
2011-04-19 23:33:47 +04:00
|
|
|
//
|
2010-11-30 03:41:17 +03:00
|
|
|
setContents: function setContents(payload, modified) {
|
2011-04-19 23:35:04 +04:00
|
|
|
let self = this;
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2012-09-15 03:02:33 +04:00
|
|
|
this._log.info(
|
|
|
|
"Setting collection keys contents. Our last modified: " +
|
2011-04-19 23:35:04 +04:00
|
|
|
this.lastModified +
|
|
|
|
", input modified: " +
|
|
|
|
modified +
|
|
|
|
"."
|
|
|
|
);
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2018-08-06 16:42:31 +03:00
|
|
|
if (!payload) {
|
2017-07-23 04:55:43 +03:00
|
|
|
throw new Error("No payload in CollectionKeyManager.setContents().");
|
2018-08-06 16:42:31 +03:00
|
|
|
}
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
if (!payload.default) {
|
|
|
|
this._log.warn("No downloaded default key: this should not occur.");
|
|
|
|
this._log.warn("Not clearing local keys.");
|
2017-07-23 04:55:43 +03:00
|
|
|
throw new Error(
|
|
|
|
"No default key in CollectionKeyManager.setContents(). Cannot proceed."
|
|
|
|
);
|
2010-12-09 21:32:03 +03:00
|
|
|
}
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
// Process the incoming default key.
|
2012-03-23 02:49:50 +04:00
|
|
|
let b = new BulkKeyBundle(DEFAULT_KEYBUNDLE_NAME);
|
|
|
|
b.keyPairB64 = payload.default;
|
2010-12-09 21:32:03 +03:00
|
|
|
let newDefault = b;
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
// Process the incoming collections.
|
|
|
|
let newCollections = {};
|
2010-11-30 03:41:17 +03:00
|
|
|
if ("collections" in payload) {
|
2010-12-09 21:32:03 +03:00
|
|
|
this._log.info("Processing downloaded per-collection keys.");
|
|
|
|
let colls = payload.collections;
|
2010-11-30 03:41:17 +03:00
|
|
|
for (let k in colls) {
|
|
|
|
let v = colls[k];
|
|
|
|
if (v) {
|
2012-03-23 02:49:50 +04:00
|
|
|
let keyObj = new BulkKeyBundle(k);
|
|
|
|
keyObj.keyPairB64 = v;
|
2016-09-08 21:21:18 +03:00
|
|
|
newCollections[k] = keyObj;
|
2010-11-30 03:41:17 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
// Check to see if these are already our keys.
|
|
|
|
let sameDefault = this._default && this._default.equals(newDefault);
|
|
|
|
let collComparison = this._compareKeyBundleCollections(
|
|
|
|
newCollections,
|
|
|
|
this._collections
|
|
|
|
);
|
|
|
|
let sameColls = collComparison.same;
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
if (sameDefault && sameColls) {
|
2016-09-08 21:21:18 +03:00
|
|
|
self._log.info("New keys are the same as our old keys!");
|
|
|
|
if (modified) {
|
|
|
|
self._log.info("Bumped local modified time.");
|
|
|
|
self.lastModified = modified;
|
|
|
|
}
|
2010-12-09 21:32:03 +03:00
|
|
|
return false;
|
2010-11-30 03:41:17 +03:00
|
|
|
}
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
// Make sure things are nice and tidy before we set.
|
|
|
|
this.clear();
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
this._log.info("Saving downloaded keys.");
|
|
|
|
this._default = newDefault;
|
|
|
|
this._collections = newCollections;
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2011-04-19 23:35:04 +04:00
|
|
|
// Always trust the server.
|
2016-09-08 21:21:18 +03:00
|
|
|
if (modified) {
|
|
|
|
self._log.info("Bumping last modified to " + modified);
|
|
|
|
self.lastModified = modified;
|
|
|
|
}
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-12-09 21:32:03 +03:00
|
|
|
return sameDefault ? collComparison.changed : true;
|
2008-11-08 13:00:33 +03:00
|
|
|
},
|
|
|
|
|
2017-09-16 05:21:31 +03:00
|
|
|
async updateContents(syncKeyBundle, storage_keys) {
|
2010-11-30 03:41:17 +03:00
|
|
|
let log = this._log;
|
|
|
|
log.info("Updating collection keys...");
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
// storage_keys is a WBO, fetched from storage/crypto/keys.
|
|
|
|
// Its payload is the default key, and a map of collections to keys.
|
|
|
|
// We lazily compute the key objects from the strings we're given.
|
2011-04-19 23:33:47 +04:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
let payload;
|
|
|
|
try {
|
2017-09-16 05:21:31 +03:00
|
|
|
payload = await storage_keys.decrypt(syncKeyBundle);
|
2010-11-30 03:41:17 +03:00
|
|
|
} catch (ex) {
|
2017-07-23 04:55:43 +03:00
|
|
|
log.warn("Got exception decrypting storage keys with sync key.", ex);
|
2010-11-30 03:41:17 +03:00
|
|
|
log.info("Aborting updateContents. Rethrowing.");
|
|
|
|
throw ex;
|
|
|
|
}
|
2008-11-08 13:00:33 +03:00
|
|
|
|
2010-11-30 03:41:17 +03:00
|
|
|
let r = this.setContents(payload, storage_keys.modified);
|
|
|
|
log.info("Collection keys updated.");
|
|
|
|
return r;
|
2018-08-31 08:59:17 +03:00
|
|
|
},
|
2017-10-15 21:50:30 +03:00
|
|
|
};
|
2008-11-04 01:37:51 +03:00
|
|
|
|
2018-02-23 22:50:01 +03:00
|
|
|
function Collection(uri, recordObj, service) {
|
2012-09-15 03:02:32 +04:00
|
|
|
if (!service) {
|
|
|
|
throw new Error("Collection constructor requires a service.");
|
|
|
|
}
|
|
|
|
|
2011-01-19 03:23:30 +03:00
|
|
|
Resource.call(this, uri);
|
2012-09-15 03:02:32 +04:00
|
|
|
|
|
|
|
// This is a bit hacky, but gets the job done.
|
|
|
|
let res = service.resource(uri);
|
|
|
|
this.authenticator = res.authenticator;
|
|
|
|
|
2011-01-19 03:23:30 +03:00
|
|
|
this._recordObj = recordObj;
|
2012-09-15 03:02:32 +04:00
|
|
|
this._service = service;
|
2011-01-19 03:23:30 +03:00
|
|
|
|
|
|
|
this._full = false;
|
|
|
|
this._ids = null;
|
|
|
|
this._limit = 0;
|
|
|
|
this._older = 0;
|
|
|
|
this._newer = 0;
|
|
|
|
this._data = [];
|
2016-10-07 00:52:27 +03:00
|
|
|
// optional members used by batch upload operations.
|
2016-08-24 23:02:14 +03:00
|
|
|
this._batch = null;
|
|
|
|
this._commit = false;
|
2016-10-07 00:52:27 +03:00
|
|
|
// Used for batch download operations -- note that this is explicitly an
|
|
|
|
// opaque value and not (necessarily) a number.
|
|
|
|
this._offset = null;
|
2018-02-23 22:50:01 +03:00
|
|
|
}
|
2011-01-19 03:23:30 +03:00
|
|
|
Collection.prototype = {
|
|
|
|
__proto__: Resource.prototype,
|
2011-06-13 22:42:18 +04:00
|
|
|
_logName: "Sync.Collection",
|
2011-01-19 03:23:30 +03:00
|
|
|
|
|
|
|
_rebuildURL: function Coll__rebuildURL() {
|
|
|
|
// XXX should consider what happens if it's not a URL...
|
|
|
|
this.uri.QueryInterface(Ci.nsIURL);
|
|
|
|
|
|
|
|
let args = [];
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
if (this.older) {
|
2017-01-17 18:48:17 +03:00
|
|
|
args.push("older=" + this.older);
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
|
|
|
if (this.newer) {
|
2017-01-17 18:48:17 +03:00
|
|
|
args.push("newer=" + this.newer);
|
2011-01-19 03:23:30 +03:00
|
|
|
}
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
if (this.full) {
|
2017-01-17 18:48:17 +03:00
|
|
|
args.push("full=1");
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
|
|
|
if (this.sort) {
|
2017-01-17 18:48:17 +03:00
|
|
|
args.push("sort=" + this.sort);
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
|
|
|
if (this.ids != null) {
|
2011-01-19 03:23:30 +03:00
|
|
|
args.push("ids=" + this.ids);
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
|
|
|
if (this.limit > 0 && this.limit != Infinity) {
|
2011-01-19 03:23:30 +03:00
|
|
|
args.push("limit=" + this.limit);
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
|
|
|
if (this._batch) {
|
2016-10-10 21:02:13 +03:00
|
|
|
args.push("batch=" + encodeURIComponent(this._batch));
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
|
|
|
if (this._commit) {
|
2016-08-24 23:02:14 +03:00
|
|
|
args.push("commit=true");
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
|
|
|
if (this._offset) {
|
2016-10-07 00:52:27 +03:00
|
|
|
args.push("offset=" + encodeURIComponent(this._offset));
|
Bug 1368209 - Refactor `Engine::_processIncoming` into three stages. r=eoger,tcsc
* In the first stage, we fetch changed records, newest first, up to the
download limit. We keep track of the oldest record modified time we
see.
* Once we've fetched all records, we reconcile, noting records that
fail to decrypt or reconcile for the next sync. We then ask the store
to apply all remaining records. Previously, `applyIncomingBatchSize`
specified how many records to apply at a time. I removed this because
it added an extra layer of indirection that's no longer necessary,
now that download batching buffers all records in memory, and all
stores are async.
* In the second stage, we fetch IDs for all remaining records changed
between the last sync and the oldest modified time we saw in the
first stage. We *don't* set the download limit here, to ensure we
add *all* changed records to our backlog, and we use the `"oldest"`
sort order instead of `"index"`.
* In the third stage, we backfill as before. We don't want large deltas
to delay other engines from syncing, so we still only take IDs up to
the download limit from the backlog, and include failed IDs from the
previous sync. On subsequent syncs, we'll keep fetching from the
backlog until it's empty.
Other changes to note in this patch:
* `Collection::_rebuildURL` now allows callers to specify both `older`
and `newer`. According to :rfkelly, this is explicitly and
intentionally supported.
* Tests that exercise `applyIncomingBatchSize` are gone, since that's
no longer a thing.
* The test server now shuffles records if the sort order is
unspecified.
MozReview-Commit-ID: 4EXvNOa8mIo
--HG--
extra : rebase_source : f382f0a883c5aa1f6a4466fefe22ad1a88ab6d20
2017-11-01 21:09:57 +03:00
|
|
|
}
|
2011-01-19 03:23:30 +03:00
|
|
|
|
2018-02-26 22:43:46 +03:00
|
|
|
this.uri = this.uri
|
|
|
|
.mutate()
|
|
|
|
.setQuery(args.length > 0 ? "?" + args.join("&") : "")
|
|
|
|
.finalize();
|
2011-01-19 03:23:30 +03:00
|
|
|
},
|
|
|
|
|
|
|
|
// get full items
|
|
|
|
get full() {
|
|
|
|
return this._full;
|
|
|
|
},
|
|
|
|
set full(value) {
|
|
|
|
this._full = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
|
|
|
// Apply the action to a certain set of ids
|
2015-09-23 12:40:53 +03:00
|
|
|
get ids() {
|
|
|
|
return this._ids;
|
|
|
|
},
|
2011-01-19 03:23:30 +03:00
|
|
|
set ids(value) {
|
|
|
|
this._ids = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
|
|
|
// Limit how many records to get
|
2015-09-23 12:40:53 +03:00
|
|
|
get limit() {
|
|
|
|
return this._limit;
|
|
|
|
},
|
2011-01-19 03:23:30 +03:00
|
|
|
set limit(value) {
|
|
|
|
this._limit = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
|
|
|
// get only items modified before some date
|
|
|
|
get older() {
|
|
|
|
return this._older;
|
|
|
|
},
|
|
|
|
set older(value) {
|
|
|
|
this._older = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
|
|
|
// get only items modified since some date
|
|
|
|
get newer() {
|
|
|
|
return this._newer;
|
|
|
|
},
|
|
|
|
set newer(value) {
|
|
|
|
this._newer = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
|
|
|
// get items sorted by some criteria. valid values:
|
|
|
|
// oldest (oldest first)
|
|
|
|
// newest (newest first)
|
|
|
|
// index
|
|
|
|
get sort() {
|
|
|
|
return this._sort;
|
|
|
|
},
|
|
|
|
set sort(value) {
|
2018-02-23 02:06:45 +03:00
|
|
|
if (value && value != "oldest" && value != "newest" && value != "index") {
|
|
|
|
throw new TypeError(
|
|
|
|
`Illegal value for sort: "${value}" (should be "oldest", "newest", or "index").`
|
|
|
|
);
|
|
|
|
}
|
2011-01-19 03:23:30 +03:00
|
|
|
this._sort = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
2016-10-07 00:52:27 +03:00
|
|
|
get offset() {
|
|
|
|
return this._offset;
|
|
|
|
},
|
|
|
|
set offset(value) {
|
|
|
|
this._offset = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
2016-08-24 23:02:14 +03:00
|
|
|
// Set information about the batch for this request.
|
2016-10-06 18:54:59 +03:00
|
|
|
get batch() {
|
|
|
|
return this._batch;
|
|
|
|
},
|
2016-08-24 23:02:14 +03:00
|
|
|
set batch(value) {
|
|
|
|
this._batch = value;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
2016-10-06 18:54:59 +03:00
|
|
|
get commit() {
|
|
|
|
return this._commit;
|
|
|
|
},
|
2016-08-24 23:02:14 +03:00
|
|
|
set commit(value) {
|
|
|
|
this._commit = value && true;
|
|
|
|
this._rebuildURL();
|
|
|
|
},
|
|
|
|
|
2016-10-07 00:52:27 +03:00
|
|
|
// Similar to get(), but will page through the items `batchSize` at a time,
|
|
|
|
// deferring calling the record handler until we've gotten them all.
|
|
|
|
//
|
|
|
|
// Returns the last response processed, and doesn't run the record handler
|
|
|
|
// on any items if a non-success status is received while downloading the
|
|
|
|
// records (or if a network error occurs).
|
2017-04-11 16:40:53 +03:00
|
|
|
async getBatched(batchSize = DEFAULT_DOWNLOAD_BATCH_SIZE) {
|
2016-10-07 00:52:27 +03:00
|
|
|
let totalLimit = Number(this.limit) || Infinity;
|
|
|
|
if (batchSize <= 0 || batchSize >= totalLimit) {
|
2017-05-30 20:23:57 +03:00
|
|
|
throw new Error("Invalid batch size");
|
2016-10-07 00:52:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!this.full) {
|
|
|
|
throw new Error("getBatched is unimplemented for guid-only GETs");
|
|
|
|
}
|
|
|
|
|
2017-11-02 21:30:59 +03:00
|
|
|
// _onComplete and _onProgress are reset after each `get` by Resource.
|
2017-05-30 20:23:57 +03:00
|
|
|
let { _onComplete, _onProgress } = this;
|
2016-10-07 00:52:27 +03:00
|
|
|
let recordBuffer = [];
|
|
|
|
let resp;
|
|
|
|
try {
|
|
|
|
let lastModifiedTime;
|
|
|
|
this.limit = batchSize;
|
|
|
|
|
|
|
|
do {
|
|
|
|
this._onProgress = _onProgress;
|
|
|
|
this._onComplete = _onComplete;
|
|
|
|
if (batchSize + recordBuffer.length > totalLimit) {
|
|
|
|
this.limit = totalLimit - recordBuffer.length;
|
|
|
|
}
|
|
|
|
this._log.trace("Performing batched GET", {
|
|
|
|
limit: this.limit,
|
|
|
|
offset: this.offset,
|
|
|
|
});
|
|
|
|
// Actually perform the request
|
2017-04-11 16:40:53 +03:00
|
|
|
resp = await this.get();
|
2016-10-07 00:52:27 +03:00
|
|
|
if (!resp.success) {
|
2017-05-30 20:23:57 +03:00
|
|
|
recordBuffer = [];
|
2016-10-07 00:52:27 +03:00
|
|
|
break;
|
|
|
|
}
|
2017-05-30 20:23:57 +03:00
|
|
|
for (let json of resp.obj) {
|
|
|
|
let record = new this._recordObj();
|
|
|
|
record.deserialize(json);
|
|
|
|
recordBuffer.push(record);
|
|
|
|
}
|
2016-10-07 00:52:27 +03:00
|
|
|
|
|
|
|
// Initialize last modified, or check that something broken isn't happening.
|
|
|
|
let lastModified = resp.headers["x-last-modified"];
|
|
|
|
if (!lastModifiedTime) {
|
|
|
|
lastModifiedTime = lastModified;
|
|
|
|
this.setHeader("X-If-Unmodified-Since", lastModified);
|
|
|
|
} else if (lastModified != lastModifiedTime) {
|
|
|
|
// Should be impossible -- We'd get a 412 in this case.
|
|
|
|
throw new Error(
|
|
|
|
"X-Last-Modified changed in the middle of a download batch! " +
|
2017-10-15 21:50:30 +03:00
|
|
|
`${lastModified} => ${lastModifiedTime}`
|
|
|
|
);
|
2016-10-07 00:52:27 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// If this is missing, we're finished.
|
|
|
|
this.offset = resp.headers["x-weave-next-offset"];
|
|
|
|
} while (this.offset && totalLimit > recordBuffer.length);
|
|
|
|
} finally {
|
|
|
|
// Ensure we undo any temporary state so that subsequent calls to get()
|
|
|
|
// or getBatched() work properly. We do this before calling the record
|
|
|
|
// handler so that we can more convincingly pretend to be a normal get()
|
|
|
|
// call. Note: we're resetting these to the values they had before this
|
|
|
|
// function was called.
|
|
|
|
this._limit = totalLimit;
|
|
|
|
this._offset = null;
|
|
|
|
delete this._headers["x-if-unmodified-since"];
|
|
|
|
this._rebuildURL();
|
|
|
|
}
|
2017-05-30 20:23:57 +03:00
|
|
|
return { response: resp, records: recordBuffer };
|
2012-09-15 03:02:32 +04:00
|
|
|
},
|
2016-01-21 04:30:25 +03:00
|
|
|
|
|
|
|
// This object only supports posting via the postQueue object.
|
|
|
|
post() {
|
|
|
|
throw new Error(
|
|
|
|
"Don't directly post to a collection - use newPostQueue instead"
|
|
|
|
);
|
|
|
|
},
|
|
|
|
|
2016-08-24 23:02:14 +03:00
|
|
|
newPostQueue(log, timestamp, postCallback) {
|
|
|
|
let poster = (data, headers, batch, commit) => {
|
|
|
|
this.batch = batch;
|
|
|
|
this.commit = commit;
|
|
|
|
for (let [header, value] of headers) {
|
|
|
|
this.setHeader(header, value);
|
|
|
|
}
|
2016-01-21 04:30:25 +03:00
|
|
|
return Resource.prototype.post.call(this, data);
|
2017-10-15 21:50:30 +03:00
|
|
|
};
|
2017-10-02 23:42:22 +03:00
|
|
|
return new PostQueue(
|
|
|
|
poster,
|
|
|
|
timestamp,
|
|
|
|
this._service.serverConfiguration || {},
|
|
|
|
log,
|
|
|
|
postCallback
|
|
|
|
);
|
|
|
|
},
|
|
|
|
};
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
// These are limits for requests provided by the server at the
|
|
|
|
// info/configuration endpoint -- server documentation is available here:
|
|
|
|
// http://moz-services-docs.readthedocs.io/en/latest/storage/apis-1.5.html#api-instructions
|
|
|
|
//
|
|
|
|
// All are optional, however we synthesize (non-infinite) default values for the
|
|
|
|
// "max_request_bytes" and "max_record_payload_bytes" options. For the others,
|
|
|
|
// we ignore them (we treat the limit is infinite) if they're missing.
|
|
|
|
//
|
|
|
|
// These are also the only ones that all servers (even batching-disabled
|
|
|
|
// servers) should support, at least once this sync-serverstorage patch is
|
|
|
|
// everywhere https://github.com/mozilla-services/server-syncstorage/pull/74
|
|
|
|
//
|
|
|
|
// Batching enabled servers also limit the amount of payload data and number
|
|
|
|
// of and records we can send in a single post as well as in the whole batch.
|
|
|
|
// Note that the byte limits for these there are just with respect to the
|
|
|
|
// *payload* data, e.g. the data appearing in the payload property (a
|
|
|
|
// string) of the object.
|
|
|
|
//
|
|
|
|
// Note that in practice, these limits should be sensible, but the code makes
|
|
|
|
// no assumptions about this. If we hit any of the limits, we perform the
|
|
|
|
// corresponding action (e.g. submit a request, possibly committing the
|
|
|
|
// current batch).
|
|
|
|
const DefaultPostQueueConfig = Object.freeze({
|
|
|
|
// Number of total bytes allowed in a request
|
|
|
|
max_request_bytes: 260 * 1024,
|
|
|
|
|
|
|
|
// Maximum number of bytes allowed in the "payload" property of a record.
|
|
|
|
max_record_payload_bytes: 256 * 1024,
|
|
|
|
|
|
|
|
// The limit for how many bytes worth of data appearing in "payload"
|
|
|
|
// properties are allowed in a single post.
|
|
|
|
max_post_bytes: Infinity,
|
|
|
|
|
|
|
|
// The limit for the number of records allowed in a single post.
|
|
|
|
max_post_records: Infinity,
|
|
|
|
|
|
|
|
// The limit for how many bytes worth of data appearing in "payload"
|
|
|
|
// properties are allowed in a batch. (Same as max_post_bytes, but for
|
|
|
|
// batches).
|
|
|
|
max_total_bytes: Infinity,
|
|
|
|
|
|
|
|
// The limit for the number of records allowed in a single post. (Same
|
|
|
|
// as max_post_records, but for batches).
|
|
|
|
max_total_records: Infinity,
|
|
|
|
});
|
|
|
|
|
|
|
|
// Manages a pair of (byte, count) limits for a PostQueue, such as
|
|
|
|
// (max_post_bytes, max_post_records) or (max_total_bytes, max_total_records).
|
|
|
|
class LimitTracker {
|
|
|
|
constructor(maxBytes, maxRecords) {
|
|
|
|
this.maxBytes = maxBytes;
|
|
|
|
this.maxRecords = maxRecords;
|
|
|
|
this.curBytes = 0;
|
|
|
|
this.curRecords = 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
clear() {
|
|
|
|
this.curBytes = 0;
|
|
|
|
this.curRecords = 0;
|
|
|
|
}
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
canAddRecord(payloadSize) {
|
|
|
|
// The record counts are inclusive, but depending on the version of the
|
|
|
|
// server, the byte counts may or may not be inclusive (See
|
|
|
|
// https://github.com/mozilla-services/server-syncstorage/issues/73).
|
|
|
|
return (
|
|
|
|
this.curRecords + 1 <= this.maxRecords &&
|
|
|
|
this.curBytes + payloadSize < this.maxBytes
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
canNeverAdd(recordSize) {
|
|
|
|
return recordSize >= this.maxBytes;
|
|
|
|
}
|
|
|
|
|
|
|
|
didAddRecord(recordSize) {
|
|
|
|
if (!this.canAddRecord(recordSize)) {
|
|
|
|
// This is a bug, caller is expected to call canAddRecord first.
|
|
|
|
throw new Error(
|
|
|
|
"LimitTracker.canAddRecord must be checked before adding record"
|
|
|
|
);
|
2016-08-24 23:02:14 +03:00
|
|
|
}
|
2017-10-02 23:42:22 +03:00
|
|
|
this.curRecords += 1;
|
|
|
|
this.curBytes += recordSize;
|
|
|
|
}
|
|
|
|
}
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2016-01-21 04:30:25 +03:00
|
|
|
/* A helper to manage the posting of records while respecting the various
|
|
|
|
size limits.
|
2016-08-24 23:02:14 +03:00
|
|
|
|
|
|
|
This supports the concept of a server-side "batch". The general idea is:
|
|
|
|
* We queue as many records as allowed in memory, then make a single POST.
|
|
|
|
* This first POST (optionally) gives us a batch ID, which we use for
|
|
|
|
all subsequent posts, until...
|
|
|
|
* At some point we hit a batch-maximum, and jump through a few hoops to
|
|
|
|
commit the current batch (ie, all previous POSTs) and start a new one.
|
|
|
|
* Eventually commit the final batch.
|
|
|
|
|
|
|
|
In most cases we expect there to be exactly 1 batch consisting of possibly
|
|
|
|
multiple POSTs.
|
2016-01-21 04:30:25 +03:00
|
|
|
*/
|
2017-10-02 23:42:22 +03:00
|
|
|
function PostQueue(poster, timestamp, serverConfig, log, postCallback) {
|
2016-01-21 04:30:25 +03:00
|
|
|
// The "post" function we should use when it comes time to do the post.
|
|
|
|
this.poster = poster;
|
|
|
|
this.log = log;
|
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
let config = Object.assign({}, DefaultPostQueueConfig, serverConfig);
|
|
|
|
|
|
|
|
if (!serverConfig.max_request_bytes && serverConfig.max_post_bytes) {
|
|
|
|
// Use max_post_bytes for max_request_bytes if it's missing. Only needed
|
|
|
|
// until server-syncstorage/pull/74 is everywhere, and even then it's
|
|
|
|
// unnecessary if the server limits are configured sanely (there's no
|
|
|
|
// guarantee of -- at least before that is fully deployed)
|
|
|
|
config.max_request_bytes = serverConfig.max_post_bytes;
|
|
|
|
}
|
|
|
|
|
|
|
|
this.log.trace("new PostQueue config (after defaults): ", config);
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2016-01-21 04:30:25 +03:00
|
|
|
// The callback we make with the response when we do get around to making the
|
|
|
|
// post (which could be during any of the enqueue() calls or the final flush())
|
|
|
|
// This callback may be called multiple times and must not add new items to
|
|
|
|
// the queue.
|
2016-08-24 23:02:14 +03:00
|
|
|
// The second argument passed to this callback is a boolean value that is true
|
|
|
|
// if we're in the middle of a batch, and false if either the batch is
|
|
|
|
// complete, or it's a post to a server that does not understand batching.
|
2016-01-21 04:30:25 +03:00
|
|
|
this.postCallback = postCallback;
|
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
// Tracks the count and combined payload size for the records we've queued
|
|
|
|
// so far but are yet to POST.
|
|
|
|
this.postLimits = new LimitTracker(
|
|
|
|
config.max_post_bytes,
|
|
|
|
config.max_post_records
|
|
|
|
);
|
|
|
|
|
|
|
|
// As above, but for the batch size.
|
|
|
|
this.batchLimits = new LimitTracker(
|
|
|
|
config.max_total_bytes,
|
|
|
|
config.max_total_records
|
|
|
|
);
|
|
|
|
|
|
|
|
// Limit for the size of `this.queued` before we do a post.
|
|
|
|
this.maxRequestBytes = config.max_request_bytes;
|
|
|
|
|
|
|
|
// Limit for the size of incoming record payloads.
|
|
|
|
this.maxPayloadBytes = config.max_record_payload_bytes;
|
|
|
|
|
2016-01-21 04:30:25 +03:00
|
|
|
// The string where we are capturing the stringified version of the records
|
|
|
|
// queued so far. It will always be invalid JSON as it is always missing the
|
2017-10-02 23:42:22 +03:00
|
|
|
// closing bracket. It's also used to track whether or not we've gone past
|
|
|
|
// maxRequestBytes.
|
2016-01-21 04:30:25 +03:00
|
|
|
this.queued = "";
|
|
|
|
|
2016-08-24 23:02:14 +03:00
|
|
|
// The ID of our current batch. Can be undefined (meaning we are yet to make
|
|
|
|
// the first post of a patch, so don't know if we have a batch), null (meaning
|
|
|
|
// we've made the first post but the server response indicated no batching
|
|
|
|
// semantics), otherwise we have made the first post and it holds the batch ID
|
|
|
|
// returned from the server.
|
|
|
|
this.batchID = undefined;
|
|
|
|
|
|
|
|
// Time used for X-If-Unmodified-Since -- should be the timestamp from the last GET.
|
|
|
|
this.lastModified = timestamp;
|
2016-01-21 04:30:25 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
PostQueue.prototype = {
|
2017-06-06 01:50:07 +03:00
|
|
|
async enqueue(record) {
|
2016-01-21 04:30:25 +03:00
|
|
|
// We want to ensure the record has a .toJSON() method defined - even
|
|
|
|
// though JSON.stringify() would implicitly call it, the stringify might
|
|
|
|
// still work even if it isn't defined, which isn't what we want.
|
|
|
|
let jsonRepr = record.toJSON();
|
|
|
|
if (!jsonRepr) {
|
|
|
|
throw new Error(
|
|
|
|
"You must only call this with objects that explicitly support JSON"
|
|
|
|
);
|
|
|
|
}
|
2017-09-14 04:02:41 +03:00
|
|
|
|
2016-01-21 04:30:25 +03:00
|
|
|
let bytes = JSON.stringify(jsonRepr);
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
// We use the payload size for the LimitTrackers, since that's what the
|
|
|
|
// byte limits other than max_request_bytes refer to.
|
|
|
|
let payloadLength = jsonRepr.payload.length;
|
2017-09-14 04:02:41 +03:00
|
|
|
|
|
|
|
// The `+ 2` is to account for the 2-byte (maximum) overhead (one byte for
|
|
|
|
// the leading comma or "[", which all records will have, and the other for
|
|
|
|
// the final trailing "]", only present for the last record).
|
2017-10-02 23:42:22 +03:00
|
|
|
let encodedLength = bytes.length + 2;
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
// Check first if there's some limit that indicates we cannot ever enqueue
|
|
|
|
// this record.
|
|
|
|
let isTooBig =
|
|
|
|
this.postLimits.canNeverAdd(payloadLength) ||
|
|
|
|
this.batchLimits.canNeverAdd(payloadLength) ||
|
|
|
|
encodedLength >= this.maxRequestBytes ||
|
|
|
|
payloadLength >= this.maxPayloadBytes;
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
if (isTooBig) {
|
|
|
|
return {
|
|
|
|
enqueued: false,
|
|
|
|
error: new Error("Single record too large to submit to server"),
|
|
|
|
};
|
|
|
|
}
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
let canPostRecord = this.postLimits.canAddRecord(payloadLength);
|
|
|
|
let canBatchRecord = this.batchLimits.canAddRecord(payloadLength);
|
|
|
|
let canSendRecord =
|
|
|
|
this.queued.length + encodedLength < this.maxRequestBytes;
|
2016-08-24 23:02:14 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
if (!canPostRecord || !canBatchRecord || !canSendRecord) {
|
|
|
|
this.log.trace("PostQueue flushing: ", {
|
|
|
|
canPostRecord,
|
|
|
|
canSendRecord,
|
|
|
|
canBatchRecord,
|
|
|
|
});
|
2016-08-24 23:02:14 +03:00
|
|
|
// We need to write the queue out before handling this one, but we only
|
2017-10-02 23:42:22 +03:00
|
|
|
// commit the batch (and thus start a new one) if the record couldn't fit
|
|
|
|
// inside the batch.
|
|
|
|
await this.flush(!canBatchRecord);
|
2016-01-21 04:30:25 +03:00
|
|
|
}
|
2017-09-14 04:02:41 +03:00
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
this.postLimits.didAddRecord(payloadLength);
|
|
|
|
this.batchLimits.didAddRecord(payloadLength);
|
|
|
|
|
2016-01-21 04:30:25 +03:00
|
|
|
// Either a ',' or a '[' depending on whether this is the first record.
|
2017-10-02 23:42:22 +03:00
|
|
|
this.queued += this.queued.length ? "," : "[";
|
2016-01-21 04:30:25 +03:00
|
|
|
this.queued += bytes;
|
2016-08-24 23:02:14 +03:00
|
|
|
return { enqueued: true };
|
2016-01-21 04:30:25 +03:00
|
|
|
},
|
|
|
|
|
2017-06-06 01:50:07 +03:00
|
|
|
async flush(finalBatchPost) {
|
2016-01-21 04:30:25 +03:00
|
|
|
if (!this.queued) {
|
2016-08-24 23:02:14 +03:00
|
|
|
// nothing queued - we can't be in a batch, and something has gone very
|
|
|
|
// bad if we think we are.
|
|
|
|
if (this.batchID) {
|
|
|
|
throw new Error(
|
|
|
|
`Flush called when no queued records but we are in a batch ${
|
|
|
|
this.batchID
|
|
|
|
}`
|
|
|
|
);
|
|
|
|
}
|
2016-01-21 04:30:25 +03:00
|
|
|
return;
|
|
|
|
}
|
2016-08-24 23:02:14 +03:00
|
|
|
// the batch query-param and headers we'll send.
|
|
|
|
let batch;
|
|
|
|
let headers = [];
|
|
|
|
if (this.batchID === undefined) {
|
|
|
|
// First commit in a (possible) batch.
|
|
|
|
batch = "true";
|
|
|
|
} else if (this.batchID) {
|
|
|
|
// We have an existing batch.
|
|
|
|
batch = this.batchID;
|
|
|
|
} else {
|
|
|
|
// Not the first post and we know we have no batch semantics.
|
|
|
|
batch = null;
|
|
|
|
}
|
|
|
|
|
|
|
|
headers.push(["x-if-unmodified-since", this.lastModified]);
|
|
|
|
|
2017-10-02 23:42:22 +03:00
|
|
|
let numQueued = this.postLimits.curRecords;
|
|
|
|
this.log.info(
|
|
|
|
`Posting ${numQueued} records of ${this.queued.length +
|
|
|
|
1} bytes with batch=${batch}`
|
|
|
|
);
|
2016-01-21 04:30:25 +03:00
|
|
|
let queued = this.queued + "]";
|
2016-08-24 23:02:14 +03:00
|
|
|
if (finalBatchPost) {
|
2017-10-02 23:42:22 +03:00
|
|
|
this.batchLimits.clear();
|
2016-08-24 23:02:14 +03:00
|
|
|
}
|
2017-10-02 23:42:22 +03:00
|
|
|
this.postLimits.clear();
|
2016-01-21 04:30:25 +03:00
|
|
|
this.queued = "";
|
2017-06-06 01:50:07 +03:00
|
|
|
let response = await this.poster(
|
|
|
|
queued,
|
|
|
|
headers,
|
|
|
|
batch,
|
|
|
|
!!(finalBatchPost && this.batchID !== null)
|
|
|
|
);
|
2016-08-24 23:02:14 +03:00
|
|
|
|
|
|
|
if (!response.success) {
|
|
|
|
this.log.trace("Server error response during a batch", response);
|
|
|
|
// not clear what we should do here - we expect the consumer of this to
|
|
|
|
// abort by throwing in the postCallback below.
|
2018-12-18 02:34:04 +03:00
|
|
|
await this.postCallback(this, response, !finalBatchPost);
|
2017-02-17 04:34:45 +03:00
|
|
|
return;
|
2016-08-24 23:02:14 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (finalBatchPost) {
|
|
|
|
this.log.trace("Committed batch", this.batchID);
|
|
|
|
this.batchID = undefined; // we are now in "first post for the batch" state.
|
|
|
|
this.lastModified = response.headers["x-last-modified"];
|
2018-12-18 02:34:04 +03:00
|
|
|
await this.postCallback(this, response, false);
|
2017-02-17 04:34:45 +03:00
|
|
|
return;
|
2016-08-24 23:02:14 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (response.status != 202) {
|
|
|
|
if (this.batchID) {
|
|
|
|
throw new Error(
|
|
|
|
"Server responded non-202 success code while a batch was in progress"
|
|
|
|
);
|
|
|
|
}
|
|
|
|
this.batchID = null; // no batch semantics are in place.
|
|
|
|
this.lastModified = response.headers["x-last-modified"];
|
2018-12-18 02:34:04 +03:00
|
|
|
await this.postCallback(this, response, false);
|
2017-02-17 04:34:45 +03:00
|
|
|
return;
|
2016-08-24 23:02:14 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
// this response is saying the server has batch semantics - we should
|
|
|
|
// always have a batch ID in the response.
|
|
|
|
let responseBatchID = response.obj.batch;
|
|
|
|
this.log.trace("Server responsed 202 with batch", responseBatchID);
|
|
|
|
if (!responseBatchID) {
|
|
|
|
this.log.error(
|
|
|
|
"Invalid server response: 202 without a batch ID",
|
|
|
|
response
|
|
|
|
);
|
|
|
|
throw new Error("Invalid server response: 202 without a batch ID");
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.batchID === undefined) {
|
|
|
|
this.batchID = responseBatchID;
|
|
|
|
if (!this.lastModified) {
|
|
|
|
this.lastModified = response.headers["x-last-modified"];
|
|
|
|
if (!this.lastModified) {
|
|
|
|
throw new Error("Batch response without x-last-modified");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
if (this.batchID != responseBatchID) {
|
|
|
|
throw new Error(
|
|
|
|
`Invalid client/server batch state - client has ${
|
|
|
|
this.batchID
|
|
|
|
}, server has ${responseBatchID}`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2018-12-18 02:34:04 +03:00
|
|
|
await this.postCallback(this, response, true);
|
2016-01-21 04:30:25 +03:00
|
|
|
},
|
2017-10-15 21:50:30 +03:00
|
|
|
};
|