core.js 16 KB

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