core.js 14 KB

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