notifications.js 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  1. 'use strict';
  2. const coreClass = require("../core");
  3. const crypto = require('crypto');
  4. const redis = require('redis');
  5. const config = require('config');
  6. const subscriptions = [];
  7. module.exports = class extends coreClass {
  8. initialize() {
  9. return new Promise((resolve, reject) => {
  10. this.setStage(1);
  11. const url = this.url = config.get("redis").url;
  12. const password = this.password = config.get("redis").password;
  13. this.pub = redis.createClient({
  14. url,
  15. password,
  16. retry_strategy: (options) => {
  17. if (this.state === "LOCKDOWN") return;
  18. if (this.state !== "RECONNECTING") this.setState("RECONNECTING");
  19. this.logger.info("NOTIFICATIONS_MODULE", `Attempting to reconnect pub.`);
  20. if (options.attempt >= 10) {
  21. this.logger.error("NOTIFICATIONS_MODULE", `Stopped trying to reconnect pub.`);
  22. this.failed = true;
  23. this._lockdown();
  24. return undefined;
  25. }
  26. return 3000;
  27. }
  28. });
  29. this.sub = redis.createClient({
  30. url,
  31. password,
  32. retry_strategy: (options) => {
  33. if (this.state === "LOCKDOWN") return;
  34. if (this.state !== "RECONNECTING") this.setState("RECONNECTING");
  35. this.logger.info("NOTIFICATIONS_MODULE", `Attempting to reconnect sub.`);
  36. if (options.attempt >= 10) {
  37. this.logger.error("NOTIFICATIONS_MODULE", `Stopped trying to reconnect sub.`);
  38. this.failed = true;
  39. this._lockdown();
  40. return undefined;
  41. }
  42. return 3000;
  43. }
  44. });
  45. this.sub.on('error', (err) => {
  46. if (this.state === "INITIALIZING") reject(err);
  47. if(this.state === "LOCKDOWN") return;
  48. this.logger.error("NOTIFICATIONS_MODULE", `Sub error ${err.message}.`);
  49. });
  50. this.pub.on('error', (err) => {
  51. if (this.state === "INITIALIZING") reject(err);
  52. if(this.state === "LOCKDOWN") return;
  53. this.logger.error("NOTIFICATIONS_MODULE", `Pub error ${err.message}.`);
  54. });
  55. this.sub.on("connect", () => {
  56. this.logger.info("NOTIFICATIONS_MODULE", "Sub connected succesfully.");
  57. if (this.state === "INITIALIZING") resolve();
  58. else if (this.state === "LOCKDOWN" || this.state === "RECONNECTING") this.setState("INITIALIZED");
  59. });
  60. this.pub.on("connect", () => {
  61. this.logger.info("NOTIFICATIONS_MODULE", "Pub connected succesfully.");
  62. if (this.state === "INITIALIZING") resolve();
  63. else if (this.state === "LOCKDOWN" || this.state === "RECONNECTING") this.setState("INITIALIZED");
  64. });
  65. this.sub.on('pmessage', (pattern, channel, expiredKey) => {
  66. this.logger.stationIssue(`PMESSAGE1 - Pattern: ${pattern}; Channel: ${channel}; ExpiredKey: ${expiredKey}`);
  67. subscriptions.forEach((sub) => {
  68. this.logger.stationIssue(`PMESSAGE2 - Sub name: ${sub.name}; Calls cb: ${!(sub.name !== expiredKey)}`);
  69. if (sub.name !== expiredKey) return;
  70. sub.cb();
  71. });
  72. });
  73. this.sub.psubscribe('__keyevent@0__:expired');
  74. });
  75. }
  76. /**
  77. * Schedules a notification to be dispatched in a specific amount of milliseconds,
  78. * notifications are unique by name, and the first one is always kept, as in
  79. * attempting to schedule a notification that already exists won't do anything
  80. *
  81. * @param {String} name - the name of the notification we want to schedule
  82. * @param {Integer} time - how long in milliseconds until the notification should be fired
  83. * @param {Function} cb - gets called when the notification has been scheduled
  84. */
  85. async schedule(name, time, cb, station) {
  86. try { await this._validateHook(); } catch { return; }
  87. if (!cb) cb = ()=>{};
  88. time = Math.round(time);
  89. this.logger.stationIssue(`SCHEDULE - Time: ${time}; Name: ${name}; Key: ${crypto.createHash('md5').update(`_notification:${name}_`).digest('hex')}; StationId: ${station._id}; StationName: ${station.name}`);
  90. this.pub.set(crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), '', 'PX', time, 'NX', cb);
  91. }
  92. /**
  93. * Subscribes a callback function to be called when a notification gets called
  94. *
  95. * @param {String} name - the name of the notification we want to subscribe to
  96. * @param {Function} cb - gets called when the subscribed notification gets called
  97. * @param {Boolean} unique - only subscribe if another subscription with the same name doesn't already exist
  98. * @return {Object} - the subscription object
  99. */
  100. async subscribe(name, cb, unique = false, station) {
  101. try { await this._validateHook(); } catch { return; }
  102. this.logger.stationIssue(`SUBSCRIBE - Name: ${name}; Key: ${crypto.createHash('md5').update(`_notification:${name}_`).digest('hex')}, StationId: ${station._id}; StationName: ${station.name}; Unique: ${unique}; SubscriptionExists: ${!!subscriptions.find((subscription) => subscription.originalName == name)};`);
  103. if (unique && !!subscriptions.find((subscription) => subscription.originalName == name)) return;
  104. let subscription = { originalName: name, name: crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'), cb };
  105. subscriptions.push(subscription);
  106. return subscription;
  107. }
  108. /**
  109. * Remove a notification subscription
  110. *
  111. * @param {Object} subscription - the subscription object returned by {@link subscribe}
  112. */
  113. async remove(subscription) {
  114. try { await this._validateHook(); } catch { return; }
  115. let index = subscriptions.indexOf(subscription);
  116. if (index) subscriptions.splice(index, 1);
  117. }
  118. async unschedule(name) {
  119. try { await this._validateHook(); } catch { return; }
  120. this.logger.stationIssue(`UNSCHEDULE - Name: ${name}; Key: ${crypto.createHash('md5').update(`_notification:${name}_`).digest('hex')}`);
  121. this.pub.del(crypto.createHash('md5').update(`_notification:${name}_`).digest('hex'));
  122. }
  123. }