core.js 19 KB

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