Skip to content

Commit

Permalink
fixed logic to get all alerts (#965)
Browse files Browse the repository at this point in the history
Signed-off-by: Amardeepsingh Siglani <amardeep7194@gmail.com>
  • Loading branch information
amsiglan authored Mar 22, 2024
1 parent 4faedfe commit 03d3b14
Showing 1 changed file with 31 additions and 39 deletions.
70 changes: 31 additions & 39 deletions public/store/AlertsStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
import { NotificationsStart } from 'opensearch-dashboards/public';
import { AlertsService } from '../services';
import { errorNotificationToast } from '../utils/helpers';
import { GetAlertsResponse, ServerResponse } from '../../types';

export class AlertsStore {
constructor(
Expand All @@ -16,49 +15,42 @@ export class AlertsStore {

public async getAlertsByDetector(detectorId: string, detectorName: string) {
let allAlerts: any[] = [];
const alertsSize = 10000;

const firstGetAlertsRes = await this.service.getAlerts({
detector_id: detectorId,
startIndex: 0,
size: alertsSize,
});

if (firstGetAlertsRes.ok) {
allAlerts = [...firstGetAlertsRes.response.alerts];
let remainingAlerts = firstGetAlertsRes.response.total_alerts - alertsSize;
let startIndex = alertsSize + 1;
const getAlertsPromises: Promise<ServerResponse<GetAlertsResponse>>[] = [];
const maxAlertsReturned = 10000;
let startIndex = 0;
let alertsCount = 0;

do {
const getAlertsRes = await this.service.getAlerts({
detector_id: detectorId,
startIndex,
size: maxAlertsReturned,
});

while (remainingAlerts > 0) {
getAlertsPromises.push(
this.service.getAlerts({ detector_id: detectorId, startIndex, size: alertsSize })
);
remainingAlerts -= alertsSize;
startIndex += alertsSize;
if (getAlertsRes.ok) {
allAlerts = allAlerts.concat(getAlertsRes.response.alerts);
alertsCount = getAlertsRes.response.alerts.length;
} else {
alertsCount = 0;
errorNotificationToast(this.notifications, 'retrieve', 'alerts', getAlertsRes.error);
}

const alertsPromisesRes = await Promise.allSettled(getAlertsPromises);
startIndex += alertsCount;
} while (
// If we get 10,000 alerts as part of the previous call then there might be more alerts to fetch,
// hence we make another call until the number of alerts is less then 10,000
alertsCount === maxAlertsReturned
);

alertsPromisesRes.forEach((response) => {
if (response.status === 'fulfilled' && response.value.ok) {
allAlerts = allAlerts.concat(response.value.response.alerts);
}
});

allAlerts = allAlerts.map((alert) => {
if (!alert.detector_id) {
alert.detector_id = detectorId;
}
allAlerts = allAlerts.map((alert) => {
if (!alert.detector_id) {
alert.detector_id = detectorId;
}

return {
...alert,
detectorName: detectorName,
};
});
} else {
errorNotificationToast(this.notifications, 'retrieve', 'alerts', firstGetAlertsRes.error);
}
return {
...alert,
detectorName: detectorName,
};
});

return allAlerts;
}
Expand Down

0 comments on commit 03d3b14

Please sign in to comment.