core.js 13 KB

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