core.js 17 KB

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