UNPKG

vulpes

Version:
835 lines (702 loc) 34.1 kB
"use strict"; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var EventEmitter = require("eventemitter3"); var merge = require("merge"); var ChannelQueue = require("@buttercup/channel-queue"); var endOfStream = require("end-of-stream"); var cron = require("node-cron"); var uuid = require("uuid/v4"); var _require = require("./symbols.js"), ITEM_TYPE = _require.ITEM_TYPE, ITEM_TYPE_SCHEDULED_TASK = _require.ITEM_TYPE_SCHEDULED_TASK; var ITEM_SCHEDULE_PREFIX = /^scheduled\//; /** * @typedef {Object} NewScheduledTask * @property {String} title - The scheduled job title * @property {String} schedule - The CRON formatted schedule for the job creation * @property {NewJob[]} jobs - An array of job templates * @property {Boolean} enabled - Whether the task is enabled or not */ /** * @typedef {NewScheduledTask} ScheduledTask * @property {String} id - The ID of the scheduled job */ /** * Scheduler for scheduled tasks * @augments EventEmitter */ var Scheduler = function (_EventEmitter) { _inherits(Scheduler, _EventEmitter); function Scheduler(service) { _classCallCheck(this, Scheduler); var _this = _possibleConstructorReturn(this, (Scheduler.__proto__ || Object.getPrototypeOf(Scheduler)).call(this)); _this._service = service; _this._channelQueue = new ChannelQueue(); _this._cronTasks = {}; _this.enabled = true; return _this; } /** * Service reference * @type {Service} * @memberof Scheduler */ _createClass(Scheduler, [{ key: "addScheduledJobs", /** * Add scheduled jobs * @deprecated Use `addScheduledTask` instead * @see Scheduler#addScheduledTask * @memberof Scheduler */ value: function addScheduledJobs() { return this.addScheduledTask.apply(this, arguments); } /** * Add scheduled jobs task * @param {NewScheduledTask} options Task structure for the newly scheduled job * @returns {String} The ID of the scheduled task * @memberof Scheduler * @throws {Error} Throws if the schedule is not a valid CRON format * @fires Scheduler#taskAdded */ }, { key: "addScheduledTask", value: function () { var _ref = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee() { var _task; var _ref2 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, title = _ref2.title, schedule = _ref2.schedule, jobs = _ref2.jobs, _ref2$enabled = _ref2.enabled, enabled = _ref2$enabled === undefined ? true : _ref2$enabled; var id, task; return regeneratorRuntime.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: if (cron.validate(schedule)) { _context.next = 2; break; } throw new Error("Invalid CRON schedule: " + schedule); case 2: id = uuid(); task = (_task = {}, _defineProperty(_task, ITEM_TYPE, ITEM_TYPE_SCHEDULED_TASK), _defineProperty(_task, "id", id), _defineProperty(_task, "title", title), _defineProperty(_task, "schedule", schedule), _defineProperty(_task, "enabled", enabled), _defineProperty(_task, "jobs", jobs), _task); _context.next = 6; return this._writeTask(task); case 6: this._watchTask(task); /** * Event for when a new task is added * @event Scheduler#taskAdded * @type {Object} * @property {String} id - The ID of the task * @property {String} title - The title of the task * @property {String} schedule - The CRON schedule for the task * @property {Boolean} enabled - Whether the task is enabled or not * @property {NewJob[]} jobs - Array of job templates for scheduled creation */ this.emit("taskAdded", task); return _context.abrupt("return", id); case 9: case "end": return _context.stop(); } } }, _callee, this); })); function addScheduledTask() { return _ref.apply(this, arguments); } return addScheduledTask; }() /** * Get a scheduled task by its ID * @param {String} id The ID of the task * @returns {Promise.<ScheduledTask>} A promise that resolves with the scheduled task * @memberof Scheduler */ }, { key: "getScheduledTask", value: function () { var _ref3 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee2(id) { return regeneratorRuntime.wrap(function _callee2$(_context2) { while (1) { switch (_context2.prev = _context2.next) { case 0: _context2.next = 2; return this.service.storage.getItem(id); case 2: return _context2.abrupt("return", _context2.sent); case 3: case "end": return _context2.stop(); } } }, _callee2, this); })); function getScheduledTask(_x2) { return _ref3.apply(this, arguments); } return getScheduledTask; }() /** * Get all scheduled tasks * @returns {Promise.<ScheduledTask[]>} A promise that resolves with an array of all * scheduled tasks * @memberof Scheduler */ }, { key: "getScheduledTasks", value: function () { var _ref4 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee3() { var itemStream, results; return regeneratorRuntime.wrap(function _callee3$(_context3) { while (1) { switch (_context3.prev = _context3.next) { case 0: _context3.next = 2; return this.service.storage.streamItems(); case 2: itemStream = _context3.sent; results = []; itemStream.on("data", function (item) { if (item[ITEM_TYPE] === ITEM_TYPE_SCHEDULED_TASK) { results.push(item); } }); _context3.next = 7; return new Promise(function (resolve, reject) { return endOfStream(itemStream, function (err) { if (err) { return reject(err); } resolve(); }); }); case 7: return _context3.abrupt("return", results); case 8: case "end": return _context3.stop(); } } }, _callee3, this); })); function getScheduledTasks() { return _ref4.apply(this, arguments); } return getScheduledTasks; }() /** * Initialise the scheduler * @returns {Promise} * @memberof Scheduler */ }, { key: "initialise", value: function () { var _ref5 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee5() { var _this2 = this; return regeneratorRuntime.wrap(function _callee5$(_context5) { while (1) { switch (_context5.prev = _context5.next) { case 0: if (!this.service.initialised) { _context5.next = 2; break; } throw new Error("Failed initialising Scheduler: Parent service already initialised"); case 2: _context5.next = 4; return this.taskQueue.enqueue(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee4() { var tasks; return regeneratorRuntime.wrap(function _callee4$(_context4) { while (1) { switch (_context4.prev = _context4.next) { case 0: _context4.next = 2; return _this2.getScheduledTasks(); case 2: tasks = _context4.sent; tasks.forEach(function (task) { return _this2._watchTask(task); }); case 4: case "end": return _context4.stop(); } } }, _callee4, _this2); }))); case 4: case "end": return _context5.stop(); } } }, _callee5, this); })); function initialise() { return _ref5.apply(this, arguments); } return initialise; }() /** * Remove a scheduled task * @returns {Promise} * @memberof Scheduler */ }, { key: "removeScheduledTask", value: function () { var _ref7 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee7(id) { var _this3 = this; return regeneratorRuntime.wrap(function _callee7$(_context7) { while (1) { switch (_context7.prev = _context7.next) { case 0: _context7.next = 2; return this.taskQueue.enqueue(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee6() { var cronTask; return regeneratorRuntime.wrap(function _callee6$(_context6) { while (1) { switch (_context6.prev = _context6.next) { case 0: _context6.next = 2; return _this3.service.storage.removeItem(id); case 2: cronTask = _this3._cronTasks[id]; delete _this3._cronTasks[id]; cronTask.destroy(); case 5: case "end": return _context6.stop(); } } }, _callee6, _this3); }))); case 2: case "end": return _context7.stop(); } } }, _callee7, this); })); function removeScheduledTask(_x3) { return _ref7.apply(this, arguments); } return removeScheduledTask; }() /** * Set the jobs array for a task * @param {String} taskID The ID of the task * @param {NewJob[]} jobs An array of job templates * @memberof Scheduler * @returns {Promise} * @fires Scheduler#taskJobsUpdated */ }, { key: "setJobsForScheduledTask", value: function () { var _ref9 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee8(taskID, jobs) { var task; return regeneratorRuntime.wrap(function _callee8$(_context8) { while (1) { switch (_context8.prev = _context8.next) { case 0: _context8.next = 2; return this.getScheduledTask(taskID); case 2: task = _context8.sent; task.jobs = jobs; _context8.next = 6; return this._writeTask(task); case 6: /** * Event for when a task's jobs are updated * @event Scheduler#taskJobsUpdated * @type {Object} * @property {String} id - The ID of the task * @property {NewJob[]} jobs - Array of job templates for scheduled creation */ this.emit("taskJobsUpdated", { id: taskID, jobs: jobs }); return _context8.abrupt("return", task); case 8: case "end": return _context8.stop(); } } }, _callee8, this); })); function setJobsForScheduledTask(_x4, _x5) { return _ref9.apply(this, arguments); } return setJobsForScheduledTask; }() /** * Shutdown the scheduler * @memberof Scheduler */ }, { key: "shutdown", value: function shutdown() { var _this4 = this; Object.keys(this._cronTasks).forEach(function (key) { var cronTask = _this4._cronTasks[key]; cronTask.destroy(); }); this._cronTasks = {}; } /** * Enable/disable a task * @param {String} taskID The ID of the task * @param {Boolean=} enabled Set the enabled status of the task to * true or false. If not specified, the status of the task will * be toggled. * @memberof Scheduler * @returns {ScheduledTask} Returns the toggled task * @fires Scheduler#taskStatusToggled */ }, { key: "toggleTask", value: function () { var _ref10 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee9(taskID, enabled) { var task; return regeneratorRuntime.wrap(function _callee9$(_context9) { while (1) { switch (_context9.prev = _context9.next) { case 0: _context9.next = 2; return this.getScheduledTask(taskID); case 2: task = _context9.sent; task.enabled = typeof enabled === "boolean" ? enabled : !task.enabled; _context9.next = 6; return this._writeTask(task); case 6: /** * Event for when a task has its status toggled (enabled/disabled) * @event Scheduler#taskStatusToggled * @type {Object} * @property {String} id - The ID of the task * @property {Boolean} enabled - Whether the task is enabled or disabled */ this.emit("taskStatusToggled", { id: taskID, enabled: task.enabled }); return _context9.abrupt("return", task); case 8: case "end": return _context9.stop(); } } }, _callee9, this); })); function toggleTask(_x6, _x7) { return _ref10.apply(this, arguments); } return toggleTask; }() /** * Trigger a task (skip schedule) * @param {String} taskID The scheduled task's ID * @returns {Promise} * @memberof Scheduler */ }, { key: "triggerTask", value: function () { var _ref11 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee10(taskID) { return regeneratorRuntime.wrap(function _callee10$(_context10) { while (1) { switch (_context10.prev = _context10.next) { case 0: _context10.next = 2; return this._executeTask(taskID, /* force: */true); case 2: case "end": return _context10.stop(); } } }, _callee10, this); })); function triggerTask(_x8) { return _ref11.apply(this, arguments); } return triggerTask; }() /** * @typedef {Object} UpdateTaskPropertiesOptions * @property {String=} title - The title of the task * @property {String=} schedule - The schedule of the task (CRON) */ /** * Update properties of a task * @param {String} taskID The ID of the task to update * @param {UpdateTaskPropertiesOptions} ops Properties to update on the task * @returns {ScheduledTask} Returns the toggled task * @memberof Scheduler * @fires Scheduler#taskPropertiesUpdated */ }, { key: "updateTaskProperties", value: function () { var _ref12 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee11(taskID) { var _ref13 = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, title = _ref13.title, schedule = _ref13.schedule; var task; return regeneratorRuntime.wrap(function _callee11$(_context11) { while (1) { switch (_context11.prev = _context11.next) { case 0: _context11.next = 2; return this.getScheduledTask(taskID); case 2: task = _context11.sent; if (title) { task.title = title; } if (!schedule) { _context11.next = 8; break; } if (cron.validate(schedule)) { _context11.next = 7; break; } throw new Error("Invalid CRON schedule: " + schedule); case 7: task.schedule = schedule; case 8: _context11.next = 10; return this._writeTask(task); case 10: // Remove CRON watcher this._unwatchTask(task); // Set new CRON watcher (schedule changed) this._watchTask(task); /** * Event for when a task's properties (title/schedule) are updated * @event Scheduler#taskPropertiesUpdated * @type {Object} * @property {String} id - The ID of the task * @property {String} title - The title of the task * @property {String} schedule - The CRON schedule for the task */ this.emit("taskPropertiesUpdated", { id: taskID, title: task.title, schedule: task.schedule }); return _context11.abrupt("return", task); case 14: case "end": return _context11.stop(); } } }, _callee11, this); })); function updateTaskProperties(_x9) { return _ref12.apply(this, arguments); } return updateTaskProperties; }() /** * Schedule a CRON execution * @property {String} schedule - The minute-accurate CRON string * @property {Function} cb - The callback to fire when the CRON timer matches current time * @protected * @returns {Object} The CRON task * @memberof Scheduler */ }, { key: "_cronSchedule", value: function _cronSchedule(schedule, cb) { return cron.schedule(schedule, cb); } /** * Execute a task * @param {ScheduledTask|String} taskOrTaskID The scheduled task or an ID of a task * @param {Boolean=} force Optionally force the execution (bypass disabled statuses). * Default is false. * @protected * @fires Scheduler#createdJobsFromTask * @memberof Scheduler */ }, { key: "_executeTask", value: function () { var _ref14 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee12(taskOrTaskID) { var force = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var activatedTask, jobs; return regeneratorRuntime.wrap(function _callee12$(_context12) { while (1) { switch (_context12.prev = _context12.next) { case 0: _context12.next = 2; return this.getScheduledTask(typeof taskOrTaskID === "string" ? taskOrTaskID : taskOrTaskID.id); case 2: activatedTask = _context12.sent; if (!(!force && (!activatedTask || activatedTask.enabled !== true || !this.enabled))) { _context12.next = 5; break; } return _context12.abrupt("return"); case 5: _context12.next = 7; return this.service.addJobs(activatedTask.jobs); case 7: jobs = _context12.sent; /** * Event for when jobs are created as a result of a scheduled task * having been fired using its CRON schedule * @event Scheduler#createdJobsFromTask * @type {Object} * @property {String} id - The ID of the task * @property {String} title - The title of the task * @property {String} schedule - The CRON schedule for the task * @property {NewJob[]} jobs - Array of job templates for scheduled creation */ this.emit("createdJobsFromTask", { jobs: jobs, id: activatedTask.id, title: activatedTask.title, schedule: activatedTask.schedule }); case 9: case "end": return _context12.stop(); } } }, _callee12, this); })); function _executeTask(_x11) { return _ref14.apply(this, arguments); } return _executeTask; }() /** * Unwatch a CRON task (deschedule it) * @param {ScheduledTask} task The task to deschedule * @returns {Boolean} True if a task was found, false otherwise * @protected * @memberof Scheduler */ }, { key: "_unwatchTask", value: function _unwatchTask(task) { var cronTask = this._cronTasks[task.id]; if (!cronTask) { return false; } cronTask.destroy(); delete this._cronTasks[task.id]; return true; } /** * Watch a task (start timer for scheduling) * @param {ScheduledTask} task The task to watch * @protected * @memberof Scheduler * @fires Scheduler#taskScheduled */ }, { key: "_watchTask", value: function _watchTask(task) { var _this5 = this; var cronTask = this._cronSchedule(task.schedule, function () { return _this5._executeTask(task); }); /** * Event for when a task has been scheduled (fired both when created and * when being read from storage upon a fresh start-up) * @event Scheduler#taskScheduled * @type {Object} * @property {String} id - The ID of the task * @property {String} title - The title of the task * @property {String} schedule - The CRON schedule for the task * @property {Boolean} enabled - Whether the task is enabled or not */ this.emit("taskScheduled", { id: task.id, title: task.title, schedule: task.schedule, enabled: task.enabled }); this._cronTasks[task.id] = cronTask; } /** * Write a task to storage * @param {ScheduledTask} task The task to write (will overwrite) * @returns {Promise} * @memberof Scheduler * @protected */ }, { key: "_writeTask", value: function () { var _ref15 = _asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee14(task) { var _this6 = this; return regeneratorRuntime.wrap(function _callee14$(_context14) { while (1) { switch (_context14.prev = _context14.next) { case 0: _context14.next = 2; return this.taskQueue.enqueue(_asyncToGenerator( /*#__PURE__*/regeneratorRuntime.mark(function _callee13() { return regeneratorRuntime.wrap(function _callee13$(_context13) { while (1) { switch (_context13.prev = _context13.next) { case 0: _context13.next = 2; return _this6.service.storage.setItem(task.id, task); case 2: case "end": return _context13.stop(); } } }, _callee13, _this6); }))); case 2: case "end": return _context14.stop(); } } }, _callee14, this); })); function _writeTask(_x13) { return _ref15.apply(this, arguments); } return _writeTask; }() }, { key: "service", get: function get() { return this._service; } /** * Task queue for job schedule checks * @type {Channel} * @readonly * @memberof Scheduler */ }, { key: "taskQueue", get: function get() { return this._channelQueue.channel("scheduler"); } }]); return Scheduler; }(EventEmitter); module.exports = Scheduler;