File size: 1,174 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
package message

import (
	"sort"

	"github.com/target/goalert/notification"
)

// dedupAlerts will "bundle" identical alert notifications and point them at the oldest pending notification.
func dedupAlerts(msgs []Message, bundleFunc func(parentID string, duplicateIDs []string) error) ([]Message, error) {
	if len(msgs) == 0 {
		return msgs, nil
	}

	toProcess, result := splitPendingByType(msgs, notification.MessageTypeAlert)

	// sort by "created" time
	sort.Slice(toProcess, func(i, j int) bool { return toProcess[i].CreatedAt.Before(toProcess[j].CreatedAt) })

	type msgKey struct {
		notification.DestID
		AlertID int
	}
	alerts := make(map[msgKey]string, len(msgs))
	duplicates := make(map[string][]string)

	for _, msg := range toProcess {
		// check if we have seen this alert before
		key := msgKey{msg.DestID, msg.AlertID}

		if parentID, ok := alerts[key]; ok {
			duplicates[parentID] = append(duplicates[parentID], msg.ID)
			continue
		}

		alerts[key] = msg.ID
		result = append(result, msg)
	}

	for parentID, duplicateIDs := range duplicates {
		err := bundleFunc(parentID, duplicateIDs)
		if err != nil {
			return nil, err
		}
	}

	return result, nil
}