core.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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.jobNames = [];
  289. this.logRules = config.get("customLoggingPerModule")[name]
  290. ? config.get("customLoggingPerModule")[name]
  291. : config.get("defaultLogging");
  292. this.registerJobs();
  293. }
  294. /**
  295. * Sets the status of a module
  296. *
  297. * @param {string} status - the new status of a module
  298. */
  299. setStatus(status) {
  300. this.status = status;
  301. this.log("INFO", `Status changed to: ${status}`);
  302. if (this.status === "READY") this.jobQueue.resume();
  303. else if (this.status === "FAIL" || this.status === "LOCKDOWN") this.jobQueue.pause();
  304. }
  305. /**
  306. * Returns the status of a module
  307. *
  308. * @returns {string} - the status of a module
  309. */
  310. getStatus() {
  311. return this.status;
  312. }
  313. /**
  314. * Changes the current stage of a module
  315. *
  316. * @param {string} stage - the new stage of a module
  317. */
  318. setStage(stage) {
  319. this.stage = stage;
  320. }
  321. /**
  322. * Returns the current stage of a module
  323. *
  324. * @returns {string} - the current stage of a module
  325. */
  326. getStage() {
  327. return this.stage;
  328. }
  329. /**
  330. * Initialises a module and handles initialise successes and failures
  331. */
  332. _initialize() {
  333. this.setStatus("INITIALIZING");
  334. this.initialize()
  335. .then(() => {
  336. this.setStatus("READY");
  337. this.moduleManager.onInitialize(this);
  338. })
  339. .catch(err => {
  340. console.error(err);
  341. this.setStatus("FAILED");
  342. this.moduleManager.onFail(this);
  343. });
  344. }
  345. /**
  346. * Creates a new log message
  347. *
  348. * @param {...any} args - anything to be included in the log message, the first argument is the type of log
  349. */
  350. log(...args) {
  351. const _arguments = Array.from(args);
  352. const type = _arguments[0];
  353. if (config.debug && config.debug.stationIssue === true && type === "STATION_ISSUE") {
  354. this.moduleManager.debugLogs.stationIssue.push(_arguments);
  355. return;
  356. }
  357. if (this.logRules.hideType.indexOf(type) !== -1) return;
  358. _arguments.splice(0, 1);
  359. const start = `|${this.name.toUpperCase()}|`;
  360. const numberOfSpacesNeeded = 20 - start.length;
  361. _arguments.unshift(`${start}${Array(numberOfSpacesNeeded).join(" ")}`);
  362. if (this.logRules.blacklistedTerms.some(blacklistedTerm => _arguments.join().indexOf(blacklistedTerm) !== -1))
  363. return;
  364. if (type === "INFO" || type === "SUCCESS") {
  365. _arguments[0] += "\x1b[36m";
  366. _arguments.push("\x1b[0m");
  367. console.log.apply(null, _arguments);
  368. } else if (type === "ERROR") {
  369. _arguments[0] += "\x1b[31m";
  370. _arguments.push("\x1b[0m");
  371. console.error.apply(null, _arguments);
  372. }
  373. }
  374. /**
  375. * Sets up each job with the statistics service (includes mean average for job completion)
  376. */
  377. registerJobs() {
  378. let props = [];
  379. let obj = this;
  380. do {
  381. props = props.concat(Object.getOwnPropertyNames(obj));
  382. // eslint-disable-next-line no-cond-assign
  383. } while ((obj = Object.getPrototypeOf(obj)));
  384. const jobNames = props.sort().filter(prop => typeof this[prop] === "function" && prop === prop.toUpperCase());
  385. jobNames.forEach(jobName => {
  386. this.jobStatistics[jobName] = {
  387. successful: 0,
  388. failed: 0,
  389. total: 0,
  390. averageTiming: new MovingAverageCalculator()
  391. };
  392. });
  393. this.jobNames = jobNames;
  394. }
  395. /**
  396. * Runs a job
  397. *
  398. * @param {string} name - the name of the job e.g. GET_PLAYLIST
  399. * @param {object} payload - any expected payload for the job itself
  400. * @param {object} parentJob - the parent job, if any
  401. * @param {number} priority - custom priority. Optional.
  402. * @param {object} options - custom options e.g. isQuiet. Optional.
  403. * @returns {Promise} - returns a promise
  404. */
  405. runJob(name, payload, parentJob, priority, options) {
  406. /** Allows for any combination of optional parameters (parentJob, priority, options) */
  407. let _options;
  408. let _priority;
  409. let _parentJob;
  410. if (parentJob) {
  411. if (typeof parentJob === "object")
  412. if (!parentJob.name) _options = parentJob;
  413. else _parentJob = parentJob;
  414. else if (typeof parentJob === "number") _priority = parentJob;
  415. }
  416. if (options) {
  417. if (typeof options === "object")
  418. if (options.name) _parentJob = options;
  419. else _options = options;
  420. if (typeof options === "number") _priority = options;
  421. }
  422. if (priority && typeof priority === "object") {
  423. if (!priority.name) _options = priority;
  424. else _parentJob = priority;
  425. } else _priority = priority;
  426. if (!_options) _options = { isQuiet: false };
  427. const deferredPromise = new DeferredPromise();
  428. const job = new Job(name, payload, deferredPromise, this, _parentJob);
  429. this.log("INFO", `Queuing job ${name} (${job.toString()})`);
  430. if (_parentJob) {
  431. _parentJob.addChildJob(job);
  432. if (_parentJob.status === "RUNNING") {
  433. this.log(
  434. "INFO",
  435. `Pausing job ${_parentJob.name} (${_parentJob.toString()}) since a child job has to run first`
  436. );
  437. _parentJob.setStatus("WAITING_ON_CHILD_JOB");
  438. _parentJob.module.jobQueue.pauseRunningJob(_parentJob);
  439. } else {
  440. this.log(
  441. "INFO",
  442. `Not pausing job ${_parentJob.name} (${_parentJob.toString()}) since it's already paused`
  443. );
  444. }
  445. }
  446. job.setStatus("QUEUED");
  447. let calculatedPriority = null;
  448. if (_priority) calculatedPriority = _priority;
  449. else if (this.priorities[name]) calculatedPriority = this.priorities[name];
  450. else if (_parentJob) calculatedPriority = _parentJob.task.priority;
  451. else calculatedPriority = 10;
  452. this.jobQueue.push(job, _options, calculatedPriority);
  453. if (
  454. config.debug &&
  455. config.debug.stationIssue === true &&
  456. config.debug.captureJobs &&
  457. config.debug.captureJobs.indexOf(name) !== -1
  458. ) {
  459. this.moduleManager.debugJobs.all.push({ job, _priority });
  460. }
  461. return deferredPromise.promise;
  462. }
  463. /**
  464. * UNKNOWN
  465. *
  466. * @param {object} moduleManager - UNKNOWN
  467. */
  468. setModuleManager(moduleManager) {
  469. this.moduleManager = moduleManager;
  470. }
  471. /**
  472. * Actually runs the job? UNKNOWN
  473. *
  474. * @param {object} job - object containing details of the job
  475. * @param {string} job.name - the name of the job e.g. GET_PLAYLIST
  476. * @param {string} job.payload - any expected payload for the job itself
  477. * @param {Promise} job.onFinish - deferred promise when the job is complete
  478. * @param {object} options - custom options e.g. isQuiet. Optional.
  479. * @returns {Promise} - returns a promise
  480. */
  481. _runJob(job, options) {
  482. if (!options.isQuiet) this.log("INFO", `Running job ${job.name} (${job.toString()})`);
  483. return new Promise(resolve => {
  484. const startTime = Date.now();
  485. const previousStatus = job.status;
  486. job.setStatus("RUNNING");
  487. this.moduleManager.jobManager.addJob(job);
  488. if (previousStatus === "QUEUED") {
  489. if (!options.isQuiet) this.log("INFO", `Job ${job.name} (${job.toString()}) is queued, so calling it`);
  490. // TODO check if job exists
  491. this[job.name]
  492. .apply(job, [job.payload])
  493. .then(response => {
  494. if (!options.isQuiet) this.log("INFO", `Ran job ${job.name} (${job.toString()}) successfully`);
  495. job.setStatus("FINISHED");
  496. job.setResponse(response);
  497. this.jobStatistics[job.name].successful += 1;
  498. job.setResponseType("RESOLVE");
  499. if (
  500. config.debug &&
  501. config.debug.stationIssue === true &&
  502. config.debug.captureJobs &&
  503. config.debug.captureJobs.indexOf(job.name) !== -1
  504. ) {
  505. this.moduleManager.debugJobs.completed.push({
  506. status: "success",
  507. job,
  508. priority: job.task.priority,
  509. response
  510. });
  511. }
  512. })
  513. .catch(error => {
  514. this.log("INFO", `Running job ${job.name} (${job.toString()}) failed`);
  515. job.setStatus("FINISHED");
  516. job.setResponse(error);
  517. job.setResponseType("REJECT");
  518. this.jobStatistics[job.name].failed += 1;
  519. if (
  520. config.debug &&
  521. config.debug.stationIssue === true &&
  522. config.debug.captureJobs &&
  523. config.debug.captureJobs.indexOf(job.name) !== -1
  524. ) {
  525. this.moduleManager.debugJobs.completed.push({
  526. status: "error",
  527. job,
  528. error
  529. });
  530. }
  531. })
  532. .finally(() => {
  533. const endTime = Date.now();
  534. const executionTime = endTime - startTime;
  535. this.jobStatistics[job.name].total += 1;
  536. this.jobStatistics[job.name].averageTiming.update(executionTime);
  537. this.moduleManager.jobManager.removeJob(job);
  538. job.cleanup();
  539. if (!job.parentJob) {
  540. if (job.responseType === "RESOLVE") {
  541. job.onFinish.resolve(job.response);
  542. job.responseType = "RESOLVED";
  543. } else if (job.responseType === "REJECT") {
  544. job.onFinish.reject(job.response);
  545. job.responseType = "REJECTED";
  546. }
  547. } else if (
  548. job.parentJob &&
  549. job.parentJob.childJobs.find(childJob =>
  550. childJob ? childJob.status !== "FINISHED" : true
  551. ) === undefined
  552. ) {
  553. if (job.parentJob.status !== "WAITING_ON_CHILD_JOB") {
  554. this.log(
  555. "ERROR",
  556. `Job ${
  557. job.parentJob.name
  558. } (${job.parentJob.toString()}) had a child job complete even though it is not waiting on a child job. This should never happen.`
  559. );
  560. } else {
  561. job.parentJob.setStatus("REQUEUED");
  562. job.parentJob.module.jobQueue.resumeRunningJob(job.parentJob);
  563. }
  564. }
  565. resolve();
  566. });
  567. } else {
  568. this.log(
  569. "INFO",
  570. `Job ${job.name} (${job.toString()}) is re-queued, so resolving/rejecting all child jobs.`
  571. );
  572. job.childJobs.forEach(childJob => {
  573. if (childJob.responseType === "RESOLVE") {
  574. childJob.onFinish.resolve(childJob.response);
  575. childJob.responseType = "RESOLVED";
  576. } else if (childJob.responseType === "REJECT") {
  577. childJob.onFinish.reject(childJob.response);
  578. childJob.responseType = "REJECTED";
  579. }
  580. });
  581. }
  582. });
  583. }
  584. }