forked from pivotal-cf/cred-alert
-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.go
91 lines (69 loc) · 2 KB
/
router.go
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package notifications
import (
"context"
"cloud.google.com/go/trace"
"code.cloudfoundry.org/lager"
)
//go:generate counterfeiter . Router
type Router interface {
Deliver(ctx context.Context, logger lager.Logger, batch []Notification) error
}
type router struct {
notifier Notifier
addressBook AddressBook
whitelist Whitelist
}
func NewRouter(notifier Notifier, addressBook AddressBook, whitelist Whitelist) Router {
return &router{
notifier: notifier,
addressBook: addressBook,
whitelist: whitelist,
}
}
func (r *router) Deliver(ctx context.Context, logger lager.Logger, batch []Notification) error {
logger = logger.Session("deliver")
span := trace.FromContext(ctx).NewChild("notify")
defer span.Finish()
envelopes := r.filterAndGroupByDestination(ctx, logger, batch)
logger.Debug("sending", lager.Data{
"envelope-count": len(envelopes),
"notification-count": len(batch),
})
for _, envelope := range envelopes {
err := r.notifier.Send(ctx, logger, *envelope)
if err != nil {
return err
}
}
logger.Debug("sent")
return nil
}
func (r *router) filterAndGroupByDestination(ctx context.Context, logger lager.Logger, batch []Notification) []*Envelope {
bag := mailbag{}
for _, notification := range batch {
if r.whitelist.ShouldSkipNotification(notification.Private, notification.Repository) {
continue
}
addresses := r.addressBook.AddressForRepo(ctx, logger, notification.Private, notification.Owner, notification.Repository)
for _, address := range addresses {
bag.envelopeToAddress(notification, address)
}
}
return bag.Envelopes
}
type mailbag struct {
Envelopes []*Envelope
}
func (m *mailbag) envelopeToAddress(notification Notification, address Address) {
for _, envelope := range m.Envelopes {
if envelope.Address == address {
envelope.Contents = append(envelope.Contents, notification)
return
}
}
envelope := &Envelope{
Address: address,
Contents: []Notification{notification},
}
m.Envelopes = append(m.Envelopes, envelope)
}