core.js 19 KB

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