Skip to content

Commit

Permalink
feat(receiver): add new slack_channel receiver type (#14)
Browse files Browse the repository at this point in the history
* feat(receiver): add new  receiver type

* fix: test

* feat: update proto and add some fixes

* refactor: receiver plugin
  • Loading branch information
mabdh authored Aug 1, 2023
1 parent 10a0f6a commit 107c283
Show file tree
Hide file tree
Showing 32 changed files with 1,949 additions and 1,001 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ NAME="github.com/goto/siren"
LAST_COMMIT := $(shell git rev-parse --short HEAD)
LAST_TAG := "$(shell git rev-list --tags --max-count=1)"
APP_VERSION := "$(shell git describe --tags ${LAST_TAG})-next"
PROTON_COMMIT := "7d42d6208b65cf7f8a2ba19e05d93234f07f59d7"
PROTON_COMMIT := "6e57afd7de6dc405d17a7f39754fcfe4b9acc497"

.PHONY: all build test clean dist vet proto install

Expand Down
20 changes: 12 additions & 8 deletions cli/deps.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import (
"github.com/goto/siren/plugins/receivers/httpreceiver"
"github.com/goto/siren/plugins/receivers/pagerduty"
"github.com/goto/siren/plugins/receivers/slack"
"github.com/goto/siren/plugins/receivers/slackchannel"
"github.com/newrelic/go-agent/v3/newrelic"
)

Expand Down Expand Up @@ -101,6 +102,7 @@ func InitDeps(

// plugin receiver services
slackPluginService := slack.NewPluginService(cfg.Receivers.Slack, encryptor)
slackChannelPluginService := slackchannel.NewPluginService(cfg.Receivers.Slack, encryptor)
pagerDutyPluginService := pagerduty.NewPluginService(cfg.Receivers.Pagerduty)
httpreceiverPluginService := httpreceiver.NewPluginService(logger, cfg.Receivers.HTTPReceiver)
filePluginService := file.NewPluginService()
Expand All @@ -109,10 +111,11 @@ func InitDeps(
receiverService := receiver.NewService(
receiverRepository,
map[string]receiver.ConfigResolver{
receiver.TypeSlack: slackPluginService,
receiver.TypeHTTP: httpreceiverPluginService,
receiver.TypePagerDuty: pagerDutyPluginService,
receiver.TypeFile: filePluginService,
receiver.TypeSlack: slackPluginService,
receiver.TypeSlackChannel: slackChannelPluginService,
receiver.TypeHTTP: httpreceiverPluginService,
receiver.TypePagerDuty: pagerDutyPluginService,
receiver.TypeFile: filePluginService,
},
)

Expand All @@ -126,10 +129,11 @@ func InitDeps(

// notification
notifierRegistry := map[string]notification.Notifier{
receiver.TypeSlack: slackPluginService,
receiver.TypePagerDuty: pagerDutyPluginService,
receiver.TypeHTTP: httpreceiverPluginService,
receiver.TypeFile: filePluginService,
receiver.TypeSlack: slackPluginService,
receiver.TypeSlackChannel: slackChannelPluginService,
receiver.TypePagerDuty: pagerDutyPluginService,
receiver.TypeHTTP: httpreceiverPluginService,
receiver.TypeFile: filePluginService,
}

idempotencyRepository := postgres.NewIdempotencyRepository(pgClient)
Expand Down
2 changes: 1 addition & 1 deletion core/alert/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ func TestService_List(t *testing.T) {
})
assert.Nil(t, err)
assert.NotEmpty(t, actualAlerts)
repositoryMock.AssertNotCalled(t, "Get", "foo", uint64(1), uint64(0), uint64(0))
repositoryMock.AssertNotCalled(t, "Get", "foo", uint64(1), uint64(0))
})

t.Run("should call repository List method and handle errors", func(t *testing.T) {
Expand Down
3 changes: 1 addition & 2 deletions core/notification/dispatch_receiver_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"strconv"

"github.com/goto/siren/core/log"
"github.com/goto/siren/core/receiver"
"github.com/goto/siren/pkg/errors"
)

Expand Down Expand Up @@ -39,7 +38,7 @@ func (s *DispatchReceiverService) PrepareMessage(ctx context.Context, n Notifica
return nil, nil, false, err
}

rcv, err := s.receiverService.Get(ctx, receiverID, receiver.GetWithData(false))
rcv, err := s.receiverService.Get(ctx, receiverID)
if err != nil {
return nil, nil, false, err
}
Expand Down
8 changes: 4 additions & 4 deletions core/notification/dispatch_receiver_service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func TestDispatchReceiverService_PrepareMessage(t *testing.T) {
},
},
setup: func(rs *mocks.ReceiverService, n *mocks.Notifier) {
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64"), mock.AnythingOfType("receiver.GetOption")).Return(nil, errors.New("some error"))
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64")).Return(nil, errors.New("some error"))
},
wantErr: true,
},
Expand All @@ -53,7 +53,7 @@ func TestDispatchReceiverService_PrepareMessage(t *testing.T) {
},
},
setup: func(rs *mocks.ReceiverService, n *mocks.Notifier) {
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64"), mock.AnythingOfType("receiver.GetOption")).Return(&receiver.Receiver{}, nil)
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64")).Return(&receiver.Receiver{}, nil)
},
wantErr: true,
},
Expand All @@ -65,7 +65,7 @@ func TestDispatchReceiverService_PrepareMessage(t *testing.T) {
},
},
setup: func(rs *mocks.ReceiverService, n *mocks.Notifier) {
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64"), mock.AnythingOfType("receiver.GetOption")).Return(&receiver.Receiver{
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64")).Return(&receiver.Receiver{
Type: testPluginType,
}, nil)
n.EXPECT().PreHookQueueTransformConfigs(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("map[string]interface {}")).Return(nil, errors.New("some error"))
Expand All @@ -80,7 +80,7 @@ func TestDispatchReceiverService_PrepareMessage(t *testing.T) {
},
},
setup: func(rs *mocks.ReceiverService, n *mocks.Notifier) {
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64"), mock.AnythingOfType("receiver.GetOption")).Return(&receiver.Receiver{
rs.EXPECT().Get(mock.AnythingOfType("*context.emptyCtx"), mock.AnythingOfType("uint64")).Return(&receiver.Receiver{
ID: 11,
Type: testPluginType,
}, nil)
Expand Down
5 changes: 1 addition & 4 deletions core/notification/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -250,10 +250,7 @@ func TestService_BuildFromAlerts(t *testing.T) {
errString: "empty alerts",
},
{
name: `should properly return notification
- same annotations are joined by newline
- different labels are splitted into two notifications
`,
name: "should properly return notification (same annotations are joined by newline and different labels are splitted into two notifications)",
alerts: []alert.Alert{
{
ID: 14,
Expand Down
2 changes: 2 additions & 0 deletions core/receiver/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,6 @@ package receiver

type Filter struct {
ReceiverIDs []uint64
Labels map[string]string
Expanded bool
}
13 changes: 13 additions & 0 deletions core/receiver/receiver.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package receiver

import (
"context"
"fmt"
"time"
)

Expand All @@ -23,6 +24,18 @@ type Receiver struct {
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`

// The pointer to receiver parent of a child receiver. This field is required if a receiver is a child receiver
// If ParentID != 0, the receiver is a child receiver.
ParentID uint64 `json:"parent_id"`

// Type should be immutable
Type string `json:"type"`
}

func (r *Receiver) Validate() error {
if r.Type == TypeSlackChannel && r.ParentID == 0 {
return fmt.Errorf("type slack_channel needs receiver parent ID")
}

return nil
}
82 changes: 77 additions & 5 deletions core/receiver/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package receiver

import (
"context"
"fmt"

"github.com/goto/siren/pkg/errors"
"github.com/goto/siren/pkg/telemetry"
Expand Down Expand Up @@ -35,6 +36,15 @@ func (s *Service) List(ctx context.Context, flt Filter) ([]Receiver, error) {
return nil, err
}

if !flt.Expanded {
return receivers, nil
}

receivers, err = s.ExpandParents(ctx, receivers)
if err != nil {
return nil, err
}

domainReceivers := make([]Receiver, 0, len(receivers))
for i := 0; i < len(receivers); i++ {
rcv := receivers[i]
Expand All @@ -51,10 +61,15 @@ func (s *Service) List(ctx context.Context, flt Filter) ([]Receiver, error) {

domainReceivers = append(domainReceivers, rcv)
}

return domainReceivers, nil
}

func (s *Service) Create(ctx context.Context, rcv *Receiver) error {
if err := rcv.Validate(); err != nil {
return errors.ErrInvalid.WithMsgf("%s", err.Error())
}

receiverPlugin, err := s.getReceiverPlugin(rcv.Type)
if err != nil {
return err
Expand All @@ -67,7 +82,7 @@ func (s *Service) Create(ctx context.Context, rcv *Receiver) error {
tag.Upsert(telemetry.TagHookCondition, telemetry.HookConditionPreHookDB),
)

return err
return errors.ErrInvalid.WithMsgf("%s", err.Error())
}

err = s.repository.Create(ctx, rcv)
Expand All @@ -79,14 +94,21 @@ func (s *Service) Create(ctx context.Context, rcv *Receiver) error {
}

type getOpts struct {
withData bool
withData bool
withExpand bool
}

type GetOption func(*getOpts)

func GetWithData(withData bool) GetOption {
func GetWithData() GetOption {
return func(g *getOpts) {
g.withData = withData
g.withData = true
}
}

func GetWithExpand() GetOption {
return func(g *getOpts) {
g.withExpand = true
}
}

Expand All @@ -105,11 +127,21 @@ func (s *Service) Get(ctx context.Context, id uint64, gopts ...GetOption) (*Rece
return nil, err
}

if !opt.withExpand {
return rcv, nil
}

receiverPlugin, err := s.getReceiverPlugin(rcv.Type)
if err != nil {
return nil, err
}

receivers, err := s.ExpandParents(ctx, []Receiver{*rcv})
if err != nil {
return nil, err
}
rcv = &receivers[0]

transformedConfigs, err := receiverPlugin.PostHookDBTransformConfigs(ctx, rcv.Configurations)
if err != nil {
telemetry.IncrementInt64Counter(ctx, telemetry.MetricReceiverHookFailed,
Expand Down Expand Up @@ -149,7 +181,7 @@ func (s *Service) Update(ctx context.Context, rcv *Receiver) error {

rcv.Configurations, err = receiverPlugin.PreHookDBTransformConfigs(ctx, rcv.Configurations)
if err != nil {
return err
return errors.ErrInvalid.WithMsgf("%s", err.Error())
}

if err = s.repository.Update(ctx, rcv); err != nil {
Expand All @@ -165,3 +197,43 @@ func (s *Service) Update(ctx context.Context, rcv *Receiver) error {
func (s *Service) Delete(ctx context.Context, id uint64) error {
return s.repository.Delete(ctx, id)
}

func (s *Service) ExpandParents(ctx context.Context, rcvs []Receiver) ([]Receiver, error) {
var uniqueParentIDsMap = map[uint64]bool{}
for _, rcv := range rcvs {
if rcv.ParentID != 0 {
uniqueParentIDsMap[rcv.ParentID] = true
}
}
if len(uniqueParentIDsMap) == 0 {
return rcvs, nil
}

var uniqueParentIDs []uint64
for k := range uniqueParentIDsMap {
uniqueParentIDs = append(uniqueParentIDs, k)
}

parentReceivers, err := s.List(ctx, Filter{ReceiverIDs: uniqueParentIDs, Expanded: true})
if err != nil {
return nil, fmt.Errorf("failure when expanding receiver parents: %w", err)
}

var parentReceiversMap = map[uint64]Receiver{}
for _, parentRcv := range parentReceivers {
parentReceiversMap[parentRcv.ID] = parentRcv
}

// enrich existing receivers
for _, rcv := range rcvs {
if rcv.ParentID != 0 {
if len(parentReceiversMap[rcv.ParentID].Configurations) != 0 {
for k, v := range parentReceiversMap[rcv.ParentID].Configurations {
rcv.Configurations[k] = v
}
}
}
}

return rcvs, nil
}
Loading

0 comments on commit 107c283

Please sign in to comment.