core.js 17 KB

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