JobStatistics.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. export default class JobStatistics {
  2. static primaryInstance = new this();
  3. private stats: Record<
  4. string,
  5. {
  6. successful: number;
  7. failed: number;
  8. total: number;
  9. added: number;
  10. averageTime: number;
  11. }
  12. >;
  13. public constructor() {
  14. this.stats = {};
  15. }
  16. /**
  17. * getStats - Get statistics of job queue
  18. *
  19. * @returns Job queue statistics
  20. */
  21. public getStats() {
  22. return {
  23. ...this.stats,
  24. total: Object.values(this.stats).reduce(
  25. (a, b) => ({
  26. successful: a.successful + b.successful,
  27. failed: a.failed + b.failed,
  28. total: a.total + b.total,
  29. added: a.added + b.added,
  30. averageTime: -1
  31. }),
  32. {
  33. successful: 0,
  34. failed: 0,
  35. total: 0,
  36. added: 0,
  37. averageTime: -1
  38. }
  39. )
  40. };
  41. }
  42. /**
  43. * updateStats - Update job statistics
  44. *
  45. * @param jobName - Job name
  46. * @param type - Stats type
  47. * @param duration - Duration of job, for average time stats
  48. */
  49. public updateStats(
  50. jobName: string,
  51. type: "successful" | "failed" | "total" | "added" | "averageTime",
  52. duration?: number
  53. ) {
  54. if (!this.stats[jobName])
  55. this.stats[jobName] = {
  56. successful: 0,
  57. failed: 0,
  58. total: 0,
  59. added: 0,
  60. averageTime: 0
  61. };
  62. if (type === "averageTime" && duration)
  63. this.stats[jobName].averageTime +=
  64. (duration - this.stats[jobName].averageTime) /
  65. this.stats[jobName].total;
  66. else this.stats[jobName][type] += 1;
  67. }
  68. static getPrimaryInstance(): JobStatistics {
  69. return this.primaryInstance;
  70. }
  71. static setPrimaryInstance(instance: JobStatistics) {
  72. this.primaryInstance = instance;
  73. }
  74. }