Skip to content

Commit

Permalink
perf: less recursion for isUnderMaintenance using db query
Browse files Browse the repository at this point in the history
  • Loading branch information
julian-piehl committed Oct 16, 2024
1 parent 16c04f6 commit c9e5dff
Showing 1 changed file with 25 additions and 7 deletions.
32 changes: 25 additions & 7 deletions server/model/monitor.js
Original file line number Diff line number Diff line change
Expand Up @@ -1469,10 +1469,12 @@ class Monitor extends BeanModel {
* @returns {Promise<boolean>} Is the monitor under maintenance
*/
static async isUnderMaintenance(monitorID) {
const ancestorIDs = await Monitor.getAllAncestorIDs(monitorID);
const allIDs = [ monitorID, ...ancestorIDs ];
const maintenanceIDList = await R.getCol(`
SELECT maintenance_id FROM monitor_maintenance
WHERE monitor_id = ?
`, [ monitorID ]);
WHERE monitor_id IN (${allIDs.map((_) => "?").join(",")})
`, allIDs);

for (const maintenanceID of maintenanceIDList) {
const maintenance = await UptimeKumaServer.getInstance().getMaintenance(maintenanceID);
Expand All @@ -1481,11 +1483,6 @@ class Monitor extends BeanModel {
}
}

const parent = await Monitor.getParent(monitorID);
if (parent != null) {
return await Monitor.isUnderMaintenance(parent.id);
}

return false;
}

Expand Down Expand Up @@ -1683,6 +1680,27 @@ class Monitor extends BeanModel {
return path;
}

/**
* Gets recursive all ancestor ids
* @param {number} monitorID ID of the monitor to get
* @returns {Promise<number[]>} IDs of all ancestors
*/
static async getAllAncestorIDs(monitorID) {
return await R.getCol(`
WITH RECURSIVE Ancestors AS (
SELECT parent FROM monitor
WHERE id = ?
UNION ALL
SELECT m.parent FROM monitor m
JOIN Ancestors a ON m.id = a.parent
)
SELECT parent AS ancestor_id FROM Ancestors
WHERE parent IS NOT NULL;
`, [
monitorID,
]);
}

/**
* Gets recursive all children ids
* @param {number} monitorID ID of the monitor to get
Expand Down

0 comments on commit c9e5dff

Please sign in to comment.