diff --git a/server/model/monitor.js b/server/model/monitor.js index bd0597854..6c6ccbcc2 100644 --- a/server/model/monitor.js +++ b/server/model/monitor.js @@ -15,6 +15,7 @@ const { UptimeKumaServer } = require("../uptime-kuma-server"); const { CacheableDnsHttpAgent } = require("../cacheable-dns-http-agent"); const { DockerHost } = require("../docker"); const Maintenance = require("./maintenance"); +const { UptimeCacheList } = require("../uptime-cache-list"); /** * status: @@ -714,6 +715,7 @@ class Monitor extends BeanModel { } log.debug("monitor", `[${this.name}] Send to socket`); + UptimeCacheList.clearCache(this.id); io.to(this.user_id).emit("heartbeat", bean.toJSON()); Monitor.sendStats(io, this.id, this.user_id); @@ -898,7 +900,15 @@ class Monitor extends BeanModel { * @param {number} duration Hours * @param {number} monitorID ID of monitor to calculate */ - static async calcUptime(duration, monitorID) { + static async calcUptime(duration, monitorID, forceNoCache = false) { + + if (!forceNoCache) { + let cachedUptime = UptimeCacheList.getUptime(monitorID, duration); + if (cachedUptime != null) { + return cachedUptime; + } + } + const timeLogger = new TimeLogger(); const startTime = R.isoDateTime(dayjs.utc().subtract(duration, "hour")); @@ -957,6 +967,9 @@ class Monitor extends BeanModel { } } + // Cache + UptimeCacheList.addUptime(monitorID, duration, uptime); + return uptime; } diff --git a/server/uptime-cache-list.js b/server/uptime-cache-list.js new file mode 100644 index 000000000..1347968fa --- /dev/null +++ b/server/uptime-cache-list.js @@ -0,0 +1,39 @@ +const { log } = require("../src/util"); +class UptimeCacheList { + /** + * list[monitorID][duration] + */ + static list = {}; + + /** + * + * @param monitorID + * @param duration + * @return number + */ + static getUptime(monitorID, duration) { + if (UptimeCacheList.list[monitorID] && UptimeCacheList.list[monitorID][duration]) { + log.debug("UptimeCacheList", "getUptime: " + monitorID + " " + duration); + return UptimeCacheList.list[monitorID][duration]; + } else { + return null; + } + } + + static addUptime(monitorID, duration, uptime) { + log.debug("UptimeCacheList", "addUptime: " + monitorID + " " + duration); + if (!UptimeCacheList.list[monitorID]) { + UptimeCacheList.list[monitorID] = {}; + } + UptimeCacheList.list[monitorID][duration] = uptime; + } + + static clearCache(monitorID) { + log.debug("UptimeCacheList", "clearCache: " + monitorID); + delete UptimeCacheList.list[monitorID]; + } +} + +module.exports = { + UptimeCacheList, +};