Wed, 31 Dec 2014 06:09:35 +0100
Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.
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 "use strict";
7 const Cu = Components.utils;
8 const Cc = Components.classes;
9 const Ci = Components.interfaces;
11 Cu.import("resource://gre/modules/osfile.jsm");
12 Cu.import("resource://gre/modules/Promise.jsm");
14 // Make it possible to mock out timers for testing
15 let MakeTimer = () => Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer);
17 this.EXPORTED_SYMBOLS = ["DeferredSave"];
19 // If delay parameter is not provided, default is 50 milliseconds.
20 const DEFAULT_SAVE_DELAY_MS = 50;
22 Cu.import("resource://gre/modules/Log.jsm");
23 //Configure a logger at the parent 'DeferredSave' level to format
24 //messages for all the modules under DeferredSave.*
25 const DEFERREDSAVE_PARENT_LOGGER_ID = "DeferredSave";
26 let parentLogger = Log.repository.getLogger(DEFERREDSAVE_PARENT_LOGGER_ID);
27 parentLogger.level = Log.Level.Warn;
28 let formatter = new Log.BasicFormatter();
29 //Set parent logger (and its children) to append to
30 //the Javascript section of the Browser Console
31 parentLogger.addAppender(new Log.ConsoleAppender(formatter));
32 //Set parent logger (and its children) to
33 //also append to standard out
34 parentLogger.addAppender(new Log.DumpAppender(formatter));
36 //Provide the ability to enable/disable logging
37 //messages at runtime.
38 //If the "extensions.logging.enabled" preference is
39 //missing or 'false', messages at the WARNING and higher
40 //severity should be logged to the JS console and standard error.
41 //If "extensions.logging.enabled" is set to 'true', messages
42 //at DEBUG and higher should go to JS console and standard error.
43 Cu.import("resource://gre/modules/Services.jsm");
45 const PREF_LOGGING_ENABLED = "extensions.logging.enabled";
46 const NS_PREFBRANCH_PREFCHANGE_TOPIC_ID = "nsPref:changed";
48 /**
49 * Preference listener which listens for a change in the
50 * "extensions.logging.enabled" preference and changes the logging level of the
51 * parent 'addons' level logger accordingly.
52 */
53 var PrefObserver = {
54 init: function PrefObserver_init() {
55 Services.prefs.addObserver(PREF_LOGGING_ENABLED, this, false);
56 Services.obs.addObserver(this, "xpcom-shutdown", false);
57 this.observe(null, NS_PREFBRANCH_PREFCHANGE_TOPIC_ID, PREF_LOGGING_ENABLED);
58 },
60 observe: function PrefObserver_observe(aSubject, aTopic, aData) {
61 if (aTopic == "xpcom-shutdown") {
62 Services.prefs.removeObserver(PREF_LOGGING_ENABLED, this);
63 Services.obs.removeObserver(this, "xpcom-shutdown");
64 }
65 else if (aTopic == NS_PREFBRANCH_PREFCHANGE_TOPIC_ID) {
66 let debugLogEnabled = false;
67 try {
68 debugLogEnabled = Services.prefs.getBoolPref(PREF_LOGGING_ENABLED);
69 }
70 catch (e) {
71 }
72 if (debugLogEnabled) {
73 parentLogger.level = Log.Level.Debug;
74 }
75 else {
76 parentLogger.level = Log.Level.Warn;
77 }
78 }
79 }
80 };
82 PrefObserver.init();
84 /**
85 * A module to manage deferred, asynchronous writing of data files
86 * to disk. Writing is deferred by waiting for a specified delay after
87 * a request to save the data, before beginning to write. If more than
88 * one save request is received during the delay, all requests are
89 * fulfilled by a single write.
90 *
91 * @constructor
92 * @param aPath
93 * String representing the full path of the file where the data
94 * is to be written.
95 * @param aDataProvider
96 * Callback function that takes no argument and returns the data to
97 * be written. If aDataProvider returns an ArrayBufferView, the
98 * bytes it contains are written to the file as is.
99 * If aDataProvider returns a String the data are UTF-8 encoded
100 * and then written to the file.
101 * @param [optional] aDelay
102 * The delay in milliseconds between the first saveChanges() call
103 * that marks the data as needing to be saved, and when the DeferredSave
104 * begins writing the data to disk. Default 50 milliseconds.
105 */
106 this.DeferredSave = function (aPath, aDataProvider, aDelay) {
107 // Create a new logger (child of 'DeferredSave' logger)
108 // for use by this particular instance of DeferredSave object
109 let leafName = OS.Path.basename(aPath);
110 let logger_id = DEFERREDSAVE_PARENT_LOGGER_ID + "." + leafName;
111 this.logger = Log.repository.getLogger(logger_id);
113 // @type {Deferred|null}, null when no data needs to be written
114 // @resolves with the result of OS.File.writeAtomic when all writes complete
115 // @rejects with the error from OS.File.writeAtomic if the write fails,
116 // or with the error from aDataProvider() if that throws.
117 this._pending = null;
119 // @type {Promise}, completes when the in-progress write (if any) completes,
120 // kept as a resolved promise at other times to simplify logic.
121 // Because _deferredSave() always uses _writing.then() to execute
122 // its next action, we don't need a special case for whether a write
123 // is in progress - if the previous write is complete (and the _writing
124 // promise is already resolved/rejected), _writing.then() starts
125 // the next action immediately.
126 //
127 // @resolves with the result of OS.File.writeAtomic
128 // @rejects with the error from OS.File.writeAtomic
129 this._writing = Promise.resolve(0);
131 // Are we currently waiting for a write to complete
132 this.writeInProgress = false;
134 this._path = aPath;
135 this._dataProvider = aDataProvider;
137 this._timer = null;
139 // Some counters for telemetry
140 // The total number of times the file was written
141 this.totalSaves = 0;
143 // The number of times the data became dirty while
144 // another save was in progress
145 this.overlappedSaves = 0;
147 // Error returned by the most recent write (if any)
148 this._lastError = null;
150 if (aDelay && (aDelay > 0))
151 this._delay = aDelay;
152 else
153 this._delay = DEFAULT_SAVE_DELAY_MS;
154 }
156 this.DeferredSave.prototype = {
157 get dirty() {
158 return this._pending || this.writeInProgress;
159 },
161 get lastError() {
162 return this._lastError;
163 },
165 // Start the pending timer if data is dirty
166 _startTimer: function() {
167 if (!this._pending) {
168 return;
169 }
171 this.logger.debug("Starting timer");
172 if (!this._timer)
173 this._timer = MakeTimer();
174 this._timer.initWithCallback(() => this._deferredSave(),
175 this._delay, Ci.nsITimer.TYPE_ONE_SHOT);
176 },
178 /**
179 * Mark the current stored data dirty, and schedule a flush to disk
180 * @return A Promise<integer> that will be resolved after the data is written to disk;
181 * the promise is resolved with the number of bytes written.
182 */
183 saveChanges: function() {
184 this.logger.debug("Save changes");
185 if (!this._pending) {
186 if (this.writeInProgress) {
187 this.logger.debug("Data changed while write in progress");
188 this.overlappedSaves++;
189 }
190 this._pending = Promise.defer();
191 // Wait until the most recent write completes or fails (if it hasn't already)
192 // and then restart our timer
193 this._writing.then(count => this._startTimer(), error => this._startTimer());
194 }
195 return this._pending.promise;
196 },
198 _deferredSave: function() {
199 let pending = this._pending;
200 this._pending = null;
201 let writing = this._writing;
202 this._writing = pending.promise;
204 // In either the success or the exception handling case, we don't need to handle
205 // the error from _writing here; it's already being handled in another then()
206 let toSave = null;
207 try {
208 toSave = this._dataProvider();
209 }
210 catch(e) {
211 this.logger.error("Deferred save dataProvider failed", e);
212 writing.then(null, error => {})
213 .then(count => {
214 pending.reject(e);
215 });
216 return;
217 }
219 writing.then(null, error => {return 0;})
220 .then(count => {
221 this.logger.debug("Starting write");
222 this.totalSaves++;
223 this.writeInProgress = true;
225 OS.File.writeAtomic(this._path, toSave, {tmpPath: this._path + ".tmp"})
226 .then(
227 result => {
228 this._lastError = null;
229 this.writeInProgress = false;
230 this.logger.debug("Write succeeded");
231 pending.resolve(result);
232 },
233 error => {
234 this._lastError = error;
235 this.writeInProgress = false;
236 this.logger.warn("Write failed", error);
237 pending.reject(error);
238 });
239 });
240 },
242 /**
243 * Immediately save the dirty data to disk, skipping
244 * the delay of normal operation. Note that the write
245 * still happens asynchronously in the worker
246 * thread from OS.File.
247 *
248 * There are four possible situations:
249 * 1) Nothing to flush
250 * 2) Data is not currently being written, in-memory copy is dirty
251 * 3) Data is currently being written, in-memory copy is clean
252 * 4) Data is being written and in-memory copy is dirty
253 *
254 * @return Promise<integer> that will resolve when all in-memory data
255 * has finished being flushed, returning the number of bytes
256 * written. If all in-memory data is clean, completes with the
257 * result of the most recent write.
258 */
259 flush: function() {
260 // If we have pending changes, cancel our timer and set up the write
261 // immediately (_deferredSave queues the write for after the most
262 // recent write completes, if it hasn't already)
263 if (this._pending) {
264 this.logger.debug("Flush called while data is dirty");
265 if (this._timer) {
266 this._timer.cancel();
267 this._timer = null;
268 }
269 this._deferredSave();
270 }
272 return this._writing;
273 }
274 };