All files / src alerter.ts

100% Statements 15/15
66.66% Branches 8/12
100% Functions 2/2
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51  5x   5x     4x 4x       4x 1x 1x     3x   3x                         3x 3x               2x 1x     1x     2x      
import { SeraphConfig } from './config';
import fetch from 'node-fetch';
 
export class AlerterClient {
  private alertManagerUrl: string;
 
  constructor(private config: SeraphConfig) {
    this.alertManagerUrl = this.config.alertManager?.url || '';
  }
 
  public async sendAlert(context: Record<string, any>) {
    if (!this.alertManagerUrl) {
      console.error('[AlerterClient] Alertmanager URL is not configured. Cannot send alert.');
      return;
    }
 
    console.log('[AlerterClient] Sending alert with context:', JSON.stringify(context, null, 2));
 
    const alert = {
      labels: {
        alertname: 'SeraphAnomalyDetected',
        source: context.source || 'unknown',
        type: context.type || 'unknown',
      },
      annotations: {
        summary: `Anomaly detected in ${context.source}`,
        description: context.details || 'No details provided.',
        log: context.log || 'No log provided.',
      },
    };
 
    try {
      const response = await (fetch as any)(this.alertManagerUrl, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify([alert]),
      });
 
      if (!response.ok) {
        throw new Error(`Alertmanager returned an error: ${response.statusText} - ${await response.text()}`);
      }
 
      console.log('[AlerterClient] Successfully sent alert to Alertmanager.');
 
    } catch (error: any) {
      console.error('[AlerterClient] Failed to send alert:', error.message);
    }
  }
}