core.js 17 KB

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