From b4fde61884963c7ae82947d61c109cf48fd67571 Mon Sep 17 00:00:00 2001 From: Nikolai Ovtsinnikov Date: Fri, 15 Dec 2023 12:05:17 +0200 Subject: [PATCH] optimize CPU usage --- lib/imap-notifier.js | 45 ++++++++++++++++++++++++++++++++++---------- 1 file changed, 35 insertions(+), 10 deletions(-) diff --git a/lib/imap-notifier.js b/lib/imap-notifier.js index 1e7dd09c..dfd4397f 100644 --- a/lib/imap-notifier.js +++ b/lib/imap-notifier.js @@ -78,17 +78,42 @@ class ImapNotifier extends EventEmitter { this.subscriber.on('message', (channel, message) => { if (channel === 'wd_events') { let data; - try { - data = JSON.parse(message); - } catch (E) { - return; + // if e present at beginning, check if p also is present + // if no p -> no json parse + // if p -> json parse ONLY p + // if e not in beginning but p is -> json parse whole + + if (message[2] === 'e') { + for (let i = 6; i < 6 + 24; i++) { + if (!/[0-9ABCDEF]/i.test(message[i])) { + // check for hex char + return; // incorrect e, e HAS to be hex + } + } + + data = { e: message.slice(6, 6 + 24) }; + + if (message[33] === 'p') { + // parse next JSON only if the payload is actually there + data.p = JSON.parse('{' + message.slice(32, message.length - 1) + '}').p; + } + } else { + try { + data = JSON.parse(message); + } catch (E) { + return; + } } - if (data.e && !data.p) { - // events without payload are scheduled, these are notifications about changes in journal - scheduleDataEvent(data.e); - } else if (data.e) { - // events with payload are triggered immediatelly, these are actions for doing something - this._listeners.emit(data.e, data.p); + + if (this._listeners._events[data.e] && this._listeners._events[data.e].length > 0) { + // do not schedule or fire/emit empty events + if (data.e && !data.p) { + // events without payload are scheduled, these are notifications about changes in journal + scheduleDataEvent(data.e); + } else if (data.e) { + // events with payload are triggered immediatelly, these are actions for doing something + this._listeners.emit(data.e, data.p); + } } } });