Skip to content

Commit

Permalink
chore: implement alerting
Browse files Browse the repository at this point in the history
  • Loading branch information
YogiPristiawan committed May 27, 2024
1 parent e85286b commit 2ad74bf
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 3 deletions.
17 changes: 16 additions & 1 deletion backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,16 @@ func main() {
log.Warn().Msg("API_KEY is not set")
}

telegramChatID, ok := os.LookupEnv("TELEGRAM_CHAT_ID")
if !ok {
log.Warn().Msg("TELEGRAM_CHAT_ID is not set")
}

telegramUrl, ok := os.LookupEnv("TELEGRAM_URL is not set")
if !ok {
log.Warn().Msg("TELEGRAM_URL is not set")
}

if os.Getenv("ENV") == "" {
err := os.Setenv("ENV", "development")
if err != nil {
Expand Down Expand Up @@ -100,7 +110,12 @@ func main() {
log.Fatal().Err(err).Msg("failed to migrate database")
}

processor := &Processor{}
processor := &Processor{
telegramAlertProvider: NewTelegramAlertProvider(TelegramProviderConfig{
Url: telegramUrl,
ChatID: telegramChatID,
}),
}

// Create a new worker
for _, monitor := range config.Monitors {
Expand Down
44 changes: 42 additions & 2 deletions backend/monitor_processor.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import (
type Processor struct {
historicalWriter *MonitorHistoricalWriter
historicalReader *MonitorHistoricalReader

telegramAlertProvider Alerter
discordAlertProvider Alerter
}

func (m *Processor) ProcessResponse(response Response) {
Expand All @@ -35,5 +38,42 @@ func (m *Processor) ProcessResponse(response Response) {
log.Error().Err(err).Msg("failed to write historical data")
}

// TODO: If the current status is different from the last status, send an alert notification
}
go func() {
if m.telegramAlertProvider == nil && m.discordAlertProvider == nil {
log.Warn().Msg("no alert providers are set")
return
}

alertMessage := AlertMessage{
Success: response.Success,
MonitorID: uniqueId,
MonitorName: response.Monitor.Name,
StatusCode: response.StatusCode,
Timestamp: response.Timestamp,
Latency: response.RequestDuration,
}

lastRawHistorical, err := m.historicalReader.ReadRawLatest(context.Background(), uniqueId)
if err != nil {
log.Error().Err(err).Msg("failed to get raw latest historical data")
return
}

if lastRawHistorical.Status != status {
switch response.Monitor.AlertProvider {
case AlertProviderTypeTelegram, AlertProviderTypeUnspecified:
if m.telegramAlertProvider == nil {
log.Warn().Msg("telegram alert provider is not set")
return
}

err := m.telegramAlertProvider.Send(context.Background(), alertMessage)
if err != nil {
log.Error().Err(err).Msg("failed to send alert")
}
case AlertProviderTypeDiscord:
panic("TODO: Implement me!")
}
}
}()
}

0 comments on commit 2ad74bf

Please sign in to comment.