core.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689
  1. import config from "config";
  2. import { EventEmitter } from "events";
  3. class DeferredPromise {
  4. // eslint-disable-next-line require-jsdoc
  5. constructor() {
  6. this.promise = new Promise((resolve, reject) => {
  7. this.reject = reject;
  8. this.resolve = resolve;
  9. });
  10. }
  11. }
  12. class QueueTask {
  13. // eslint-disable-next-line require-jsdoc
  14. constructor(job, options, priority) {
  15. this.job = job;
  16. this.options = options;
  17. this.priority = priority;
  18. this.job.setTask(this);
  19. }
  20. }
  21. class Queue {
  22. // eslint-disable-next-line require-jsdoc
  23. constructor(handleTaskFunction, concurrency) {
  24. this.handleTaskFunction = handleTaskFunction;
  25. this.concurrency = concurrency;
  26. this.queue = [];
  27. this.runningTasks = [];
  28. this.pausedTasks = [];
  29. this.paused = false;
  30. }
  31. /**
  32. * Pauses the queue, meaning no new jobs can be started. Jobs can still be added to the queue, and already running tasks won't be paused.
  33. */
  34. pause() {
  35. this.paused = true;
  36. }
  37. /**
  38. * Resumes the queue.
  39. */
  40. resume() {
  41. this.paused = false;
  42. setTimeout(() => {
  43. this._handleQueue();
  44. }, 0);
  45. }
  46. /**
  47. * Returns the amount of jobs in the queue.
  48. *
  49. * @returns {number} - amount of jobs in queue
  50. */
  51. lengthQueue() {
  52. return this.queue.length;
  53. }
  54. /**
  55. * Returns the amount of running jobs.
  56. *
  57. * @returns {number} - amount of running jobs
  58. */
  59. lengthRunning() {
  60. return this.runningTasks.length;
  61. }
  62. /**
  63. * Returns the amount of running jobs.
  64. *
  65. * @returns {number} - amount of running jobs
  66. */
  67. lengthPaused() {
  68. return this.pausedTasks.length;
  69. }
  70. /**
  71. * Adds a job to the queue, with a given priority.
  72. *
  73. * @param {object} job - the job that is to be added
  74. * @param {object} options - custom options e.g. isQuiet. Optional.
  75. * @param {number} priority - the priority of the to be added job
  76. */
  77. push(job, options, priority) {
  78. this.queue.push(new QueueTask(job, options, priority));
  79. setTimeout(() => {
  80. this._handleQueue();
  81. }, 0);
  82. }
  83. /**
  84. * Removes a job currently running from the queue.
  85. *
  86. * @param {object} job - the job to be removed
  87. */
  88. removeRunningJob(job) {
  89. this.runningTasks.remove(this.runningTasks.find(task => task.job.toString() === job.toString()));
  90. }
  91. /**
  92. * Pauses a job currently running from the queue.
  93. *
  94. * @param {object} job - the job to be pauses
  95. */
  96. pauseRunningJob(job) {
  97. const task = this.runningTasks.find(task => task.job.toString() === job.toString());
  98. if (!task) {
  99. console.log(
  100. `Attempted to pause job ${job.name} (${job.toString()}), but couldn't find it in running tasks.`
  101. );
  102. return;
  103. }
  104. this.runningTasks.remove(task);
  105. this.pausedTasks.push(task);
  106. }
  107. /**
  108. * Resumes a job currently paused, adding the job back to the front of the queue
  109. *
  110. * @param {object} job - the job to be pauses
  111. */
  112. resumeRunningJob(job) {
  113. const task = this.pausedTasks.find(task => task.job.toString() === job.toString());
  114. if (!task) {
  115. console.log(
  116. `Attempted to resume job ${job.name} (${job.toString()}), but couldn't find it in paused tasks.`
  117. );
  118. return;
  119. }
  120. this.pausedTasks.remove(task);
  121. this.queue.unshift(task);
  122. setTimeout(() => {
  123. this._handleQueue();
  124. }, 0);
  125. }
  126. /**
  127. * Check if there's room for a job to be processed, and if there is, run it.
  128. */
  129. _handleQueue() {
  130. if (this.queue.length > 0) {
  131. const task = this.queue.reduce((a, b) => (a.priority < b.priority ? a : b));
  132. if (task) {
  133. if ((!this.paused && this.runningTasks.length < this.concurrency) || task.priority === -1) {
  134. this.queue.remove(task);
  135. this.runningTasks.push(task);
  136. this._handleTask(task);
  137. setTimeout(() => {
  138. this._handleQueue();
  139. }, 0);
  140. }
  141. }
  142. }
  143. }
  144. /**
  145. * Handles a task, calling the handleTaskFunction provided in the constructor
  146. *
  147. * @param {object} task - the task to be handled
  148. */
  149. _handleTask(task) {
  150. this.handleTaskFunction(task.job, task.options).finally(() => {
  151. this.runningTasks.remove(task);
  152. this._handleQueue();
  153. });
  154. }
  155. }
  156. class Job {
  157. // eslint-disable-next-line require-jsdoc
  158. constructor(name, payload, onFinish, module, parentJob, options) {
  159. this.name = name;
  160. this.payload = payload;
  161. this.response = null;
  162. this.responseType = null;
  163. this.onFinish = onFinish;
  164. this.module = module;
  165. this.parentJob = parentJob;
  166. this.childJobs = [];
  167. /* eslint-disable no-bitwise, eqeqeq */
  168. this.uniqueId = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, c => {
  169. const r = (Math.random() * 16) | 0;
  170. const v = c == "x" ? r : (r & 0x3) | 0x8;
  171. return v.toString(16);
  172. });
  173. this.status = "INITIALIZED";
  174. this.task = null;
  175. this.onProgress = options.onProgress;
  176. this.lastProgressData = null;
  177. this.lastProgressTime = Date.now();
  178. this.lastProgressTimeout = null;
  179. }
  180. /**
  181. * Adds a child job to this job
  182. *
  183. * @param {object} childJob - the child job
  184. */
  185. addChildJob(childJob) {
  186. this.childJobs.push(childJob);
  187. }
  188. /**
  189. * Sets the job status
  190. *
  191. * @param {string} status - the new status
  192. */
  193. setStatus(status) {
  194. this.status = status;
  195. }
  196. /**
  197. * Sets the task for a job
  198. *
  199. * @param {string} task - the job task
  200. */
  201. setTask(task) {
  202. this.task = task;
  203. }
  204. /**
  205. * Returns the UUID of the job, allowing you to compare jobs with toString
  206. *
  207. * @returns {string} - the job's UUID/uniqueId
  208. */
  209. toString() {
  210. return this.uniqueId;
  211. }
  212. /**
  213. * Sets the response that will be provided to the onFinish DeferredPromise resolve/reject function, as soon as the job is done if it has no parent, or when the parent job is resumed
  214. *
  215. * @param {object} response - the response
  216. */
  217. setResponse(response) {
  218. this.response = response;
  219. }
  220. /**
  221. * Sets the response type that is paired with the response. If it is RESOLVE/REJECT, then it will resolve/reject with the response. If it is RESOLVED/REJECTED, then it has already resolved/rejected with the response.
  222. *
  223. * @param {string} responseType - the response type, so RESOLVE/REJECT/RESOLVED/REJECTED
  224. */
  225. setResponseType(responseType) {
  226. this.responseType = responseType;
  227. }
  228. /**
  229. * Removes child jobs to prevent memory leak
  230. */
  231. cleanup() {
  232. this.childJobs = this.childJobs.map(() => null);
  233. }
  234. /**
  235. * Logs to the module of the job
  236. *
  237. * @param {any} args - Anything to be added to the log e.g. log type, log message
  238. */
  239. log(...args) {
  240. args.splice(1, 0, this.name); // Adds the name of the job as the first argument (after INFO/SUCCESS/ERROR).
  241. this.module.log(...args);
  242. }
  243. /**
  244. *
  245. * @param {data} data - Data to publish upon progress
  246. */
  247. publishProgress(data) {
  248. if (this.onProgress) {
  249. this.lastProgressData = data;
  250. if (data.status === "update") {
  251. if ((Date.now() - this.lastProgressTime) > 1000) {
  252. this.lastProgressTime = Date.now();
  253. } else {
  254. if (this.lastProgressTimeout) clearTimeout(this.lastProgressTimeout);
  255. this.lastProgressTimeout = setTimeout(() => {
  256. this.lastProgressTime = Date.now();
  257. this.lastProgressTimeout = null;
  258. this.onProgress.emit("progress", data);
  259. }, Date.now() - this.lastProgressTime);
  260. return;
  261. }
  262. } else if (data.status === "success" || data.status === "error")
  263. if (this.lastProgressTimeout) clearTimeout(this.lastProgressTimeout);
  264. this.onProgress.emit("progress", data);
  265. } else this.log("Progress published, but no onProgress specified.")
  266. }
  267. }
  268. class MovingAverageCalculator {
  269. // eslint-disable-next-line require-jsdoc
  270. constructor() {
  271. this.count = 0;
  272. this._mean = 0;
  273. }
  274. /**
  275. * Updates the mean average
  276. *
  277. * @param {number} newValue - the new time it took to complete a job
  278. */
  279. update(newValue) {
  280. this.count += 1;
  281. const differential = (newValue - this._mean) / this.count;
  282. this._mean += differential;
  283. }
  284. /**
  285. * Returns the mean average
  286. *
  287. * @returns {number} - returns the mean average
  288. */
  289. get mean() {
  290. this.validate();
  291. return this._mean;
  292. }
  293. /**
  294. * Checks that the mean is valid
  295. */
  296. validate() {
  297. if (this.count === 0) throw new Error("Mean is undefined");
  298. }
  299. }
  300. export default class CoreClass {
  301. /**
  302. *
  303. * @param {string} name - the name of the class
  304. * @param {object} options - optional options
  305. * @param {number} options.concurrency - how many jobs can run at the same time
  306. * @param {object} options.priorities - custom priorities for jobs
  307. */
  308. constructor(name, options) {
  309. this.name = name;
  310. this.status = "UNINITIALIZED";
  311. this.concurrency = options && options.concurrency ? options.concurrency : 10;
  312. this.jobQueue = new Queue((job, options) => this._runJob(job, options), this.concurrency);
  313. this.jobQueue.pause();
  314. this.priorities = options && options.priorities ? options.priorities : {};
  315. this.stage = 0;
  316. this.jobStatistics = {};
  317. this.jobNames = [];
  318. this.logRules = config.get("customLoggingPerModule")[name]
  319. ? config.get("customLoggingPerModule")[name]
  320. : config.get("defaultLogging");
  321. this.registerJobs();
  322. }
  323. /**
  324. * Sets the status of a module
  325. *
  326. * @param {string} status - the new status of a module
  327. */
  328. setStatus(status) {
  329. this.status = status;
  330. this.log("INFO", `Status changed to: ${status}`);
  331. if (this.status === "READY") this.jobQueue.resume();
  332. else if (this.status === "FAIL" || this.status === "LOCKDOWN") this.jobQueue.pause();
  333. }
  334. /**
  335. * Returns the status of a module
  336. *
  337. * @returns {string} - the status of a module
  338. */
  339. getStatus() {
  340. return this.status;
  341. }
  342. /**
  343. * Changes the current stage of a module
  344. *
  345. * @param {string} stage - the new stage of a module
  346. */
  347. setStage(stage) {
  348. this.stage = stage;
  349. }
  350. /**
  351. * Returns the current stage of a module
  352. *
  353. * @returns {string} - the current stage of a module
  354. */
  355. getStage() {
  356. return this.stage;
  357. }
  358. /**
  359. * Initialises a module and handles initialise successes and failures
  360. */
  361. _initialize() {
  362. this.setStatus("INITIALIZING");
  363. this.initialize()
  364. .then(() => {
  365. this.setStatus("READY");
  366. this.moduleManager.onInitialize(this);
  367. })
  368. .catch(err => {
  369. console.error(err);
  370. this.setStatus("FAILED");
  371. this.moduleManager.onFail(this);
  372. });
  373. }
  374. /**
  375. * Creates a new log message
  376. *
  377. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  378. */
  379. log(...args) {
  380. const _arguments = Array.from(args);
  381. const type = _arguments[0];
  382. if (config.debug && config.debug.stationIssue === true && type === "STATION_ISSUE") {
  383. this.moduleManager.debugLogs.stationIssue.push(_arguments);
  384. return;
  385. }
  386. if (this.logRules.hideType.indexOf(type) !== -1) return;
  387. _arguments.splice(0, 1);
  388. const start = `|${this.name.toUpperCase()}|`;
  389. const numberOfSpacesNeeded = 20 - start.length;
  390. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  391. if (this.logRules.blacklistedTerms.some(blacklistedTerm => _arguments.join().indexOf(blacklistedTerm) !== -1))
  392. return;
  393. if (type === "INFO" || type === "SUCCESS") {
  394. _arguments[0] += "\x1b[36m";
  395. _arguments.push("\x1b[0m");
  396. console.log.apply(null, _arguments);
  397. } else if (type === "ERROR") {
  398. _arguments[0] += "\x1b[31m";
  399. _arguments.push("\x1b[0m");
  400. console.error.apply(null, _arguments);
  401. }
  402. }
  403. /**
  404. * Sets up each job with the statistics service (includes mean average for job completion)
  405. */
  406. registerJobs() {
  407. let props = [];
  408. let obj = this;
  409. do {
  410. props = props.concat(Object.getOwnPropertyNames(obj));
  411. // eslint-disable-next-line no-cond-assign
  412. } while ((obj = Object.getPrototypeOf(obj)));
  413. const jobNames = props.sort().filter(prop => typeof this[prop] === "function" && prop === prop.toUpperCase());
  414. jobNames.forEach(jobName => {
  415. this.jobStatistics[jobName] = {
  416. successful: 0,
  417. failed: 0,
  418. total: 0,
  419. averageTiming: new MovingAverageCalculator()
  420. };
  421. });
  422. this.jobNames = jobNames;
  423. }
  424. /**
  425. * Runs a job
  426. *
  427. * @param {string} name - the name of the job e.g. GET_PLAYLIST
  428. * @param {object} payload - any expected payload for the job itself
  429. * @param {object} parentJob - the parent job, if any
  430. * @param {number} priority - custom priority. Optional.
  431. * @param {object} options - custom options e.g. isQuiet. Optional.
  432. * @returns {Promise} - returns a promise
  433. */
  434. runJob(name, payload, parentJob, priority, options) {
  435. /** Allows for any combination of optional parameters (parentJob, priority, options) */
  436. let _options;
  437. let _priority;
  438. let _parentJob;
  439. if (parentJob) {
  440. if (typeof parentJob === "object")
  441. if (!parentJob.name) _options = parentJob;
  442. else _parentJob = parentJob;
  443. else if (typeof parentJob === "number") _priority = parentJob;
  444. }
  445. if (options) {
  446. if (typeof options === "object")
  447. if (options.name) _parentJob = options;
  448. else _options = options;
  449. if (typeof options === "number") _priority = options;
  450. }
  451. if (priority && typeof priority === "object") {
  452. if (!priority.name) _options = priority;
  453. else _parentJob = priority;
  454. } else _priority = priority;
  455. if (!_options) _options = { isQuiet: false };
  456. if (_options && typeof _options.onProgress === "function") {
  457. const onProgress = new EventEmitter();
  458. onProgress.on("progress", _options.onProgress);
  459. _options.onProgress = onProgress;
  460. }
  461. if (!_options.onProgress && parentJob) _options.onProgress = parentJob.onProgress;
  462. const deferredPromise = new DeferredPromise();
  463. const job = new Job(name, payload, deferredPromise, this, _parentJob, { onProgress: _options.onProgress });
  464. this.log("INFO", `Queuing job ${name} (${job.toString()})`);
  465. if (_parentJob) {
  466. _parentJob.addChildJob(job);
  467. if (_parentJob.status === "RUNNING") {
  468. this.log(
  469. "INFO",
  470. `Pausing job ${_parentJob.name} (${_parentJob.toString()}) since a child job has to run first`
  471. );
  472. _parentJob.setStatus("WAITING_ON_CHILD_JOB");
  473. _parentJob.module.jobQueue.pauseRunningJob(_parentJob);
  474. } else {
  475. this.log(
  476. "INFO",
  477. `Not pausing job ${_parentJob.name} (${_parentJob.toString()}) since it's already paused`
  478. );
  479. }
  480. }
  481. job.setStatus("QUEUED");
  482. let calculatedPriority = null;
  483. if (_priority) calculatedPriority = _priority;
  484. else if (this.priorities[name]) calculatedPriority = this.priorities[name];
  485. else if (_parentJob) calculatedPriority = _parentJob.task.priority;
  486. else calculatedPriority = 10;
  487. this.jobQueue.push(job, _options, calculatedPriority);
  488. if (
  489. config.debug &&
  490. config.debug.stationIssue === true &&
  491. config.debug.captureJobs &&
  492. config.debug.captureJobs.indexOf(name) !== -1
  493. ) {
  494. this.moduleManager.debugJobs.all.push({ job, _priority });
  495. }
  496. return deferredPromise.promise;
  497. }
  498. /**
  499. * UNKNOWN
  500. *
  501. * @param {object} moduleManager - UNKNOWN
  502. */
  503. setModuleManager(moduleManager) {
  504. this.moduleManager = moduleManager;
  505. }
  506. /**
  507. * Actually runs the job? UNKNOWN
  508. *
  509. * @param {object} job - object containing details of the job
  510. * @param {string} job.name - the name of the job e.g. GET_PLAYLIST
  511. * @param {string} job.payload - any expected payload for the job itself
  512. * @param {Promise} job.onFinish - deferred promise when the job is complete
  513. * @param {object} options - custom options e.g. isQuiet. Optional.
  514. * @returns {Promise} - returns a promise
  515. */
  516. _runJob(job, options) {
  517. if (!options.isQuiet) this.log("INFO", `Running job ${job.name} (${job.toString()})`);
  518. return new Promise(resolve => {
  519. const startTime = Date.now();
  520. const previousStatus = job.status;
  521. job.setStatus("RUNNING");
  522. this.moduleManager.jobManager.addJob(job);
  523. if (previousStatus === "QUEUED") {
  524. if (!options.isQuiet) this.log("INFO", `Job ${job.name} (${job.toString()}) is queued, so calling it`);
  525. if (this[job.name])
  526. this[job.name]
  527. .apply(job, [job.payload])
  528. .then(response => {
  529. if (!options.isQuiet) this.log("INFO", `Ran job ${job.name} (${job.toString()}) successfully`);
  530. job.setStatus("FINISHED");
  531. job.setResponse(response);
  532. this.jobStatistics[job.name].successful += 1;
  533. job.setResponseType("RESOLVE");
  534. if (
  535. config.debug &&
  536. config.debug.stationIssue === true &&
  537. config.debug.captureJobs &&
  538. config.debug.captureJobs.indexOf(job.name) !== -1
  539. ) {
  540. this.moduleManager.debugJobs.completed.push({
  541. status: "success",
  542. job,
  543. priority: job.task.priority,
  544. response
  545. });
  546. }
  547. })
  548. .catch(error => {
  549. this.log("INFO", `Running job ${job.name} (${job.toString()}) failed`);
  550. job.setStatus("FINISHED");
  551. job.setResponse(error);
  552. job.setResponseType("REJECT");
  553. this.jobStatistics[job.name].failed += 1;
  554. if (
  555. config.debug &&
  556. config.debug.stationIssue === true &&
  557. config.debug.captureJobs &&
  558. config.debug.captureJobs.indexOf(job.name) !== -1
  559. ) {
  560. this.moduleManager.debugJobs.completed.push({
  561. status: "error",
  562. job,
  563. error
  564. });
  565. }
  566. })
  567. .finally(() => {
  568. const endTime = Date.now();
  569. const executionTime = endTime - startTime;
  570. this.jobStatistics[job.name].total += 1;
  571. this.jobStatistics[job.name].averageTiming.update(executionTime);
  572. this.moduleManager.jobManager.removeJob(job);
  573. job.cleanup();
  574. if (!job.parentJob) {
  575. if (job.responseType === "RESOLVE") {
  576. job.onFinish.resolve(job.response);
  577. job.responseType = "RESOLVED";
  578. } else if (job.responseType === "REJECT") {
  579. job.onFinish.reject(job.response);
  580. job.responseType = "REJECTED";
  581. }
  582. } else if (
  583. job.parentJob &&
  584. job.parentJob.childJobs.find(childJob =>
  585. childJob ? childJob.status !== "FINISHED" : true
  586. ) === undefined
  587. ) {
  588. if (job.parentJob.status !== "WAITING_ON_CHILD_JOB") {
  589. this.log(
  590. "ERROR",
  591. `Job ${
  592. job.parentJob.name
  593. } (${job.parentJob.toString()}) had a child job complete even though it is not waiting on a child job. This should never happen.`
  594. );
  595. } else {
  596. job.parentJob.setStatus("REQUEUED");
  597. job.parentJob.module.jobQueue.resumeRunningJob(job.parentJob);
  598. }
  599. }
  600. resolve();
  601. });
  602. else
  603. this.log("ERROR", `Job not found! ${job.name}`)
  604. } else {
  605. this.log(
  606. "INFO",
  607. `Job ${job.name} (${job.toString()}) is re-queued, so resolving/rejecting all child jobs.`
  608. );
  609. job.childJobs.forEach(childJob => {
  610. if (childJob.responseType === "RESOLVE") {
  611. childJob.onFinish.resolve(childJob.response);
  612. childJob.responseType = "RESOLVED";
  613. } else if (childJob.responseType === "REJECT") {
  614. childJob.onFinish.reject(childJob.response);
  615. childJob.responseType = "REJECTED";
  616. }
  617. });
  618. }
  619. });
  620. }
  621. }