1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
5 import { XPCOMUtils } from "resource://gre/modules/XPCOMUtils.sys.mjs";
7 import { JSONFile } from "resource://gre/modules/JSONFile.sys.mjs";
8 import { Log } from "resource://gre/modules/Log.sys.mjs";
10 import { Async } from "resource://services-common/async.sys.mjs";
11 import { Observers } from "resource://services-common/observers.sys.mjs";
14 DEFAULT_DOWNLOAD_BATCH_SIZE,
15 DEFAULT_GUID_FETCH_BATCH_SIZE,
16 ENGINE_BATCH_INTERRUPTED,
21 } from "resource://services-sync/constants.sys.mjs";
26 } from "resource://services-sync/record.sys.mjs";
27 import { Resource } from "resource://services-sync/resource.sys.mjs";
32 } from "resource://services-sync/util.sys.mjs";
33 import { SyncedRecordsTelemetry } from "resource://services-sync/telemetry.sys.mjs";
37 ChromeUtils.defineESModuleGetters(lazy, {
38 PlacesUtils: "resource://gre/modules/PlacesUtils.sys.mjs",
41 function ensureDirectory(path) {
42 return IOUtils.makeDirectory(PathUtils.parent(path), {
43 createAncestors: true,
48 * Trackers are associated with a single engine and deal with
49 * listening for changes to their particular data type.
51 * The base `Tracker` only supports listening for changes, and bumping the score
52 * to indicate how urgently the engine wants to sync. It does not persist any
53 * data. Engines that track changes directly in the storage layer (like
54 * bookmarks, bridged engines, addresses, and credit cards) or only upload a
55 * single record (tabs and preferences) should subclass `Tracker`.
57 export function Tracker(name, engine) {
59 throw new Error("Tracker must be associated with an Engine instance.");
62 name = name || "Unnamed";
63 this.name = name.toLowerCase();
66 this._log = Log.repository.getLogger(`Sync.Engine.${name}.Tracker`);
70 this.asyncObserver = Async.asyncObserver(this, this._log);
74 // New-style trackers use change sources to filter out changes made by Sync in
75 // observer notifications, so we don't want to let the engine ignore all
76 // changes during a sync.
81 // Define an empty setter so that the engine doesn't throw a `TypeError`
82 // setting a read-only property.
83 set ignoreAll(value) {},
86 * Score can be called as often as desired to decide which engines to sync
88 * Valid values for score:
89 * -1: Do not sync unless the user specifically requests it (almost disabled)
90 * 0: Nothing has changed
91 * 100: Please sync me ASAP!
93 * Setting it to other values should (but doesn't currently) throw an exception
101 Observers.notify("weave:engine:score:updated", this.name);
104 // Should be called by service everytime a sync has been done for an engine
109 // Unsupported, and throws a more descriptive error to ensure callers aren't
110 // accidentally using persistence.
111 async getChangedIDs() {
112 throw new TypeError("This tracker doesn't store changed IDs");
116 async addChangedID(id, when) {
117 throw new TypeError("Can't add changed ID to this tracker");
121 async removeChangedID(...ids) {
122 throw new TypeError("Can't remove changed IDs from this tracker");
125 // This method is called at various times, so we override with a no-op
126 // instead of throwing.
127 clearChangedIDs() {},
130 return Date.now() / 1000;
136 if (!this.engineIsEnabled()) {
139 this._log.trace("start().");
140 if (!this._isTracking) {
142 this._isTracking = true;
147 this._log.trace("stop().");
148 if (this._isTracking) {
149 await this.asyncObserver.promiseObserversComplete();
151 this._isTracking = false;
155 // Override these in your subclasses.
158 async observe(subject, topic, data) {},
162 // Can't tell -- we must be running in a test!
165 return this.engine.enabled;
169 * Starts or stops listening for changes depending on the associated engine's
172 * @param {Boolean} engineEnabled Whether the engine was enabled.
174 async onEngineEnabledChanged(engineEnabled) {
175 if (engineEnabled == this._isTracking) {
183 this.clearChangedIDs();
193 * A tracker that persists a list of IDs for all changed items that need to be
194 * synced. This is 🚨 _extremely deprecated_ 🚨 and only kept around for current
195 * engines. ⚠️ Please **don't use it** for new engines! ⚠️
197 * Why is this kind of external change tracking deprecated? Because it causes
198 * consistency issues due to missed notifications, interrupted syncs, and the
199 * tracker's view of what changed diverging from the data store's.
201 export function LegacyTracker(name, engine) {
202 Tracker.call(this, name, engine);
205 this.file = this.name;
206 this._storage = new JSONFile({
207 path: Utils.jsonFilePath("changes", this.file),
208 dataPostProcessor: json => this._dataPostProcessor(json),
209 beforeSave: () => this._beforeSave(),
211 this._ignoreAll = false;
214 LegacyTracker.prototype = {
216 return this._ignoreAll;
219 set ignoreAll(value) {
220 this._ignoreAll = value;
223 // Default to an empty object if the file doesn't exist.
224 _dataPostProcessor(json) {
225 return (typeof json == "object" && json) || {};
228 // Ensure the Weave storage directory exists before writing the file.
230 return ensureDirectory(this._storage.path);
233 async getChangedIDs() {
234 await this._storage.load();
235 return this._storage.data;
239 this._storage.saveSoon();
242 // ignore/unignore specific IDs. Useful for ignoring items that are
243 // being processed, or that shouldn't be synced.
244 // But note: not persisted to disk
248 this._ignored.push(id);
252 let index = this._ignored.indexOf(id);
254 this._ignored.splice(index, 1);
258 async _saveChangedID(id, when) {
259 this._log.trace(`Adding changed ID: ${id}, ${JSON.stringify(when)}`);
260 const changedIDs = await this.getChangedIDs();
261 changedIDs[id] = when;
262 this._saveChangedIDs();
265 async addChangedID(id, when) {
267 this._log.warn("Attempted to add undefined ID to tracker");
271 if (this.ignoreAll || this._ignored.includes(id)) {
275 // Default to the current time in seconds if no time is provided.
280 const changedIDs = await this.getChangedIDs();
281 // Add/update the entry if we have a newer time.
282 if ((changedIDs[id] || -Infinity) < when) {
283 await this._saveChangedID(id, when);
289 async removeChangedID(...ids) {
290 if (!ids.length || this.ignoreAll) {
293 for (let id of ids) {
295 this._log.warn("Attempted to remove undefined ID from tracker");
298 if (this._ignored.includes(id)) {
299 this._log.debug(`Not removing ignored ID ${id} from tracker`);
302 const changedIDs = await this.getChangedIDs();
303 if (changedIDs[id] != null) {
304 this._log.trace("Removing changed ID " + id);
305 delete changedIDs[id];
308 this._saveChangedIDs();
313 this._log.trace("Clearing changed ID list");
314 this._storage.data = {};
315 this._saveChangedIDs();
319 // Persist all pending tracked changes to disk, and wait for the final write
321 await super.finalize();
322 this._saveChangedIDs();
323 await this._storage.finalize();
326 Object.setPrototypeOf(LegacyTracker.prototype, Tracker.prototype);
329 * The Store serves as the interface between Sync and stored data.
331 * The name "store" is slightly a misnomer because it doesn't actually "store"
332 * anything. Instead, it serves as a gateway to something that actually does
335 * The store is responsible for record management inside an engine. It tells
336 * Sync what items are available for Sync, converts items to and from Sync's
337 * record format, and applies records from Sync into changes on the underlying
340 * Store implementations require a number of functions to be implemented. These
341 * are all documented below.
343 * For stores that deal with many records or which have expensive store access
344 * routines, it is highly recommended to implement a custom applyIncomingBatch
345 * and/or applyIncoming function on top of the basic APIs.
348 export function Store(name, engine) {
350 throw new Error("Store must be associated with an Engine instance.");
353 name = name || "Unnamed";
354 this.name = name.toLowerCase();
355 this.engine = engine;
357 this._log = Log.repository.getLogger(`Sync.Engine.${name}.Store`);
359 ChromeUtils.defineLazyGetter(this, "_timer", function () {
360 return Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
366 * Apply multiple incoming records against the store.
368 * This is called with a set of incoming records to process. The function
369 * should look at each record, reconcile with the current local state, and
370 * make the local changes required to bring its state in alignment with the
373 * The default implementation simply iterates over all records and calls
374 * applyIncoming(). Store implementations may overwrite this function
377 * @param records Array of records to apply
378 * @param a SyncedRecordsTelemetry obj that will keep track of failed reasons
379 * @return Array of record IDs which did not apply cleanly
381 async applyIncomingBatch(records, countTelemetry) {
384 await Async.yieldingForEach(records, async record => {
386 await this.applyIncoming(record);
388 if (ex.code == SyncEngine.prototype.eEngineAbortApplyIncoming) {
389 // This kind of exception should have a 'cause' attribute, which is an
390 // originating exception.
391 // ex.cause will carry its stack with it when rethrown.
394 if (Async.isShutdownException(ex)) {
397 this._log.warn("Failed to apply incoming record " + record.id, ex);
398 failed.push(record.id);
399 countTelemetry.addIncomingFailedReason(ex.message);
407 * Apply a single record against the store.
409 * This takes a single record and makes the local changes required so the
410 * local state matches what's in the record.
412 * The default implementation calls one of remove(), create(), or update()
413 * depending on the state obtained from the store itself. Store
414 * implementations may overwrite this function if desired.
419 async applyIncoming(record) {
420 if (record.deleted) {
421 await this.remove(record);
422 } else if (!(await this.itemExists(record.id))) {
423 await this.create(record);
425 await this.update(record);
429 // override these in derived objects
432 * Create an item in the store from a record.
434 * This is called by the default implementation of applyIncoming(). If using
435 * applyIncomingBatch(), this won't be called unless your store calls it.
438 * The store record to create an item from
440 async create(record) {
441 throw new Error("override create in a subclass");
445 * Remove an item in the store from a record.
447 * This is called by the default implementation of applyIncoming(). If using
448 * applyIncomingBatch(), this won't be called unless your store calls it.
451 * The store record to delete an item from
453 async remove(record) {
454 throw new Error("override remove in a subclass");
458 * Update an item from a record.
460 * This is called by the default implementation of applyIncoming(). If using
461 * applyIncomingBatch(), this won't be called unless your store calls it.
464 * The record to use to update an item from
466 async update(record) {
467 throw new Error("override update in a subclass");
471 * Determine whether a record with the specified ID exists.
473 * Takes a string record ID and returns a booleans saying whether the record
478 * @return boolean indicating whether record exists locally
480 async itemExists(id) {
481 throw new Error("override itemExists in a subclass");
485 * Create a record from the specified ID.
487 * If the ID is known, the record should be populated with metadata from
488 * the store. If the ID is not known, the record should be created with the
489 * delete field set to true.
494 * Collection to add record to. This is typically passed into the
495 * constructor for the newly-created record.
496 * @return record type for this engine
498 async createRecord(id, collection) {
499 throw new Error("override createRecord in a subclass");
503 * Change the ID of a record.
506 * string old/current record ID
508 * string new record ID
510 async changeItemID(oldID, newID) {
511 throw new Error("override changeItemID in a subclass");
515 * Obtain the set of all known record IDs.
517 * @return Object with ID strings as keys and values of true. The values
521 throw new Error("override getAllIDs in a subclass");
525 * Wipe all data in the store.
527 * This function is called during remote wipes or when replacing local data
530 * This function should delete all local data that the store is managing. It
531 * can be thought of as clearing out all state and restoring the "new
535 throw new Error("override wipe in a subclass");
539 export function EngineManager(service) {
540 this.service = service;
544 this._altEngineInfo = {};
546 // This will be populated by Service on startup.
547 this._declined = new Set();
548 this._log = Log.repository.getLogger("Sync.EngineManager");
549 this._log.manageLevelFromPref("services.sync.log.logger.service.engines");
550 // define the default level for all engine logs here (although each engine
551 // allows its level to be controlled via a specific, non-default pref)
553 .getLogger(`Sync.Engine`)
554 .manageLevelFromPref("services.sync.log.logger.engine");
557 EngineManager.prototype = {
559 // Return an array of engines if we have an array of names
560 if (Array.isArray(name)) {
562 name.forEach(function (name) {
563 let engine = this.get(name);
565 engines.push(engine);
571 return this._engines[name]; // Silently returns undefined for unknown names.
576 for (let [, engine] of Object.entries(this._engines)) {
577 engines.push(engine);
583 * If a user has changed a pref that controls which variant of a sync engine
584 * for a given collection we use, unregister the old engine and register the
587 * This is called by EngineSynchronizer before every sync.
589 async switchAlternatives() {
590 for (let [name, info] of Object.entries(this._altEngineInfo)) {
591 let prefValue = info.prefValue;
592 if (prefValue === info.lastValue) {
594 `No change for engine ${name} (${info.pref} is still ${prefValue})`
598 // Unregister the old engine, register the new one.
600 `Switching ${name} engine ("${info.pref}" went from ${info.lastValue} => ${prefValue})`
603 await this._removeAndFinalize(name);
605 this._log.warn(`Failed to remove previous ${name} engine...`, e);
607 let engineType = prefValue ? info.whenTrue : info.whenFalse;
609 // If register throws, we'll try again next sync, but until then there
610 // won't be an engine registered for this collection.
611 await this.register(engineType);
612 info.lastValue = prefValue;
613 // Note: engineType.name is using Function.prototype.name.
614 this._log.info(`Switched the ${name} engine to use ${engineType.name}`);
617 `Switching the ${name} engine to use ${engineType.name} failed (couldn't register)`,
624 async registerAlternatives(name, pref, whenTrue, whenFalse) {
625 let info = { name, pref, whenTrue, whenFalse };
627 XPCOMUtils.defineLazyPreferenceGetter(info, "prefValue", pref, false);
629 let chosen = info.prefValue ? info.whenTrue : info.whenFalse;
630 info.lastValue = info.prefValue;
631 this._altEngineInfo[name] = info;
633 await this.register(chosen);
637 * N.B., does not pay attention to the declined list.
641 .filter(engine => engine.enabled)
642 .sort((a, b) => a.syncPriority - b.syncPriority);
645 get enabledEngineNames() {
646 return this.getEnabled().map(e => e.name);
650 Svc.PrefBranch.setCharPref(
652 [...this._declined].join(",")
660 return [...this._declined];
663 setDeclined(engines) {
664 this._declined = new Set(engines);
665 this.persistDeclined();
668 isDeclined(engineName) {
669 return this._declined.has(engineName);
673 * Accepts a Set or an array.
676 for (let e of engines) {
677 this._declined.add(e);
679 this.persistDeclined();
683 for (let e of engines) {
684 this._declined.delete(e);
686 this.persistDeclined();
690 * Register an Engine to the service. Alternatively, give an array of engine
691 * objects to register.
693 * @param engineObject
694 * Engine object used to get an instance of the engine
695 * @return The engine object if anything failed
697 async register(engineObject) {
698 if (Array.isArray(engineObject)) {
699 for (const e of engineObject) {
700 await this.register(e);
706 let engine = new engineObject(this.service);
707 let name = engine.name;
708 if (name in this._engines) {
709 this._log.error("Engine '" + name + "' is already registered!");
711 if (engine.initialize) {
712 await engine.initialize();
714 this._engines[name] = engine;
717 let name = engineObject || "";
718 name = name.prototype || "";
719 name = name.name || "";
721 this._log.error(`Could not initialize engine ${name}`, ex);
725 async unregister(val) {
727 if (val instanceof SyncEngine) {
730 await this._removeAndFinalize(name);
731 delete this._altEngineInfo[name];
734 // Common code for disabling an engine by name, that doesn't complain if the
735 // engine doesn't exist. Doesn't touch the engine's alternative info (if any
737 async _removeAndFinalize(name) {
738 if (name in this._engines) {
739 let engine = this._engines[name];
740 delete this._engines[name];
741 await engine.finalize();
746 for (let name in this._engines) {
747 let engine = this._engines[name];
748 delete this._engines[name];
749 await engine.finalize();
751 this._altEngineInfo = {};
755 export function SyncEngine(name, service) {
757 throw new Error("SyncEngine must be associated with a Service instance.");
760 this.Name = name || "Unnamed";
761 this.name = name.toLowerCase();
762 this.service = service;
764 this._notify = Utils.notify("weave:engine:");
765 this._log = Log.repository.getLogger("Sync.Engine." + this.Name);
766 this._log.manageLevelFromPref(`services.sync.log.logger.engine.${this.name}`);
768 this._modified = this.emptyChangeset();
769 this._tracker; // initialize tracker to load previously changed IDs
770 this._log.debug("Engine constructed");
772 this._toFetchStorage = new JSONFile({
773 path: Utils.jsonFilePath("toFetch", this.name),
774 dataPostProcessor: json => this._metadataPostProcessor(json),
775 beforeSave: () => this._beforeSaveMetadata(),
778 this._previousFailedStorage = new JSONFile({
779 path: Utils.jsonFilePath("failed", this.name),
780 dataPostProcessor: json => this._metadataPostProcessor(json),
781 beforeSave: () => this._beforeSaveMetadata(),
784 XPCOMUtils.defineLazyPreferenceGetter(
787 `services.sync.engine.${this.prefName}`,
790 XPCOMUtils.defineLazyPreferenceGetter(
793 `services.sync.${this.name}.syncID`,
796 XPCOMUtils.defineLazyPreferenceGetter(
799 `services.sync.${this.name}.lastSync`,
804 // Async initializations can be made in the initialize() method.
806 this.asyncObserver = Async.asyncObserver(this, this._log);
809 // Enumeration to define approaches to handling bad records.
810 // Attached to the constructor to allow use as a kind of static enumeration.
811 SyncEngine.kRecoveryStrategy = {
817 SyncEngine.prototype = {
818 _recordObj: CryptoWrapper,
819 // _storeObj, and _trackerObj should to be overridden in subclasses
821 _trackerObj: Tracker,
825 // Signal to the engine that processing further records is pointless.
826 eEngineAbortApplyIncoming: "error.engine.abort.applyincoming",
828 // Should we keep syncing if we find a record that cannot be uploaded (ever)?
829 // If this is false, we'll throw, otherwise, we'll ignore the record and
830 // continue. This currently can only happen due to the record being larger
831 // than the record upload limit.
832 allowSkippedRecord: true,
834 // Which sortindex to use when retrieving records for this engine.
835 _defaultSort: undefined,
837 _hasSyncedThisSession: false,
839 _metadataPostProcessor(json) {
840 if (Array.isArray(json)) {
841 // Pre-`JSONFile` storage stored an array, but `JSONFile` defaults to
842 // an object, so we wrap the array for consistency.
843 json = { ids: json };
848 // The set serializes the same way as an array, but offers more efficient
849 // methods of manipulation.
850 json.ids = new SerializableSet(json.ids);
854 async _beforeSaveMetadata() {
855 await ensureDirectory(this._toFetchStorage.path);
856 await ensureDirectory(this._previousFailedStorage.path);
859 // A relative priority to use when computing an order
860 // for engines to be synced. Higher-priority engines
861 // (lower numbers) are synced first.
862 // It is recommended that a unique value be used for each engine,
863 // in order to guarantee a stable sequence.
866 // How many records to pull in a single sync. This is primarily to avoid very
867 // long first syncs against profiles with many history records.
870 // How many records to pull at one time when specifying IDs. This is to avoid
871 // URI length limitations.
872 guidFetchBatchSize: DEFAULT_GUID_FETCH_BATCH_SIZE,
874 downloadBatchSize: DEFAULT_DOWNLOAD_BATCH_SIZE,
877 await this._toFetchStorage.load();
878 await this._previousFailedStorage.load();
879 Services.prefs.addObserver(
880 `${PREFS_BRANCH}engine.${this.prefName}`,
884 this._log.debug("SyncEngine initialized", this.name);
892 return this._enabled;
896 if (!!val != this._enabled) {
897 Svc.PrefBranch.setBoolPref("engine." + this.prefName, !!val);
902 return this._tracker.score;
906 let store = new this._storeObj(this.Name, this);
907 this.__defineGetter__("_store", () => store);
912 let tracker = new this._trackerObj(this.Name, this);
913 this.__defineGetter__("_tracker", () => tracker);
918 return this.service.storageURL;
922 return this.storageURL + this.name;
925 get cryptoKeysURL() {
926 return this.storageURL + "crypto/keys";
930 return this.storageURL + "meta/global";
934 this._tracker.start();
939 return this._tracker.stop();
942 // Listens for engine enabled state changes, and updates the tracker's state.
943 // This is an async observer because the tracker waits on all its async
944 // observers to finish when it's stopped.
945 async observe(subject, topic, data) {
947 topic == "nsPref:changed" &&
948 data == `services.sync.engine.${this.prefName}`
950 await this._tracker.onEngineEnabledChanged(this._enabled);
960 throw new Error("engine does not implement _sync method");
963 return this._notify("sync", this.name, this._sync)();
966 // Override this method to return a new changeset type.
968 return new Changeset();
972 * Returns the local sync ID for this engine, or `""` if the engine hasn't
973 * synced for the first time. This is exposed for tests.
975 * @return the current sync ID.
982 * Ensures that the local sync ID for the engine matches the sync ID for the
983 * collection on the server. A mismatch indicates that another client wiped
984 * the collection; we're syncing after a node reassignment, and another
985 * client synced before us; or the store was replaced since the last sync.
986 * In case of a mismatch, we need to reset all local Sync state and start
987 * over as a first sync.
989 * In most cases, this method should return the new sync ID as-is. However, an
990 * engine may ignore the given ID and assign a different one, if it determines
991 * that the sync ID on the server is out of date. The bookmarks engine uses
992 * this to wipe the server and other clients on the first sync after the user
993 * restores from a backup.
996 * The new sync ID for the collection from `meta/global`.
997 * @return The assigned sync ID. If this doesn't match `newSyncID`, we'll
998 * replace the sync ID in `meta/global` with the assigned ID.
1000 async ensureCurrentSyncID(newSyncID) {
1001 let existingSyncID = this._syncID;
1002 if (existingSyncID == newSyncID) {
1003 return existingSyncID;
1005 this._log.debug("Engine syncIDs: " + [newSyncID, existingSyncID]);
1006 Svc.PrefBranch.setStringPref(this.name + ".syncID", newSyncID);
1007 Svc.PrefBranch.setCharPref(this.name + ".lastSync", "0");
1012 * Resets the local sync ID for the engine, wipes the server, and resets all
1013 * local Sync state to start over as a first sync.
1015 * @return the new sync ID.
1017 async resetSyncID() {
1018 let newSyncID = await this.resetLocalSyncID();
1019 await this.wipeServer();
1024 * Resets the local sync ID for the engine, signaling that we're starting over
1027 * @return the new sync ID.
1029 async resetLocalSyncID() {
1030 return this.ensureCurrentSyncID(Utils.makeGUID());
1034 * Allows overriding scheduler logic -- added to help reduce kinto server
1035 * getting hammered because our scheduler never got tuned for it.
1037 * Note: Overriding engines must take resyncs into account -- score will not
1040 shouldSkipSync(syncReason) {
1045 * lastSync is a timestamp in server time.
1047 async getLastSync() {
1048 return this._lastSync;
1050 async setLastSync(lastSync) {
1051 // Store the value as a string to keep floating point precision
1052 Svc.PrefBranch.setCharPref(this.name + ".lastSync", lastSync.toString());
1054 async resetLastSync() {
1055 this._log.debug("Resetting " + this.name + " last sync time");
1056 await this.setLastSync(0);
1059 get hasSyncedThisSession() {
1060 return this._hasSyncedThisSession;
1063 set hasSyncedThisSession(hasSynced) {
1064 this._hasSyncedThisSession = hasSynced;
1068 this._toFetchStorage.ensureDataReady();
1069 return this._toFetchStorage.data.ids;
1073 if (ids.constructor.name != "SerializableSet") {
1075 "Bug: Attempted to set toFetch to something that isn't a SerializableSet"
1078 this._toFetchStorage.data = { ids };
1079 this._toFetchStorage.saveSoon();
1082 get previousFailed() {
1083 this._previousFailedStorage.ensureDataReady();
1084 return this._previousFailedStorage.data.ids;
1087 set previousFailed(ids) {
1088 if (ids.constructor.name != "SerializableSet") {
1090 "Bug: Attempted to set previousFailed to something that isn't a SerializableSet"
1093 this._previousFailedStorage.data = { ids };
1094 this._previousFailedStorage.saveSoon();
1098 * Returns a changeset for this sync. Engine implementations can override this
1099 * method to bypass the tracker for certain or all changed items.
1101 async getChangedIDs() {
1102 return this._tracker.getChangedIDs();
1105 // Create a new record using the store and add in metadata.
1106 async _createRecord(id) {
1107 let record = await this._store.createRecord(id, this.name);
1109 record.collection = this.name;
1113 // Creates a tombstone Sync record with additional metadata.
1114 _createTombstone(id) {
1115 let tombstone = new this._recordObj(this.name, id);
1117 tombstone.collection = this.name;
1118 tombstone.deleted = true;
1122 // Any setup that needs to happen at the beginning of each sync.
1123 async _syncStartup() {
1124 // Determine if we need to wipe on outdated versions
1125 let metaGlobal = await this.service.recordManager.get(this.metaURL);
1126 let engines = metaGlobal.payload.engines || {};
1127 let engineData = engines[this.name] || {};
1129 // Assume missing versions are 0 and wipe the server
1130 if ((engineData.version || 0) < this.version) {
1131 this._log.debug("Old engine data: " + [engineData.version, this.version]);
1133 // Clear the server and reupload everything on bad version or missing
1134 // meta. Note that we don't regenerate per-collection keys here.
1135 let newSyncID = await this.resetSyncID();
1137 // Set the newer version and newly generated syncID
1138 engineData.version = this.version;
1139 engineData.syncID = newSyncID;
1141 // Put the new data back into meta/global and mark for upload
1142 engines[this.name] = engineData;
1143 metaGlobal.payload.engines = engines;
1144 metaGlobal.changed = true;
1145 } else if (engineData.version > this.version) {
1146 // Don't sync this engine if the server has newer data
1148 let error = new Error("New data: " + [engineData.version, this.version]);
1149 error.failureCode = VERSION_OUT_OF_DATE;
1152 // Changes to syncID mean we'll need to upload everything
1153 let assignedSyncID = await this.ensureCurrentSyncID(engineData.syncID);
1154 if (assignedSyncID != engineData.syncID) {
1155 engineData.syncID = assignedSyncID;
1156 metaGlobal.changed = true;
1160 // Save objects that need to be uploaded in this._modified. As we
1161 // successfully upload objects we remove them from this._modified. If an
1162 // error occurs or any objects fail to upload, they will remain in
1163 // this._modified. At the end of a sync, or after an error, we add all
1164 // objects remaining in this._modified to the tracker.
1165 let initialChanges = await this.pullChanges();
1166 this._modified.replace(initialChanges);
1167 // Clear the tracker now. If the sync fails we'll add the ones we failed
1169 this._tracker.clearChangedIDs();
1170 this._tracker.resetScore();
1172 // Keep track of what to delete at the end of sync
1176 async pullChanges() {
1177 let lastSync = await this.getLastSync();
1179 return this.pullNewChanges();
1181 this._log.debug("First sync, uploading all items");
1182 return this.pullAllChanges();
1186 * A tiny abstraction to make it easier to test incoming record
1190 return new Collection(this.engineURL, this._recordObj, this.service);
1194 * Download and apply remote records changed since the last sync. This
1195 * happens in three stages.
1197 * In the first stage, we fetch full records for all changed items, newest
1198 * first, up to the download limit. The limit lets us make progress for large
1199 * collections, where the sync is likely to be interrupted before we
1200 * can fetch everything.
1202 * In the second stage, we fetch the IDs of any remaining records changed
1203 * since the last sync, add them to our backlog, and fast-forward our last
1206 * In the third stage, we fetch and apply records for all backlogged IDs,
1207 * as well as any records that failed to apply during the last sync. We
1208 * request records for the IDs in chunks, to avoid exceeding URL length
1209 * limits, then remove successfully applied records from the backlog, and
1210 * record IDs of any records that failed to apply to retry on the next sync.
1212 async _processIncoming() {
1213 this._log.trace("Downloading & applying server changes");
1215 let newitems = this.itemSource();
1216 let lastSync = await this.getLastSync();
1218 newitems.newer = lastSync;
1219 newitems.full = true;
1221 let downloadLimit = Infinity;
1222 if (this.downloadLimit) {
1223 // Fetch new records up to the download limit. Currently, only the history
1224 // engine sets a limit, since the history collection has the highest volume
1225 // of changed records between syncs. The other engines fetch all records
1226 // changed since the last sync.
1227 if (this._defaultSort) {
1228 // A download limit with a sort order doesn't make sense: we won't know
1229 // which records to backfill.
1230 throw new Error("Can't specify download limit with default sort order");
1232 newitems.sort = "newest";
1233 downloadLimit = newitems.limit = this.downloadLimit;
1234 } else if (this._defaultSort) {
1235 // The bookmarks engine fetches records by sort index; other engines leave
1236 // the order unspecified. We can remove `_defaultSort` entirely after bug
1237 // 1305563: the sort index won't matter because we'll buffer all bookmarks
1239 newitems.sort = this._defaultSort;
1242 // applied => number of items that should be applied.
1243 // failed => number of items that failed in this sync.
1244 // newFailed => number of items that failed for the first time in this sync.
1245 // reconciled => number of items that were reconciled.
1246 // failedReasons => {name, count} of reasons a record failed
1247 let countTelemetry = new SyncedRecordsTelemetry();
1248 let count = countTelemetry.incomingCounts;
1249 let recordsToApply = [];
1250 let failedInCurrentSync = new SerializableSet();
1252 let oldestModified = this.lastModified;
1253 let downloadedIDs = new Set();
1255 // Stage 1: Fetch new records from the server, up to the download limit.
1256 if (this.lastModified == null || this.lastModified > lastSync) {
1257 let { response, records } = await newitems.getBatched(
1258 this.downloadBatchSize
1260 if (!response.success) {
1261 response.failureCode = ENGINE_DOWNLOAD_FAIL;
1265 await Async.yieldingForEach(records, async record => {
1266 downloadedIDs.add(record.id);
1268 if (record.modified < oldestModified) {
1269 oldestModified = record.modified;
1272 let { shouldApply, error } = await this._maybeReconcile(record);
1274 failedInCurrentSync.add(record.id);
1276 countTelemetry.addIncomingFailedReason(error.message);
1283 recordsToApply.push(record);
1286 let failedToApply = await this._applyRecords(
1290 Utils.setAddAll(failedInCurrentSync, failedToApply);
1292 // `applied` is a bit of a misnomer: it counts records that *should* be
1293 // applied, so it also includes records that we tried to apply and failed.
1294 // `recordsToApply.length - failedToApply.length` is the number of records
1295 // that we *successfully* applied.
1296 count.failed += failedToApply.length;
1297 count.applied += recordsToApply.length;
1300 // Stage 2: If we reached our download limit, we might still have records
1301 // on the server that changed since the last sync. Fetch the IDs for the
1302 // remaining records, and add them to the backlog. Note that this stage
1303 // only runs for engines that set a download limit.
1304 if (downloadedIDs.size == downloadLimit) {
1305 let guidColl = this.itemSource();
1307 guidColl.newer = lastSync;
1308 guidColl.older = oldestModified;
1309 guidColl.sort = "oldest";
1311 let guids = await guidColl.get();
1312 if (!guids.success) {
1316 // Filtering out already downloaded IDs here isn't necessary. We only do
1317 // that in case the Sync server doesn't support `older` (bug 1316110).
1318 let remainingIDs = guids.obj.filter(id => !downloadedIDs.has(id));
1319 if (remainingIDs.length) {
1320 this.toFetch = Utils.setAddAll(this.toFetch, remainingIDs);
1324 // Fast-foward the lastSync timestamp since we have backlogged the
1326 if (lastSync < this.lastModified) {
1327 lastSync = this.lastModified;
1328 await this.setLastSync(lastSync);
1331 // Stage 3: Backfill records from the backlog, and those that failed to
1332 // decrypt or apply during the last sync. We only backfill up to the
1333 // download limit, to prevent a large backlog for one engine from blocking
1334 // the others. We'll keep processing the backlog on subsequent engine syncs.
1335 let failedInPreviousSync = this.previousFailed;
1336 let idsToBackfill = Array.from(
1338 Utils.subsetOfSize(this.toFetch, downloadLimit),
1339 failedInPreviousSync
1343 // Note that we intentionally overwrite the previously failed list here.
1344 // Records that fail to decrypt or apply in two consecutive syncs are likely
1345 // corrupt; we remove them from the list because retrying and failing on
1346 // every subsequent sync just adds noise.
1347 this.previousFailed = failedInCurrentSync;
1349 let backfilledItems = this.itemSource();
1351 backfilledItems.sort = "newest";
1352 backfilledItems.full = true;
1354 // `getBatched` includes the list of IDs as a query parameter, so we need to fetch
1355 // records in chunks to avoid exceeding URI length limits.
1356 if (this.guidFetchBatchSize) {
1357 for (let ids of lazy.PlacesUtils.chunkArray(
1359 this.guidFetchBatchSize
1361 backfilledItems.ids = ids;
1363 let { response, records } = await backfilledItems.getBatched(
1364 this.downloadBatchSize
1366 if (!response.success) {
1367 response.failureCode = ENGINE_DOWNLOAD_FAIL;
1371 let backfilledRecordsToApply = [];
1372 let failedInBackfill = [];
1374 await Async.yieldingForEach(records, async record => {
1375 let { shouldApply, error } = await this._maybeReconcile(record);
1377 failedInBackfill.push(record.id);
1379 countTelemetry.addIncomingFailedReason(error.message);
1386 backfilledRecordsToApply.push(record);
1389 let failedToApply = await this._applyRecords(
1390 backfilledRecordsToApply,
1393 failedInBackfill.push(...failedToApply);
1395 count.failed += failedToApply.length;
1396 count.applied += backfilledRecordsToApply.length;
1398 this.toFetch = Utils.setDeleteAll(this.toFetch, ids);
1399 this.previousFailed = Utils.setAddAll(
1400 this.previousFailed,
1404 if (lastSync < this.lastModified) {
1405 lastSync = this.lastModified;
1406 await this.setLastSync(lastSync);
1411 count.newFailed = 0;
1412 for (let item of this.previousFailed) {
1413 // Anything that failed in the current sync that also failed in
1414 // the previous sync means there is likely something wrong with
1415 // the record, we remove it from trying again to prevent
1416 // infinitely syncing corrupted records
1417 if (failedInPreviousSync.has(item)) {
1418 this.previousFailed.delete(item);
1420 // otherwise it's a new failed and we count it as so
1425 count.succeeded = Math.max(0, count.applied - count.failed);
1436 "newly failed to apply,",
1441 Observers.notify("weave:engine:sync:applied", count, this.name);
1444 async _maybeReconcile(item) {
1445 let key = this.service.collectionKeys.keyForCollection(this.name);
1447 // Grab a later last modified if possible
1448 if (this.lastModified == null || item.modified > this.lastModified) {
1449 this.lastModified = item.modified;
1454 await item.decrypt(key);
1456 if (!Utils.isHMACMismatch(ex)) {
1459 let strategy = await this.handleHMACMismatch(item, true);
1460 if (strategy == SyncEngine.kRecoveryStrategy.retry) {
1461 // You only get one retry.
1463 // Try decrypting again, typically because we've got new keys.
1464 this._log.info("Trying decrypt again...");
1465 key = this.service.collectionKeys.keyForCollection(this.name);
1466 await item.decrypt(key);
1469 if (!Utils.isHMACMismatch(ex)) {
1472 strategy = await this.handleHMACMismatch(item, false);
1478 // Retry succeeded! No further handling.
1480 case SyncEngine.kRecoveryStrategy.retry:
1481 this._log.debug("Ignoring second retry suggestion.");
1482 // Fall through to error case.
1483 case SyncEngine.kRecoveryStrategy.error:
1484 this._log.warn("Error decrypting record", ex);
1485 return { shouldApply: false, error: ex };
1486 case SyncEngine.kRecoveryStrategy.ignore:
1488 "Ignoring record " + item.id + " with bad HMAC: already handled."
1490 return { shouldApply: false, error: null };
1494 if (Async.isShutdownException(ex)) {
1497 this._log.warn("Error decrypting record", ex);
1498 return { shouldApply: false, error: ex };
1501 if (this._shouldDeleteRemotely(item)) {
1502 this._log.trace("Deleting item from server without applying", item);
1503 await this._deleteId(item.id);
1504 return { shouldApply: false, error: null };
1509 shouldApply = await this._reconcile(item);
1511 if (ex.code == SyncEngine.prototype.eEngineAbortApplyIncoming) {
1512 this._log.warn("Reconciliation failed: aborting incoming processing.");
1514 } else if (!Async.isShutdownException(ex)) {
1515 this._log.warn("Failed to reconcile incoming record " + item.id, ex);
1516 return { shouldApply: false, error: ex };
1523 this._log.trace("Skipping reconciled incoming item " + item.id);
1526 return { shouldApply, error: null };
1529 async _applyRecords(records, countTelemetry) {
1530 this._tracker.ignoreAll = true;
1532 let failedIDs = await this._store.applyIncomingBatch(
1538 // Catch any error that escapes from applyIncomingBatch. At present
1539 // those will all be abort events.
1540 this._log.warn("Got exception, aborting processIncoming", ex);
1543 this._tracker.ignoreAll = false;
1547 // Indicates whether an incoming item should be deleted from the server at
1548 // the end of the sync. Engines can override this method to clean up records
1549 // that shouldn't be on the server.
1550 _shouldDeleteRemotely(remoteItem) {
1555 * Find a GUID of an item that is a duplicate of the incoming item but happens
1556 * to have a different GUID
1558 * @return GUID of the similar item; falsy otherwise
1560 async _findDupe(item) {
1561 // By default, assume there's no dupe items for the engine
1565 * Called before a remote record is discarded due to failed reconciliation.
1566 * Used by bookmark sync to merge folder child orders.
1568 beforeRecordDiscard(localRecord, remoteRecord, remoteIsNewer) {},
1570 // Called when the server has a record marked as deleted, but locally we've
1571 // changed it more recently than the deletion. If we return false, the
1572 // record will be deleted locally. If we return true, we'll reupload the
1573 // record to the server -- any extra work that's needed as part of this
1574 // process should be done at this point (such as mark the record's parent
1575 // for reuploading in the case of bookmarks).
1576 async _shouldReviveRemotelyDeletedRecord(remoteItem) {
1580 async _deleteId(id) {
1581 await this._tracker.removeChangedID(id);
1582 this._noteDeletedId(id);
1585 // Marks an ID for deletion at the end of the sync.
1586 _noteDeletedId(id) {
1587 if (this._delete.ids == null) {
1588 this._delete.ids = [id];
1590 this._delete.ids.push(id);
1594 async _switchItemToDupe(localDupeGUID, incomingItem) {
1595 // The local, duplicate ID is always deleted on the server.
1596 await this._deleteId(localDupeGUID);
1598 // We unconditionally change the item's ID in case the engine knows of
1599 // an item but doesn't expose it through itemExists. If the API
1600 // contract were stronger, this could be changed.
1602 "Switching local ID to incoming: " +
1607 return this._store.changeItemID(localDupeGUID, incomingItem.id);
1611 * Reconcile incoming record with local state.
1613 * This function essentially determines whether to apply an incoming record.
1616 * Record from server to be tested for application.
1618 * Truthy if incoming record should be applied. False if not.
1620 async _reconcile(item) {
1621 if (this._log.level <= Log.Level.Trace) {
1622 this._log.trace("Incoming: " + item);
1625 // We start reconciling by collecting a bunch of state. We do this here
1626 // because some state may change during the course of this function and we
1627 // need to operate on the original values.
1628 let existsLocally = await this._store.itemExists(item.id);
1629 let locallyModified = this._modified.has(item.id);
1631 // TODO Handle clock drift better. Tracked in bug 721181.
1632 let remoteAge = Resource.serverTime - item.modified;
1633 let localAge = locallyModified
1634 ? Date.now() / 1000 - this._modified.getModifiedTimestamp(item.id)
1636 let remoteIsNewer = remoteAge < localAge;
1651 // We handle deletions first so subsequent logic doesn't have to check
1654 // If the item doesn't exist locally, there is nothing for us to do. We
1655 // can't check for duplicates because the incoming record has no data
1656 // which can be used for duplicate detection.
1657 if (!existsLocally) {
1659 "Ignoring incoming item because it was deleted and " +
1660 "the item does not exist locally."
1665 // We decide whether to process the deletion by comparing the record
1666 // ages. If the item is not modified locally, the remote side wins and
1667 // the deletion is processed. If it is modified locally, we take the
1669 if (!locallyModified) {
1671 "Applying incoming delete because the local item " +
1672 "exists and isn't modified."
1676 this._log.trace("Incoming record is deleted but we had local changes.");
1678 if (remoteIsNewer) {
1679 this._log.trace("Remote record is newer -- deleting local record.");
1682 // If the local record is newer, we defer to individual engines for
1683 // how to handle this. By default, we revive the record.
1684 let willRevive = await this._shouldReviveRemotelyDeletedRecord(item);
1685 this._log.trace("Local record is newer -- reviving? " + willRevive);
1690 // At this point the incoming record is not for a deletion and must have
1691 // data. If the incoming record does not exist locally, we check for a local
1692 // duplicate existing under a different ID. The default implementation of
1693 // _findDupe() is empty, so engines have to opt in to this functionality.
1695 // If we find a duplicate, we change the local ID to the incoming ID and we
1696 // refresh the metadata collected above. See bug 710448 for the history
1698 if (!existsLocally) {
1699 let localDupeGUID = await this._findDupe(item);
1700 if (localDupeGUID) {
1704 " is a duplicate for " +
1709 // The current API contract does not mandate that the ID returned by
1710 // _findDupe() actually exists. Therefore, we have to perform this
1712 existsLocally = await this._store.itemExists(localDupeGUID);
1714 // If the local item was modified, we carry its metadata forward so
1715 // appropriate reconciling can be performed.
1716 if (this._modified.has(localDupeGUID)) {
1717 locallyModified = true;
1719 this._tracker._now() -
1720 this._modified.getModifiedTimestamp(localDupeGUID);
1721 remoteIsNewer = remoteAge < localAge;
1723 this._modified.changeID(localDupeGUID, item.id);
1725 locallyModified = false;
1729 // Tell the engine to do whatever it needs to switch the items.
1730 await this._switchItemToDupe(localDupeGUID, item);
1733 "Local item after duplication: age=" +
1741 this._log.trace("No duplicate found for incoming item: " + item.id);
1745 // At this point we've performed duplicate detection. But, nothing here
1746 // should depend on duplicate detection as the above should have updated
1747 // state seamlessly.
1749 if (!existsLocally) {
1750 // If the item doesn't exist locally and we have no local modifications
1751 // to the item (implying that it was not deleted), always apply the remote
1753 if (!locallyModified) {
1755 "Applying incoming because local item does not exist " +
1756 "and was not deleted."
1761 // If the item was modified locally but isn't present, it must have
1762 // been deleted. If the incoming record is younger, we restore from
1764 if (remoteIsNewer) {
1766 "Applying incoming because local item was deleted " +
1767 "before the incoming item was changed."
1769 this._modified.delete(item.id);
1774 "Ignoring incoming item because the local item's " +
1775 "deletion is newer."
1780 // If the remote and local records are the same, there is nothing to be
1781 // done, so we don't do anything. In the ideal world, this logic wouldn't
1782 // be here and the engine would take a record and apply it. The reason we
1783 // want to defer this logic is because it would avoid a redundant and
1784 // possibly expensive dip into the storage layer to query item state.
1785 // This should get addressed in the async rewrite, so we ignore it for now.
1786 let localRecord = await this._createRecord(item.id);
1787 let recordsEqual = Utils.deepEquals(item.cleartext, localRecord.cleartext);
1789 // If the records are the same, we don't need to do anything. This does
1790 // potentially throw away a local modification time. But, if the records
1791 // are the same, does it matter?
1794 "Ignoring incoming item because the local item is identical."
1797 this._modified.delete(item.id);
1801 // At this point the records are different.
1803 // If we have no local modifications, always take the server record.
1804 if (!locallyModified) {
1805 this._log.trace("Applying incoming record because no local conflicts.");
1809 // At this point, records are different and the local record is modified.
1810 // We resolve conflicts by record age, where the newest one wins. This does
1811 // result in data loss and should be handled by giving the engine an
1812 // opportunity to merge the records. Bug 720592 tracks this feature.
1814 "DATA LOSS: Both local and remote changes to record: " + item.id
1816 if (!remoteIsNewer) {
1817 this.beforeRecordDiscard(localRecord, item, remoteIsNewer);
1819 return remoteIsNewer;
1822 // Upload outgoing records.
1823 async _uploadOutgoing() {
1824 this._log.trace("Uploading local changes to server.");
1826 // collection we'll upload
1827 let up = new Collection(this.engineURL, null, this.service);
1828 let modifiedIDs = new Set(this._modified.ids());
1829 let countTelemetry = new SyncedRecordsTelemetry();
1830 let counts = countTelemetry.outgoingCounts;
1831 this._log.info(`Uploading ${modifiedIDs.size} outgoing records`);
1832 if (modifiedIDs.size) {
1833 counts.sent = modifiedIDs.size;
1836 let successful = [];
1837 let lastSync = await this.getLastSync();
1838 let handleResponse = async (postQueue, resp, batchOngoing) => {
1839 // Note: We don't want to update this.lastSync, or this._modified until
1840 // the batch is complete, however we want to remember success/failure
1841 // indicators for when that happens.
1842 if (!resp.success) {
1843 this._log.debug(`Uploading records failed: ${resp.status}`);
1845 resp.status == 412 ? ENGINE_BATCH_INTERRUPTED : ENGINE_UPLOAD_FAIL;
1849 // Update server timestamp from the upload.
1850 failed = failed.concat(Object.keys(resp.obj.failed));
1851 successful = successful.concat(resp.obj.success);
1854 // Nothing to do yet
1858 if (failed.length && this._log.level <= Log.Level.Debug) {
1860 "Records that will be uploaded again because " +
1861 "the server couldn't store them: " +
1866 counts.failed += failed.length;
1867 Object.values(failed).forEach(message => {
1868 countTelemetry.addOutgoingFailedReason(message);
1871 for (let id of successful) {
1872 this._modified.delete(id);
1875 await this._onRecordsWritten(
1878 postQueue.lastModified
1881 // Advance lastSync since we've finished the batch.
1882 if (postQueue.lastModified > lastSync) {
1883 lastSync = postQueue.lastModified;
1884 await this.setLastSync(lastSync);
1887 // clear for next batch
1889 successful.length = 0;
1892 let postQueue = up.newPostQueue(this._log, lastSync, handleResponse);
1894 for (let id of modifiedIDs) {
1898 out = await this._createRecord(id);
1899 if (this._log.level <= Log.Level.Trace) {
1900 this._log.trace("Outgoing: " + out);
1903 this.service.collectionKeys.keyForCollection(this.name)
1907 this._log.warn("Error creating record", ex);
1909 countTelemetry.addOutgoingFailedReason(ex.message);
1910 if (Async.isShutdownException(ex) || !this.allowSkippedRecord) {
1911 if (!this.allowSkippedRecord) {
1912 // Don't bother for shutdown errors
1913 Observers.notify("weave:engine:sync:uploaded", counts, this.name);
1919 let { enqueued, error } = await postQueue.enqueue(out);
1922 countTelemetry.addOutgoingFailedReason(error.message);
1923 if (!this.allowSkippedRecord) {
1924 Observers.notify("weave:engine:sync:uploaded", counts, this.name);
1926 `Failed to enqueue record "${id}" (aborting)`,
1931 this._modified.delete(id);
1933 `Failed to enqueue record "${id}" (skipping)`,
1938 await Async.promiseYield();
1940 await postQueue.flush(true);
1943 if (counts.sent || counts.failed) {
1944 Observers.notify("weave:engine:sync:uploaded", counts, this.name);
1948 async _onRecordsWritten(succeeded, failed, serverModifiedTime) {
1949 // Implement this method to take specific actions against successfully
1950 // uploaded records and failed records.
1953 // Any cleanup necessary.
1954 // Save the current snapshot so as to calculate changes at next sync
1955 async _syncFinish() {
1956 this._log.trace("Finishing up sync");
1958 let doDelete = async (key, val) => {
1959 let coll = new Collection(this.engineURL, this._recordObj, this.service);
1961 await coll.delete();
1964 for (let [key, val] of Object.entries(this._delete)) {
1965 // Remove the key for future uses
1966 delete this._delete[key];
1968 this._log.trace("doing post-sync deletions", { key, val });
1969 // Send a simple delete for the property
1970 if (key != "ids" || val.length <= 100) {
1971 await doDelete(key, val);
1973 // For many ids, split into chunks of at most 100
1974 while (val.length) {
1975 await doDelete(key, val.slice(0, 100));
1976 val = val.slice(100);
1980 this.hasSyncedThisSession = true;
1981 await this._tracker.asyncObserver.promiseObserversComplete();
1984 async _syncCleanup() {
1986 // Mark failed WBOs as changed again so they are reuploaded next time.
1987 await this.trackRemainingChanges();
1989 this._modified.clear();
1995 Async.checkAppReady();
1996 await this._syncStartup();
1997 Async.checkAppReady();
1998 Observers.notify("weave:engine:sync:status", "process-incoming");
1999 await this._processIncoming();
2000 Async.checkAppReady();
2001 Observers.notify("weave:engine:sync:status", "upload-outgoing");
2003 await this._uploadOutgoing();
2004 Async.checkAppReady();
2005 await this._syncFinish();
2007 if (!ex.status || ex.status != 412) {
2010 // a 412 posting just means another client raced - but we don't want
2011 // to treat that as a sync error - the next sync is almost certain
2013 this._log.warn("412 error during sync - will retry.");
2016 await this._syncCleanup();
2020 async canDecrypt() {
2021 // Report failure even if there's nothing to decrypt
2022 let canDecrypt = false;
2024 // Fetch the most recently uploaded record and try to decrypt it
2025 let test = new Collection(this.engineURL, this._recordObj, this.service);
2027 test.sort = "newest";
2030 let key = this.service.collectionKeys.keyForCollection(this.name);
2032 // Any failure fetching/decrypting will just result in false
2034 this._log.trace("Trying to decrypt a record from the server..");
2035 let json = (await test.get()).obj[0];
2036 let record = new this._recordObj();
2037 record.deserialize(json);
2038 await record.decrypt(key);
2041 if (Async.isShutdownException(ex)) {
2044 this._log.debug("Failed test decrypt", ex);
2051 * Deletes the collection for this engine on the server, and removes all local
2052 * Sync metadata for this engine. This does *not* remove any existing data on
2053 * other clients. This is called when we reset the sync ID.
2055 async wipeServer() {
2056 await this._deleteServerCollection();
2057 await this._resetClient();
2061 * Deletes the collection for this engine on the server, without removing
2062 * any local Sync metadata or user data. Deleting the collection will not
2063 * remove any user data on other clients, but will force other clients to
2064 * start over as a first sync.
2066 async _deleteServerCollection() {
2067 let response = await this.service.resource(this.engineURL).delete();
2068 if (response.status != 200 && response.status != 404) {
2073 async removeClientData() {
2074 // Implement this method in engines that store client specific data
2079 * Decide on (and partially effect) an error-handling strategy.
2081 * Asks the Service to respond to an HMAC error, which might result in keys
2082 * being downloaded. That call returns true if an action which might allow a
2085 * If `mayRetry` is truthy, and the Service suggests a retry,
2086 * handleHMACMismatch returns kRecoveryStrategy.retry. Otherwise, it returns
2087 * kRecoveryStrategy.error.
2089 * Subclasses of SyncEngine can override this method to allow for different
2090 * behavior -- e.g., to delete and ignore erroneous entries.
2092 * All return values will be part of the kRecoveryStrategy enumeration.
2094 async handleHMACMismatch(item, mayRetry) {
2095 // By default we either try again, or bail out noisily.
2096 return (await this.service.handleHMACEvent()) && mayRetry
2097 ? SyncEngine.kRecoveryStrategy.retry
2098 : SyncEngine.kRecoveryStrategy.error;
2102 * Returns a changeset containing all items in the store. The default
2103 * implementation returns a changeset with timestamps from long ago, to
2104 * ensure we always use the remote version if one exists.
2106 * This function is only called for the first sync. Subsequent syncs call
2109 * @return A `Changeset` object.
2111 async pullAllChanges() {
2113 let ids = await this._store.getAllIDs();
2114 for (let id in ids) {
2121 * Returns a changeset containing entries for all currently tracked items.
2122 * The default implementation returns a changeset with timestamps indicating
2123 * when the item was added to the tracker.
2125 * @return A `Changeset` object.
2127 async pullNewChanges() {
2128 await this._tracker.asyncObserver.promiseObserversComplete();
2129 return this.getChangedIDs();
2133 * Adds all remaining changeset entries back to the tracker, typically for
2134 * items that failed to upload. This method is called at the end of each sync.
2137 async trackRemainingChanges() {
2138 for (let [id, change] of this._modified.entries()) {
2139 await this._tracker.addChangedID(id, change);
2144 * Removes all local Sync metadata for this engine, but keeps all existing
2147 async resetClient() {
2148 return this._notify("reset-client", this.name, this._resetClient)();
2151 async _resetClient() {
2152 await this.resetLastSync();
2153 this.hasSyncedThisSession = false;
2154 this.previousFailed = new SerializableSet();
2155 this.toFetch = new SerializableSet();
2159 * Removes all local Sync metadata and user data for this engine.
2161 async wipeClient() {
2162 return this._notify("wipe-client", this.name, this._wipeClient)();
2165 async _wipeClient() {
2166 await this.resetClient();
2167 this._log.debug("Deleting all local data");
2168 this._tracker.ignoreAll = true;
2169 await this._store.wipe();
2170 this._tracker.ignoreAll = false;
2171 this._tracker.clearChangedIDs();
2175 * If one exists, initialize and return a validator for this engine (which
2176 * must have a `validate(engine)` method that returns a promise to an object
2177 * with a getSummary method). Otherwise return null.
2184 Services.prefs.removeObserver(
2185 `${PREFS_BRANCH}engine.${this.prefName}`,
2188 await this.asyncObserver.promiseObserversComplete();
2189 await this._tracker.finalize();
2190 await this._toFetchStorage.finalize();
2191 await this._previousFailedStorage.finalize();
2194 // Returns a new watchdog. Exposed for tests.
2196 return Async.watchdog();
2201 * A changeset is created for each sync in `Engine::get{Changed, All}IDs`,
2202 * and stores opaque change data for tracked IDs. The default implementation
2203 * only records timestamps, though engines can extend this to store additional
2204 * data for each entry.
2206 export class Changeset {
2207 // Creates an empty changeset.
2212 // Returns the last modified time, in seconds, for an entry in the changeset.
2213 // `id` is guaranteed to be in the set.
2214 getModifiedTimestamp(id) {
2215 return this.changes[id];
2218 // Adds a change for a tracked ID to the changeset.
2220 this.changes[id] = change;
2223 // Adds multiple entries to the changeset, preserving existing entries.
2225 Object.assign(this.changes, changes);
2228 // Overwrites the existing set of tracked changes with new entries.
2230 this.changes = changes;
2233 // Indicates whether an entry is in the changeset.
2235 return id in this.changes;
2238 // Deletes an entry from the changeset. Used to clean up entries for
2239 // reconciled and successfully uploaded records.
2241 delete this.changes[id];
2244 // Changes the ID of an entry in the changeset. Used when reconciling
2245 // duplicates that have local changes.
2246 changeID(oldID, newID) {
2247 this.changes[newID] = this.changes[oldID];
2248 delete this.changes[oldID];
2251 // Returns an array of all tracked IDs in this changeset.
2253 return Object.keys(this.changes);
2256 // Returns an array of `[id, change]` tuples. Used to repopulate the tracker
2257 // with entries for failed uploads at the end of a sync.
2259 return Object.entries(this.changes);
2262 // Returns the number of entries in this changeset.
2264 return this.ids().length;
2267 // Clears the changeset.