concurrentCaller.js (7895B)
1 /* 2 ***** BEGIN LICENSE BLOCK ***** 3 4 Copyright © 2013 Center for History and New Media 5 George Mason University, Fairfax, Virginia, USA 6 http://zotero.org 7 8 This file is part of Zotero. 9 10 Zotero is free software: you can redistribute it and/or modify 11 it under the terms of the GNU Affero General Public License as published by 12 the Free Software Foundation, either version 3 of the License, or 13 (at your option) any later version. 14 15 Zotero is distributed in the hope that it will be useful, 16 but WITHOUT ANY WARRANTY; without even the implied warranty of 17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 GNU Affero General Public License for more details. 19 20 You should have received a copy of the GNU Affero General Public License 21 along with Zotero. If not, see <http://www.gnu.org/licenses/>. 22 23 ***** END LICENSE BLOCK ***** 24 */ 25 26 EXPORTED_SYMBOLS = ["ConcurrentCaller"]; 27 Components.utils.import('resource://zotero/require.js'); 28 29 var Promise = require('resource://zotero/bluebird.js'); 30 31 /** 32 * Call a fixed number of functions at once, queueing the rest until slots 33 * open and returning a promise for the final completion. The functions do 34 * not need to return promises, but they should if they have asynchronous 35 * work to perform. 36 * 37 * Example: 38 * 39 * var caller = new ConcurrentCaller({ 40 * numConcurrent: 2, 41 * stopOnError: true 42 * }); 43 * yield caller.start([foo, bar, baz, qux); 44 * 45 * In this example, foo and bar would run immediately, and baz and qux would 46 * be queued for later. When foo or bar finished, baz would be run, followed 47 * by qux when another slot opened. 48 * 49 * Additional functions can be added at any time with another call to start(). The promises for 50 * all open start() calls will be resolved when all requests are finished. 51 * 52 * @param {Object} options 53 * @param {Integer} options.numConcurrent - The number of concurrent functions to run. 54 * @param {String} [options.id] - Identifier to use in debug output 55 * @param {Boolean} [options.stopOnError] 56 * @param {Function} [options.onError] 57 * @param {Integer} [options.interval] - Interval between the end of one function run and the 58 * beginning of another, in milliseconds 59 * @param {Function} [options.logger] 60 */ 61 ConcurrentCaller = function (options = {}) { 62 if (typeof options == 'number') { 63 this._log("ConcurrentCaller now takes an object rather than a number"); 64 options = { 65 numConcurrent: options 66 }; 67 } 68 69 if (!options.numConcurrent) throw new Error("numConcurrent must be provided"); 70 71 this.stopOnError = options.stopOnError || false; 72 this.onError = options.onError || null; 73 this.numConcurrent = options.numConcurrent; 74 75 this._id = options.id; 76 this._numRunning = 0; 77 this._queue = []; 78 this._logger = options.logger || null; 79 this._interval = options.interval || 0; 80 this._pausing = false; 81 this._pauseUntil = 0; 82 this._deferred = null; 83 }; 84 85 86 ConcurrentCaller.prototype.setInterval = function (ms) { 87 this._log("setInterval() is deprecated -- pass .interval to constructor"); 88 this._interval = ms; 89 }; 90 91 92 ConcurrentCaller.prototype.setLogger = function (func) { 93 this._log("setLogger() is deprecated -- pass .logger to constructor"); 94 this._logger = func; 95 }; 96 97 98 /** 99 * Don't run any new functions for the specified amount of time 100 */ 101 ConcurrentCaller.prototype.pause = function (ms) { 102 this._pauseUntil = Date.now() + ms; 103 } 104 105 106 /** 107 * Add a task to the queue without starting it 108 * 109 * @param {Function|Function[]} - One or more functions to run 110 * @return {Promise|Promise<PromiseInspection[]>} - If one function is passed, a promise for the return 111 * value of the passed function; if multiple, a promise for an array of PromiseInspection objects 112 * for those functions, resolved once they have all finished, even if other functions are still running 113 */ 114 ConcurrentCaller.prototype.add = function (func) { 115 if (Array.isArray(func)) { 116 let promises = []; 117 for (let i = 0; i < func.length; i++) { 118 promises.push(this.start(func[i]).reflect()); 119 } 120 return Promise.all(promises); 121 } 122 123 if (!this._deferred || !this._deferred.promise.isPending()) { 124 this._deferred = Promise.defer(); 125 } 126 127 var deferred = Promise.defer(); 128 this._queue.push({ 129 func: Promise.method(func), 130 deferred: deferred 131 }); 132 return deferred.promise; 133 } 134 135 136 /** 137 * @param {Function|Function[]} - One or more functions to run 138 * @return {Promise[]} - An array of promises for passed functions, resolved once they have all 139 * finished (even if other functions are still running) 140 */ 141 ConcurrentCaller.prototype.start = function (func) { 142 var promise = this.add(func); 143 var run = this._processNext(); 144 if (!run) { 145 this._log("Already at " + this.numConcurrent + " -- queueing for later"); 146 } 147 return promise; 148 } 149 150 151 /** 152 * Start processing if not already running and wait for all tasks to complete 153 * 154 * @return {Promise[]} - An array of promises for all currently queued tasks 155 */ 156 ConcurrentCaller.prototype.runAll = function () { 157 // If nothing queued, return immediately 158 if (!this._deferred) { 159 return Promise.resolve([]); 160 } 161 var promises = this._queue.map(x => x.deferred.promise); 162 do { 163 var run = this._processNext(); 164 } 165 while (run); 166 return this._deferred.promise.return(promises); 167 } 168 169 170 /** 171 * Wait for all running tasks to complete 172 * 173 * @return {Promise} 174 */ 175 ConcurrentCaller.prototype.wait = function () { 176 return this._deferred ? this._deferred.promise : Promise.resolve(); 177 } 178 179 180 ConcurrentCaller.prototype.stop = function () { 181 this._log("Clearing queue"); 182 this._queue = []; 183 }; 184 185 186 ConcurrentCaller.prototype._processNext = function () { 187 if (this._numRunning >= this.numConcurrent) { 188 return false; 189 } 190 191 // If there's a function to call and we're under the concurrent limit, run it now 192 var f = this._queue.shift(); 193 if (!f) { 194 if (this._numRunning == 0 && !this._pausing) { 195 this._log("All tasks are done"); 196 this._deferred.resolve(); 197 } 198 else { 199 this._log("Nothing left to run -- waiting for running tasks to complete"); 200 } 201 return false; 202 } 203 204 this._log("Running function (" 205 + this._numRunning + "/" + this.numConcurrent + " running, " 206 + this._queue.length + " queued)"); 207 208 this._numRunning++; 209 f.func().bind(this).then(function (value) { 210 this._numRunning--; 211 212 this._log("Done with function (" 213 + this._numRunning + "/" + this.numConcurrent + " running, " 214 + this._queue.length + " queued)"); 215 216 this._waitForPause().bind(this).then(function () { 217 this._processNext(); 218 }); 219 220 f.deferred.resolve(value); 221 }) 222 .catch(function (e) { 223 this._numRunning--; 224 225 this._log("Error in function (" + this._numRunning + "/" + this.numConcurrent + ", " 226 + this._queue.length + " in queue)" 227 + ((!this.onError && !this.stopOnError) ? ": " + e : "")); 228 229 if (this.onError) { 230 this.onError(e); 231 } 232 233 if (this.stopOnError && this._queue.length) { 234 this._log("Stopping on error: " + e); 235 this._oldQueue = this._queue; 236 this._queue = []; 237 for (let o of this._oldQueue) { 238 //this._log("Rejecting promise"); 239 o.deferred.reject(); 240 } 241 } 242 243 this._waitForPause().bind(this).then(function () { 244 this._processNext(); 245 }); 246 247 e.handledRejection = true; 248 f.deferred.reject(e); 249 }); 250 return true; 251 } 252 253 254 /** 255 * Wait until the specified interval has elapsed or the current pause (if there is one) is over, 256 * whichever is longer 257 */ 258 ConcurrentCaller.prototype._waitForPause = Promise.coroutine(function* () { 259 let interval = this._interval; 260 let now = Date.now(); 261 if (this._pauseUntil > now && (this._pauseUntil - now > interval)) { 262 interval = this._pauseUntil - now; 263 } 264 this._pausing = true; 265 yield Promise.delay(interval); 266 this._pausing = false; 267 }); 268 269 270 ConcurrentCaller.prototype._log = function (msg) { 271 if (this._logger) { 272 this._logger("[ConcurrentCaller] " + (this._id ? `[${this._id}] ` : "") + msg); 273 } 274 };