core.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719
  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. this.longJob = false;
  180. this.longJobTitle = "";
  181. this.longJobStatus = "";
  182. }
  183. /**
  184. * Adds a child job to this job
  185. *
  186. * @param {object} childJob - the child job
  187. */
  188. addChildJob(childJob) {
  189. this.childJobs.push(childJob);
  190. }
  191. /**
  192. * Sets the job status
  193. *
  194. * @param {string} status - the new status
  195. */
  196. setStatus(status) {
  197. this.status = status;
  198. }
  199. /**
  200. * Sets the task for a job
  201. *
  202. * @param {string} task - the job task
  203. */
  204. setTask(task) {
  205. this.task = task;
  206. }
  207. /**
  208. * Returns the UUID of the job, allowing you to compare jobs with toString
  209. *
  210. * @returns {string} - the job's UUID/uniqueId
  211. */
  212. toString() {
  213. return this.uniqueId;
  214. }
  215. /**
  216. * 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
  217. *
  218. * @param {object} response - the response
  219. */
  220. setResponse(response) {
  221. this.response = response;
  222. }
  223. /**
  224. * 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.
  225. *
  226. * @param {string} responseType - the response type, so RESOLVE/REJECT/RESOLVED/REJECTED
  227. */
  228. setResponseType(responseType) {
  229. this.responseType = responseType;
  230. }
  231. /**
  232. * Removes child jobs to prevent memory leak
  233. */
  234. cleanup() {
  235. this.childJobs = this.childJobs.map(() => null);
  236. }
  237. /**
  238. * Logs to the module of the job
  239. *
  240. * @param {any} args - Anything to be added to the log e.g. log type, log message
  241. */
  242. log(...args) {
  243. args.splice(1, 0, this.name); // Adds the name of the job as the first argument (after INFO/SUCCESS/ERROR).
  244. this.module.log(...args);
  245. }
  246. /**
  247. * Set whether this job is a long job.
  248. */
  249. keepLongJob() {
  250. this.longJob = true;
  251. }
  252. /**
  253. * Forget long job.
  254. */
  255. forgetLongJob() {
  256. this.longJob = false;
  257. this.module.moduleManager.jobManager.removeJob(this);
  258. }
  259. /**
  260. * Update and emit progress of job
  261. *
  262. * @param {data} data - Data to publish upon progress
  263. * @param {boolean} notALongJob - Whether job is not a long job
  264. */
  265. publishProgress(data, notALongJob) {
  266. if (this.longJob || notALongJob) {
  267. if (this.onProgress) {
  268. if (notALongJob) {
  269. this.onProgress.emit("progress", data);
  270. } else {
  271. this.lastProgressData = data;
  272. if (data.status === "update") {
  273. if (Date.now() - this.lastProgressTime > 1000) {
  274. this.lastProgressTime = Date.now();
  275. } else {
  276. if (this.lastProgressTimeout) clearTimeout(this.lastProgressTimeout);
  277. this.lastProgressTimeout = setTimeout(() => {
  278. this.lastProgressTime = Date.now();
  279. this.lastProgressTimeout = null;
  280. this.onProgress.emit("progress", data);
  281. }, Date.now() - this.lastProgressTime);
  282. return;
  283. }
  284. } else if (data.status === "success" || data.status === "error")
  285. if (this.lastProgressTimeout) clearTimeout(this.lastProgressTimeout);
  286. if (data.title) this.longJobTitle = data.title;
  287. this.onProgress.emit("progress", data);
  288. }
  289. } else this.log("Progress published, but no onProgress specified.");
  290. } else {
  291. this.parentJob.publishProgress(data);
  292. }
  293. }
  294. }
  295. class MovingAverageCalculator {
  296. // eslint-disable-next-line require-jsdoc
  297. constructor() {
  298. this.count = 0;
  299. this._mean = 0;
  300. }
  301. /**
  302. * Updates the mean average
  303. *
  304. * @param {number} newValue - the new time it took to complete a job
  305. */
  306. update(newValue) {
  307. this.count += 1;
  308. const differential = (newValue - this._mean) / this.count;
  309. this._mean += differential;
  310. }
  311. /**
  312. * Returns the mean average
  313. *
  314. * @returns {number} - returns the mean average
  315. */
  316. get mean() {
  317. this.validate();
  318. return this._mean;
  319. }
  320. /**
  321. * Checks that the mean is valid
  322. */
  323. validate() {
  324. if (this.count === 0) throw new Error("Mean is undefined");
  325. }
  326. }
  327. export default class CoreClass {
  328. /**
  329. *
  330. * @param {string} name - the name of the class
  331. * @param {object} options - optional options
  332. * @param {number} options.concurrency - how many jobs can run at the same time
  333. * @param {object} options.priorities - custom priorities for jobs
  334. */
  335. constructor(name, options) {
  336. this.name = name;
  337. this.status = "UNINITIALIZED";
  338. this.concurrency = options && options.concurrency ? options.concurrency : 10;
  339. this.jobQueue = new Queue((job, options) => this._runJob(job, options), this.concurrency);
  340. this.jobQueue.pause();
  341. this.priorities = options && options.priorities ? options.priorities : {};
  342. this.stage = 0;
  343. this.jobStatistics = {};
  344. this.jobNames = [];
  345. this.logRules = config.get("customLoggingPerModule")[name]
  346. ? config.get("customLoggingPerModule")[name]
  347. : config.get("defaultLogging");
  348. this.registerJobs();
  349. }
  350. /**
  351. * Sets the status of a module
  352. *
  353. * @param {string} status - the new status of a module
  354. */
  355. setStatus(status) {
  356. this.status = status;
  357. this.log("INFO", `Status changed to: ${status}`);
  358. if (this.status === "READY") this.jobQueue.resume();
  359. else if (this.status === "FAIL" || this.status === "LOCKDOWN") this.jobQueue.pause();
  360. }
  361. /**
  362. * Returns the status of a module
  363. *
  364. * @returns {string} - the status of a module
  365. */
  366. getStatus() {
  367. return this.status;
  368. }
  369. /**
  370. * Changes the current stage of a module
  371. *
  372. * @param {string} stage - the new stage of a module
  373. */
  374. setStage(stage) {
  375. this.stage = stage;
  376. }
  377. /**
  378. * Returns the current stage of a module
  379. *
  380. * @returns {string} - the current stage of a module
  381. */
  382. getStage() {
  383. return this.stage;
  384. }
  385. /**
  386. * Initialises a module and handles initialise successes and failures
  387. */
  388. _initialize() {
  389. this.setStatus("INITIALIZING");
  390. this.initialize()
  391. .then(() => {
  392. this.setStatus("READY");
  393. this.moduleManager.onInitialize(this);
  394. })
  395. .catch(err => {
  396. console.error(err);
  397. this.setStatus("FAILED");
  398. this.moduleManager.onFail(this);
  399. });
  400. }
  401. /**
  402. * Creates a new log message
  403. *
  404. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  405. */
  406. log(...args) {
  407. const _arguments = Array.from(args);
  408. const type = _arguments[0];
  409. if (config.debug && config.debug.stationIssue === true && type === "STATION_ISSUE") {
  410. this.moduleManager.debugLogs.stationIssue.push(_arguments);
  411. return;
  412. }
  413. if (this.logRules.hideType.indexOf(type) !== -1) return;
  414. _arguments.splice(0, 1);
  415. const start = `|${this.name.toUpperCase()}|`;
  416. const numberOfSpacesNeeded = 20 - start.length;
  417. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  418. if (this.logRules.blacklistedTerms.some(blacklistedTerm => _arguments.join().indexOf(blacklistedTerm) !== -1))
  419. return;
  420. if (type === "INFO" || type === "SUCCESS") {
  421. _arguments[0] += "\x1b[36m";
  422. _arguments.push("\x1b[0m");
  423. console.log.apply(null, _arguments);
  424. } else if (type === "ERROR") {
  425. _arguments[0] += "\x1b[31m";
  426. _arguments.push("\x1b[0m");
  427. console.error.apply(null, _arguments);
  428. }
  429. }
  430. /**
  431. * Sets up each job with the statistics service (includes mean average for job completion)
  432. */
  433. registerJobs() {
  434. let props = [];
  435. let obj = this;
  436. do {
  437. props = props.concat(Object.getOwnPropertyNames(obj));
  438. // eslint-disable-next-line no-cond-assign
  439. } while ((obj = Object.getPrototypeOf(obj)));
  440. const jobNames = props.sort().filter(prop => typeof this[prop] === "function" && prop === prop.toUpperCase());
  441. jobNames.forEach(jobName => {
  442. this.jobStatistics[jobName] = {
  443. successful: 0,
  444. failed: 0,
  445. total: 0,
  446. averageTiming: new MovingAverageCalculator()
  447. };
  448. });
  449. this.jobNames = jobNames;
  450. }
  451. /**
  452. * Runs a job
  453. *
  454. * @param {string} name - the name of the job e.g. GET_PLAYLIST
  455. * @param {object} payload - any expected payload for the job itself
  456. * @param {object} parentJob - the parent job, if any
  457. * @param {number} priority - custom priority. Optional.
  458. * @param {object} options - custom options e.g. isQuiet. Optional.
  459. * @returns {Promise} - returns a promise
  460. */
  461. runJob(name, payload, parentJob, priority, options) {
  462. /** Allows for any combination of optional parameters (parentJob, priority, options) */
  463. let _options;
  464. let _priority;
  465. let _parentJob;
  466. if (parentJob) {
  467. if (typeof parentJob === "object")
  468. if (!parentJob.name) _options = parentJob;
  469. else _parentJob = parentJob;
  470. else if (typeof parentJob === "number") _priority = parentJob;
  471. }
  472. if (options) {
  473. if (typeof options === "object")
  474. if (options.name) _parentJob = options;
  475. else _options = options;
  476. if (typeof options === "number") _priority = options;
  477. }
  478. if (priority && typeof priority === "object") {
  479. if (!priority.name) _options = priority;
  480. else _parentJob = priority;
  481. } else _priority = priority;
  482. if (!_options) _options = { isQuiet: false };
  483. if (_options && typeof _options.onProgress === "function") {
  484. const onProgress = new EventEmitter();
  485. onProgress.on("progress", _options.onProgress);
  486. _options.onProgress = onProgress;
  487. }
  488. if (!_options.onProgress && parentJob) _options.onProgress = parentJob.onProgress;
  489. const deferredPromise = new DeferredPromise();
  490. const job = new Job(name, payload, deferredPromise, this, _parentJob, { onProgress: _options.onProgress });
  491. this.log("INFO", `Queuing job ${name} (${job.toString()})`);
  492. if (_parentJob) {
  493. _parentJob.addChildJob(job);
  494. if (_parentJob.status === "RUNNING") {
  495. this.log(
  496. "INFO",
  497. `Pausing job ${_parentJob.name} (${_parentJob.toString()}) since a child job has to run first`
  498. );
  499. _parentJob.setStatus("WAITING_ON_CHILD_JOB");
  500. _parentJob.module.jobQueue.pauseRunningJob(_parentJob);
  501. } else {
  502. this.log(
  503. "INFO",
  504. `Not pausing job ${_parentJob.name} (${_parentJob.toString()}) since it's already paused`
  505. );
  506. }
  507. }
  508. job.setStatus("QUEUED");
  509. let calculatedPriority = null;
  510. if (_priority) calculatedPriority = _priority;
  511. else if (this.priorities[name]) calculatedPriority = this.priorities[name];
  512. else if (_parentJob) calculatedPriority = _parentJob.task.priority;
  513. else calculatedPriority = 10;
  514. this.jobQueue.push(job, _options, calculatedPriority);
  515. if (
  516. config.debug &&
  517. config.debug.stationIssue === true &&
  518. config.debug.captureJobs &&
  519. config.debug.captureJobs.indexOf(name) !== -1
  520. ) {
  521. this.moduleManager.debugJobs.all.push({ job, _priority });
  522. }
  523. return deferredPromise.promise;
  524. }
  525. /**
  526. * UNKNOWN
  527. *
  528. * @param {object} moduleManager - UNKNOWN
  529. */
  530. setModuleManager(moduleManager) {
  531. this.moduleManager = moduleManager;
  532. }
  533. /**
  534. * Actually runs the job? UNKNOWN
  535. *
  536. * @param {object} job - object containing details of the job
  537. * @param {string} job.name - the name of the job e.g. GET_PLAYLIST
  538. * @param {string} job.payload - any expected payload for the job itself
  539. * @param {Promise} job.onFinish - deferred promise when the job is complete
  540. * @param {object} options - custom options e.g. isQuiet. Optional.
  541. * @returns {Promise} - returns a promise
  542. */
  543. _runJob(job, options) {
  544. if (!options.isQuiet) this.log("INFO", `Running job ${job.name} (${job.toString()})`);
  545. return new Promise(resolve => {
  546. const startTime = Date.now();
  547. const previousStatus = job.status;
  548. job.setStatus("RUNNING");
  549. this.moduleManager.jobManager.addJob(job);
  550. if (previousStatus === "QUEUED") {
  551. if (!options.isQuiet) this.log("INFO", `Job ${job.name} (${job.toString()}) is queued, so calling it`);
  552. if (this[job.name])
  553. this[job.name]
  554. .apply(job, [job.payload])
  555. .then(response => {
  556. if (!options.isQuiet)
  557. this.log("INFO", `Ran job ${job.name} (${job.toString()}) successfully`);
  558. job.setStatus("FINISHED");
  559. job.setResponse(response);
  560. this.jobStatistics[job.name].successful += 1;
  561. job.setResponseType("RESOLVE");
  562. if (
  563. config.debug &&
  564. config.debug.stationIssue === true &&
  565. config.debug.captureJobs &&
  566. config.debug.captureJobs.indexOf(job.name) !== -1
  567. ) {
  568. this.moduleManager.debugJobs.completed.push({
  569. status: "success",
  570. job,
  571. priority: job.task.priority,
  572. response
  573. });
  574. }
  575. })
  576. .catch(error => {
  577. this.log("INFO", `Running job ${job.name} (${job.toString()}) failed`);
  578. job.setStatus("FINISHED");
  579. job.setResponse(error);
  580. job.setResponseType("REJECT");
  581. this.jobStatistics[job.name].failed += 1;
  582. if (
  583. config.debug &&
  584. config.debug.stationIssue === true &&
  585. config.debug.captureJobs &&
  586. config.debug.captureJobs.indexOf(job.name) !== -1
  587. ) {
  588. this.moduleManager.debugJobs.completed.push({
  589. status: "error",
  590. job,
  591. error
  592. });
  593. }
  594. })
  595. .finally(() => {
  596. const endTime = Date.now();
  597. const executionTime = endTime - startTime;
  598. this.jobStatistics[job.name].total += 1;
  599. this.jobStatistics[job.name].averageTiming.update(executionTime);
  600. if (!job.longJob) this.moduleManager.jobManager.removeJob(job);
  601. job.cleanup();
  602. if (!job.parentJob) {
  603. if (job.responseType === "RESOLVE") {
  604. job.onFinish.resolve(job.response);
  605. job.responseType = "RESOLVED";
  606. } else if (job.responseType === "REJECT") {
  607. job.onFinish.reject(job.response);
  608. job.responseType = "REJECTED";
  609. }
  610. } else if (
  611. job.parentJob &&
  612. job.parentJob.childJobs.find(childJob =>
  613. childJob ? childJob.status !== "FINISHED" : true
  614. ) === undefined
  615. ) {
  616. if (job.parentJob.status !== "WAITING_ON_CHILD_JOB") {
  617. this.log(
  618. "ERROR",
  619. `Job ${
  620. job.parentJob.name
  621. } (${job.parentJob.toString()}) had a child job complete even though it is not waiting on a child job. This should never happen.`
  622. );
  623. } else {
  624. job.parentJob.setStatus("REQUEUED");
  625. job.parentJob.module.jobQueue.resumeRunningJob(job.parentJob);
  626. }
  627. }
  628. resolve();
  629. });
  630. else this.log("ERROR", `Job not found! ${job.name}`);
  631. } else {
  632. this.log(
  633. "INFO",
  634. `Job ${job.name} (${job.toString()}) is re-queued, so resolving/rejecting all child jobs.`
  635. );
  636. job.childJobs.forEach(childJob => {
  637. if (childJob.responseType === "RESOLVE") {
  638. childJob.onFinish.resolve(childJob.response);
  639. childJob.responseType = "RESOLVED";
  640. } else if (childJob.responseType === "REJECT") {
  641. childJob.onFinish.reject(childJob.response);
  642. childJob.responseType = "REJECTED";
  643. }
  644. });
  645. }
  646. });
  647. }
  648. }