You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.8 KiB

import { runPredict } from './analytics_controller';
import { getLabeledSegments } from './segments_controller';
6 years ago
import { AnalyticUnitId } from '../models/analytic_unit';
import { sendNotification } from '../services/notification_service';
import { getJsonDataSync, writeJsonDataSync } from '../services/json_service';
6 years ago
import { ANALYTIC_UNITS_PATH } from '../config';
import * as path from 'path';
import * as fs from 'fs';
6 years ago
const ALERT_TIMEOUT = 60000; // ms
6 years ago
const ALERTS_DB_PATH = path.join(ANALYTIC_UNITS_PATH, `alerts_anomalies.json`);
6 years ago
export function getAlertsAnomalies(): AnalyticUnitId[] {
if(!fs.existsSync(ALERTS_DB_PATH)) {
saveAlertsAnomalies([]);
}
return getJsonDataSync(ALERTS_DB_PATH);
6 years ago
}
6 years ago
export function saveAlertsAnomalies(units: AnalyticUnitId[]) {
return writeJsonDataSync(ALERTS_DB_PATH, units);
6 years ago
}
6 years ago
function processAlerts(id: AnalyticUnitId) {
let segments = getLabeledSegments(id);
6 years ago
const currentTime = new Date().getTime();
6 years ago
const activeAlert = activeAlerts.has(id);
6 years ago
let newActiveAlert = false;
if(segments.length > 0) {
let lastSegment = segments[segments.length - 1];
6 years ago
if(lastSegment.finish >= currentTime - ALERT_TIMEOUT) {
6 years ago
newActiveAlert = true;
}
}
if(!activeAlert && newActiveAlert) {
6 years ago
activeAlerts.add(id);
sendNotification(id, true);
6 years ago
} else if(activeAlert && !newActiveAlert) {
6 years ago
activeAlerts.delete(id);
sendNotification(id, false);
6 years ago
}
}
async function alertsTick() {
let alertsAnomalies = getAlertsAnomalies();
for (let predictorId of alertsAnomalies) {
6 years ago
try {
await runPredict(predictorId);
processAlerts(predictorId);
6 years ago
} catch (e) {
console.error(e);
}
}
setTimeout(alertsTick, 5000);
}
6 years ago
6 years ago
const activeAlerts = new Set<string>();
setTimeout(alertsTick, 5000);