UNPKG

17.2 kBSource Map (JSON)View Raw
1{"version":3,"sources":["../src/scheduler.js"],"names":["utils","require","DEBUG","MatrixScheduler","retryAlgorithm","queueAlgorithm","RETRY_BACKOFF_RATELIMIT","QUEUE_MESSAGES","_queues","_activeQueues","_procFn","prototype","getQueueForEvent","event","name","map","obj","removeEventFromQueue","removed","removeElement","element","getId","setProcessFunction","fn","_startProcessingQueues","queueEvent","queueName","defer","push","attempts","debuglog","promise","err","httpStatus","cors","waitTime","data","retry_after_ms","Math","pow","getType","scheduler","forEach","filter","keys","indexOf","length","_processQueue","_peekNextEvent","index","splice","done","res","_removeNextEvent","resolve","waitTimeMs","reject","setTimeout","queue","isArray","shift","log","arguments","module","exports"],"mappings":"AAAA;;;;;;;;;;;;;;;AAeA;AACA;;;;;;AAMA;;;;;;AADA,IAAMA,QAAQC,QAAQ,SAAR,CAAd;;;AAGA,IAAMC,QAAQ,KAAd,C,CAAsB;;AAEtB;;;;;;;;;;;;AAYA,SAASC,eAAT,CAAyBC,cAAzB,EAAyCC,cAAzC,EAAyD;AACrD,SAAKD,cAAL,GAAsBA,kBAAkBD,gBAAgBG,uBAAxD;AACA,SAAKD,cAAL,GAAsBA,kBAAkBF,gBAAgBI,cAAxD;AACA,SAAKC,OAAL,GAAe;AACX;AACA;AACA;AACA;AACA;AALW,KAAf;AAOA,SAAKC,aAAL,GAAqB,EAArB;AACA,SAAKC,OAAL,GAAe,IAAf;AACH;;AAED;;;;;;;;;AASAP,gBAAgBQ,SAAhB,CAA0BC,gBAA1B,GAA6C,UAASC,KAAT,EAAgB;AACzD,QAAMC,OAAO,KAAKT,cAAL,CAAoBQ,KAApB,CAAb;AACA,QAAI,CAACC,IAAD,IAAS,CAAC,KAAKN,OAAL,CAAaM,IAAb,CAAd,EAAkC;AAC9B,eAAO,IAAP;AACH;AACD,WAAOd,MAAMe,GAAN,CAAU,KAAKP,OAAL,CAAaM,IAAb,CAAV,EAA8B,UAASE,GAAT,EAAc;AAC/C,eAAOA,IAA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apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n/**\n * This is an internal module which manages queuing, scheduling and retrying\n * of requests.\n * @module scheduler\n */\nconst utils = require(\"./utils\");\nimport Promise from 'bluebird';\n\nconst DEBUG = false; // set true to enable console logging.\n\n/**\n * Construct a scheduler for Matrix. Requires\n * {@link module:scheduler~MatrixScheduler#setProcessFunction} to be provided\n * with a way of processing events.\n * @constructor\n * @param {module:scheduler~retryAlgorithm} retryAlgorithm Optional. The retry\n * algorithm to apply when determining when to try to send an event again.\n * Defaults to {@link module:scheduler~MatrixScheduler.RETRY_BACKOFF_RATELIMIT}.\n * @param {module:scheduler~queueAlgorithm} queueAlgorithm Optional. The queuing\n * algorithm to apply when determining which events should be sent before the\n * given event. Defaults to {@link module:scheduler~MatrixScheduler.QUEUE_MESSAGES}.\n */\nfunction MatrixScheduler(retryAlgorithm, queueAlgorithm) {\n this.retryAlgorithm = retryAlgorithm || MatrixScheduler.RETRY_BACKOFF_RATELIMIT;\n this.queueAlgorithm = queueAlgorithm || MatrixScheduler.QUEUE_MESSAGES;\n this._queues = {\n // queueName: [{\n // event: MatrixEvent, // event to send\n // defer: Deferred, // defer to resolve/reject at the END of the retries\n // attempts: Number // number of times we've called processFn\n // }, ...]\n };\n this._activeQueues = [];\n this._procFn = null;\n}\n\n/**\n * Retrieve a queue based on an event. The event provided does not need to be in\n * the queue.\n * @param {MatrixEvent} event An event to get the queue for.\n * @return {?Array<MatrixEvent>} A shallow copy of events in the queue or null.\n * Modifying this array will not modify the list itself. Modifying events in\n * this array <i>will</i> modify the underlying event in the queue.\n * @see MatrixScheduler.removeEventFromQueue To remove an event from the queue.\n */\nMatrixScheduler.prototype.getQueueForEvent = function(event) {\n const name = this.queueAlgorithm(event);\n if (!name || !this._queues[name]) {\n return null;\n }\n return utils.map(this._queues[name], function(obj) {\n return obj.event;\n });\n};\n\n/**\n * Remove this event from the queue. The event is equal to another event if they\n * have the same ID returned from event.getId().\n * @param {MatrixEvent} event The event to remove.\n * @return {boolean} True if this event was removed.\n */\nMatrixScheduler.prototype.removeEventFromQueue = function(event) {\n const name = this.queueAlgorithm(event);\n if (!name || !this._queues[name]) {\n return false;\n }\n let removed = false;\n utils.removeElement(this._queues[name], function(element) {\n if (element.event.getId() === event.getId()) {\n // XXX we should probably reject the promise?\n // https://github.com/matrix-org/matrix-js-sdk/issues/496\n removed = true;\n return true;\n }\n });\n return removed;\n};\n\n\n/**\n * Set the process function. Required for events in the queue to be processed.\n * If set after events have been added to the queue, this will immediately start\n * processing them.\n * @param {module:scheduler~processFn} fn The function that can process events\n * in the queue.\n */\nMatrixScheduler.prototype.setProcessFunction = function(fn) {\n this._procFn = fn;\n _startProcessingQueues(this);\n};\n\n/**\n * Queue an event if it is required and start processing queues.\n * @param {MatrixEvent} event The event that may be queued.\n * @return {?Promise} A promise if the event was queued, which will be\n * resolved or rejected in due time, else null.\n */\nMatrixScheduler.prototype.queueEvent = function(event) {\n const queueName = this.queueAlgorithm(event);\n if (!queueName) {\n return null;\n }\n // add the event to the queue and make a deferred for it.\n if (!this._queues[queueName]) {\n this._queues[queueName] = [];\n }\n const defer = Promise.defer();\n this._queues[queueName].push({\n event: event,\n defer: defer,\n attempts: 0,\n });\n debuglog(\n \"Queue algorithm dumped event %s into queue '%s'\",\n event.getId(), queueName,\n );\n _startProcessingQueues(this);\n return defer.promise;\n};\n\n/**\n * Retries events up to 4 times using exponential backoff. This produces wait\n * times of 2, 4, 8, and 16 seconds (30s total) after which we give up. If the\n * failure was due to a rate limited request, the time specified in the error is\n * waited before being retried.\n * @param {MatrixEvent} event\n * @param {Number} attempts\n * @param {MatrixError} err\n * @return {Number}\n * @see module:scheduler~retryAlgorithm\n */\nMatrixScheduler.RETRY_BACKOFF_RATELIMIT = function(event, attempts, err) {\n if (err.httpStatus === 400 || err.httpStatus === 403 || err.httpStatus === 401) {\n // client error; no amount of retrying with save you now.\n return -1;\n }\n // we ship with browser-request which returns { cors: rejected } when trying\n // with no connection, so if we match that, give up since they have no conn.\n if (err.cors === \"rejected\") {\n return -1;\n }\n\n if (err.name === \"M_LIMIT_EXCEEDED\") {\n const waitTime = err.data.retry_after_ms;\n if (waitTime) {\n return waitTime;\n }\n }\n if (attempts > 4) {\n return -1; // give up\n }\n return (1000 * Math.pow(2, attempts));\n};\n\n/**\n * Queues <code>m.room.message</code> events and lets other events continue\n * concurrently.\n * @param {MatrixEvent} event\n * @return {string}\n * @see module:scheduler~queueAlgorithm\n */\nMatrixScheduler.QUEUE_MESSAGES = function(event) {\n if (event.getType() === \"m.room.message\") {\n // put these events in the 'message' queue.\n return \"message\";\n }\n // allow all other events continue concurrently.\n return null;\n};\n\nfunction _startProcessingQueues(scheduler) {\n if (!scheduler._procFn) {\n return;\n }\n // for each inactive queue with events in them\n utils.forEach(utils.filter(utils.keys(scheduler._queues), function(queueName) {\n return scheduler._activeQueues.indexOf(queueName) === -1 &&\n scheduler._queues[queueName].length > 0;\n }), function(queueName) {\n // mark the queue as active\n scheduler._activeQueues.push(queueName);\n // begin processing the head of the queue\n debuglog(\"Spinning up queue: '%s'\", queueName);\n _processQueue(scheduler, queueName);\n });\n}\n\nfunction _processQueue(scheduler, queueName) {\n // get head of queue\n const obj = _peekNextEvent(scheduler, queueName);\n if (!obj) {\n // queue is empty. Mark as inactive and stop recursing.\n const index = scheduler._activeQueues.indexOf(queueName);\n if (index >= 0) {\n scheduler._activeQueues.splice(index, 1);\n }\n debuglog(\"Stopping queue '%s' as it is now empty\", queueName);\n return;\n }\n debuglog(\n \"Queue '%s' has %s pending events\",\n queueName, scheduler._queues[queueName].length,\n );\n // fire the process function and if it resolves, resolve the deferred. Else\n // invoke the retry algorithm.\n scheduler._procFn(obj.event).done(function(res) {\n // remove this from the queue\n _removeNextEvent(scheduler, queueName);\n debuglog(\"Queue '%s' sent event %s\", queueName, obj.event.getId());\n obj.defer.resolve(res);\n // keep processing\n _processQueue(scheduler, queueName);\n }, function(err) {\n obj.attempts += 1;\n // ask the retry algorithm when/if we should try again\n const waitTimeMs = scheduler.retryAlgorithm(obj.event, obj.attempts, err);\n debuglog(\n \"retry(%s) err=%s event_id=%s waitTime=%s\",\n obj.attempts, err, obj.event.getId(), waitTimeMs,\n );\n if (waitTimeMs === -1) { // give up (you quitter!)\n debuglog(\n \"Queue '%s' giving up on event %s\", queueName, obj.event.getId(),\n );\n // remove this from the queue\n _removeNextEvent(scheduler, queueName);\n obj.defer.reject(err);\n // process next event\n _processQueue(scheduler, queueName);\n } else {\n setTimeout(function() {\n _processQueue(scheduler, queueName);\n }, waitTimeMs);\n }\n });\n}\n\nfunction _peekNextEvent(scheduler, queueName) {\n const queue = scheduler._queues[queueName];\n if (!utils.isArray(queue)) {\n return null;\n }\n return queue[0];\n}\n\nfunction _removeNextEvent(scheduler, queueName) {\n const queue = scheduler._queues[queueName];\n if (!utils.isArray(queue)) {\n return null;\n }\n return queue.shift();\n}\n\nfunction debuglog() {\n if (DEBUG) {\n console.log(...arguments);\n }\n}\n\n/**\n * The retry algorithm to apply when retrying events. To stop retrying, return\n * <code>-1</code>. If this event was part of a queue, it will be removed from\n * the queue.\n * @callback retryAlgorithm\n * @param {MatrixEvent} event The event being retried.\n * @param {Number} attempts The number of failed attempts. This will always be\n * >= 1.\n * @param {MatrixError} err The most recent error message received when trying\n * to send this event.\n * @return {Number} The number of milliseconds to wait before trying again. If\n * this is 0, the request will be immediately retried. If this is\n * <code>-1</code>, the event will be marked as\n * {@link module:models/event.EventStatus.NOT_SENT} and will not be retried.\n */\n\n/**\n * The queuing algorithm to apply to events. This function must be idempotent as\n * it may be called multiple times with the same event. All queues created are\n * serviced in a FIFO manner. To send the event ASAP, return <code>null</code>\n * which will not put this event in a queue. Events that fail to send that form\n * part of a queue will be removed from the queue and the next event in the\n * queue will be sent.\n * @callback queueAlgorithm\n * @param {MatrixEvent} event The event to be sent.\n * @return {string} The name of the queue to put the event into. If a queue with\n * this name does not exist, it will be created. If this is <code>null</code>,\n * the event is not put into a queue and will be sent concurrently.\n */\n\n /**\n * The function to invoke to process (send) events in the queue.\n * @callback processFn\n * @param {MatrixEvent} event The event to send.\n * @return {Promise} Resolved/rejected depending on the outcome of the request.\n */\n\n/**\n * The MatrixScheduler class.\n */\nmodule.exports = MatrixScheduler;\n"]}
\No newline at end of file