Skip to content

Commit

Permalink
refactor(api): renamed contact to contact template in web config (#989)
Browse files Browse the repository at this point in the history
  • Loading branch information
almostinf authored Apr 1, 2024
1 parent 9f7f720 commit 1f2b4ac
Show file tree
Hide file tree
Showing 37 changed files with 803 additions and 332 deletions.
5 changes: 2 additions & 3 deletions api/dto/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,7 @@ import (
)

// ErrSubscriptionContainsTeamAndUser used when user try to save subscription team and user attributes specified.
type ErrSubscriptionContainsTeamAndUser struct {
}
type ErrSubscriptionContainsTeamAndUser struct{}

// Error is an error interface implementation method.
func (ErrSubscriptionContainsTeamAndUser) Error() string {
Expand Down Expand Up @@ -123,7 +122,7 @@ func (subscription *Subscription) checkContacts(request *http.Request) error {
}

func normalizeTags(tags []string) []string {
var normalized = make([]string, 0)
normalized := make([]string, 0)
for _, subTag := range tags {
if subTag != "" {
normalized = append(normalized, subTag)
Expand Down
4 changes: 2 additions & 2 deletions api/dto/triggers.go
Original file line number Diff line number Diff line change
Expand Up @@ -382,8 +382,8 @@ func (trigger *Trigger) PopulatedDescription(events moira.NotificationEvents) er
return nil
}

templatingEvents := moira.NotificationEventsToTemplatingEvents(events)
description, err := templating.Populate(trigger.Name, *trigger.Desc, templatingEvents)
triggerDescriptionPopulater := templating.NewTriggerDescriptionPopulater(trigger.Name, events.ToTemplateEvents())
description, err := triggerDescriptionPopulater.Populate(*trigger.Desc)
if err != nil {
return fmt.Errorf("you have an error in your Go template: %v", err)
}
Expand Down
9 changes: 5 additions & 4 deletions api/handler/subscription.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,13 @@ func subscription(router chi.Router) {
// @router /subscription [get]
func getUserSubscriptions(writer http.ResponseWriter, request *http.Request) {
userLogin := middleware.GetLogin(request)
contacts, err := controller.GetUserSubscriptions(database, userLogin)
subscriptions, err := controller.GetUserSubscriptions(database, userLogin)
if err != nil {
render.Render(writer, request, err) //nolint
return
}
if err := render.Render(writer, request, contacts); err != nil {

if err := render.Render(writer, request, subscriptions); err != nil {
render.Render(writer, request, api.ErrorRender(err)) //nolint
return
}
Expand Down Expand Up @@ -90,10 +91,10 @@ func createSubscription(writer http.ResponseWriter, request *http.Request) {
// subscriptionFilter is middleware for check subscription existence and user permissions.
func subscriptionFilter(next http.Handler) http.Handler {
return http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
contactID := middleware.GetSubscriptionID(request)
subscriptionID := middleware.GetSubscriptionID(request)
userLogin := middleware.GetLogin(request)
auth := middleware.GetAuth(request)
subscriptionData, err := controller.CheckUserPermissionsForSubscription(database, contactID, userLogin, auth)
subscriptionData, err := controller.CheckUserPermissionsForSubscription(database, subscriptionID, userLogin, auth)
if err != nil {
render.Render(writer, request, err) //nolint
return
Expand Down
4 changes: 2 additions & 2 deletions api/handler/team.go
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ func setTeamUsers(writer http.ResponseWriter, request *http.Request) {
teamID := middleware.GetTeamID(request)

response, apiErr := controller.SetTeamUsers(database, teamID, members.Usernames)
if err != nil {
if apiErr != nil {
render.Render(writer, request, apiErr) // nolint:errcheck
return
}
Expand Down Expand Up @@ -289,7 +289,7 @@ func addTeamUsers(writer http.ResponseWriter, request *http.Request) {
teamID := middleware.GetTeamID(request)

response, apiErr := controller.AddTeamUsers(database, teamID, members.Usernames)
if err != nil {
if apiErr != nil {
render.Render(writer, request, apiErr) // nolint:errcheck
return
}
Expand Down
20 changes: 10 additions & 10 deletions cmd/api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,16 +74,16 @@ type webConfig struct {
SupportEmail string `yaml:"supportEmail"`
// If true, users will be able to choose Graphite as trigger metrics data source
RemoteAllowed bool
// List of enabled contact types
Contacts []webContact `yaml:"contacts"`
// List of enabled contacts template
ContactsTemplate []webContact `yaml:"contacts_template"`
// Struct to manage feature flags
FeatureFlags featureFlags `yaml:"feature_flags"`
// Returns the sentry configuration for the frontend
Sentry sentryConfig `yaml:"sentry"`
}

type webContact struct {
// Contact type. Use sender name for script and webhook senders, in other cases use sender type.
// Contact Type. Use sender name for script and webhook senders, in other cases use sender type.
// See senders section of notifier config for more details: https://moira.readthedocs.io/en/latest/installation/configuration.html#notifier
ContactType string `yaml:"type"`
// Contact type label that will be shown in web ui
Expand Down Expand Up @@ -128,14 +128,14 @@ func (auth *authorization) toApiConfig() api.Authorization {
}

func (config *webConfig) getSettings(isRemoteEnabled bool, remotes cmd.RemotesConfig) *api.WebConfig {
webContacts := make([]api.WebContact, 0, len(config.Contacts))
for _, configContact := range config.Contacts {
webContacts := make([]api.WebContact, 0, len(config.ContactsTemplate))
for _, contactTemplate := range config.ContactsTemplate {
contact := api.WebContact{
ContactType: configContact.ContactType,
ContactLabel: configContact.ContactLabel,
ValidationRegex: configContact.ValidationRegex,
Placeholder: configContact.Placeholder,
Help: configContact.Help,
ContactType: contactTemplate.ContactType,
ContactLabel: contactTemplate.ContactLabel,
ValidationRegex: contactTemplate.ValidationRegex,
Placeholder: contactTemplate.Placeholder,
Help: contactTemplate.Help,
}
webContacts = append(webContacts, contact)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/api/config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ func Test_webConfig_getSettings(t *testing.T) {
config := webConfig{
SupportEmail: "[email protected]",
RemoteAllowed: false,
Contacts: []webContact{
ContactsTemplate: []webContact{
{
ContactType: "slack",
ContactLabel: "label",
Expand Down
2 changes: 1 addition & 1 deletion cmd/cli/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -417,7 +417,7 @@ func openFile(filePath string, mode int) (*os.File, error) {
if filePath == "" {
return nil, fmt.Errorf("file is not specified")
}
file, err := os.OpenFile(filePath, mode, 0666) //nolint:gofumpt
file, err := os.OpenFile(filePath, mode, 0666) //nolint:gofumpt,gomnd
if err != nil {
return nil, fmt.Errorf("cannot open file: %w", err)
}
Expand Down
10 changes: 6 additions & 4 deletions cmd/cli/user_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import (
. "github.com/smartystreets/goconvey/convey"
)

const subscriptionPrefix = "subscription_"

func TestUpdateUsers(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
Expand Down Expand Up @@ -44,7 +46,7 @@ func TestUpdateUsers(t *testing.T) {
Convey("Test off notifications", func() {
So(usersCleanup(logger, database, users, conf.Cleanup), ShouldBeNil)
for _, contact := range contacts {
subscription, err := database.GetSubscription("subscription_" + contact.ID)
subscription, err := database.GetSubscription(subscriptionPrefix + contact.ID)

So(err, ShouldBeNil)

Expand All @@ -64,7 +66,7 @@ func TestUpdateUsers(t *testing.T) {
continue
}

_, err := database.GetSubscription("subscription_" + contact.ID)
_, err := database.GetSubscription(subscriptionPrefix + contact.ID)
So(err, ShouldNotBeNil)

_, err = database.GetContact(contact.ID)
Expand Down Expand Up @@ -92,7 +94,7 @@ func createDefaultData(database moira.Database) error {

subscriptions = append(subscriptions,
&moira.SubscriptionData{
ID: "subscription_" + contact.ID,
ID: subscriptionPrefix + contact.ID,
User: contact.User,
Enabled: true,
Tags: []string{"Tag" + contact.User},
Expand All @@ -114,7 +116,7 @@ func cleanData(database moira.Database) error {
return err
}

if err := database.RemoveSubscription("subscription_" + contact.ID); err != nil {
if err := database.RemoveSubscription(subscriptionPrefix + contact.ID); err != nil {
return err
}
}
Expand Down
3 changes: 2 additions & 1 deletion database/redis/notification_event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,8 @@ func TestNotificationEvents(t *testing.T) {
TriggerID: triggerID,
Metric: "my.metric",
Values: map[string]float64{"t1": 0},
}})
},
})

total := dataBase.GetNotificationEventCount(triggerID, 0)
So(total, ShouldEqual, 1)
Expand Down
21 changes: 16 additions & 5 deletions datatypes.go
Original file line number Diff line number Diff line change
Expand Up @@ -129,8 +129,10 @@ func (event *NotificationEvent) CreateMessage(location *time.Location) string {
// NotificationEvents represents slice of NotificationEvent.
type NotificationEvents []NotificationEvent

// PopulatedDescription populates a description template using provided trigger and events data.
func (trigger *TriggerData) PopulatedDescription(events NotificationEvents) error {
description, err := templating.Populate(trigger.Name, trigger.Desc, NotificationEventsToTemplatingEvents(events))
triggerDescriptionPopulater := templating.NewTriggerDescriptionPopulater(trigger.Name, events.ToTemplateEvents())
description, err := triggerDescriptionPopulater.Populate(trigger.Desc)
if err != nil {
description = "Your description is using the wrong template. Since we were unable to populate your template with " +
"data, we return it so you can parse it.\n\n" + trigger.Desc
Expand All @@ -141,10 +143,11 @@ func (trigger *TriggerData) PopulatedDescription(events NotificationEvents) erro
return err
}

func NotificationEventsToTemplatingEvents(events NotificationEvents) []templating.Event {
templatingEvents := make([]templating.Event, 0, len(events))
// ToTemplateEvents converts a slice of NotificationEvent into a slice of templating.Event.
func (events NotificationEvents) ToTemplateEvents() []templating.Event {
templateEvents := make([]templating.Event, 0, len(events))
for _, event := range events {
templatingEvents = append(templatingEvents, templating.Event{
templateEvents = append(templateEvents, templating.Event{
Metric: event.Metric,
MetricElements: strings.Split(event.Metric, "."),
Timestamp: event.Timestamp,
Expand All @@ -153,7 +156,7 @@ func NotificationEventsToTemplatingEvents(events NotificationEvents) []templatin
})
}

return templatingEvents
return templateEvents
}

// TriggerData represents trigger object.
Expand Down Expand Up @@ -199,6 +202,14 @@ type ContactData struct {
Team string `json:"team"`
}

// ToTemplateContact converts a ContactData into a template Contact.
func (contact *ContactData) ToTemplateContact() *templating.Contact {
return &templating.Contact{
Type: contact.Type,
Value: contact.Value,
}
}

// SubscriptionData represents user subscription.
type SubscriptionData struct {
Contacts []string `json:"contacts" example:"acd2db98-1659-4a2f-b227-52d71f6e3ba1"`
Expand Down
2 changes: 1 addition & 1 deletion docs/docs.go
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// Will be generated in `Dockerfile.api` by the `make spec` command for swagger docs. DO NOT EDIT.

package docs
package docs
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ require (
github.com/golang/snappy v0.0.4 // indirect
github.com/gomodule/redigo v1.8.9 // indirect
github.com/google/go-querystring v1.1.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/google/uuid v1.3.0
github.com/gopherjs/gopherjs v1.17.2 // indirect
github.com/gorilla/websocket v1.5.0 // indirect
github.com/graph-gophers/graphql-go v1.5.1-0.20230110080634-edea822f558a // indirect
Expand Down
5 changes: 3 additions & 2 deletions integration_tests/notifier/notifier_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@ import (
)

var senderSettings = map[string]interface{}{
"type": "mega-sender",
"sender_type": "mega-sender",
"contact_type": "mega-contact",
}

var (
Expand All @@ -46,7 +47,7 @@ var (

var contact = moira.ContactData{
ID: "ContactID-000000000000001",
Type: "mega-sender",
Type: "mega-contact",
Value: "[email protected]",
}

Expand Down
2 changes: 1 addition & 1 deletion local/api.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ api:
listen: ":8081"
enable_cors: false
web:
contacts:
contacts_template:
- type: mail
label: E-mail
- type: pushover
Expand Down
4 changes: 2 additions & 2 deletions logging/zerolog_adapter/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,10 @@ func getLogWriter(logFileName string) (io.Writer, error) {
}

logDir := filepath.Dir(logFileName)
if err := os.MkdirAll(logDir, 0755); err != nil { //nolint:gofumpt
if err := os.MkdirAll(logDir, 0755); err != nil { //nolint:gofumpt,gomnd
return nil, fmt.Errorf("can't create log directories %s: %s", logDir, err.Error())
}
logFile, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) //nolint:gofumpt
logFile, err := os.OpenFile(logFileName, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) //nolint:gofumpt,gomnd
if err != nil {
return nil, fmt.Errorf("can't open log file %s: %s", logFileName, err.Error())
}
Expand Down
2 changes: 1 addition & 1 deletion notifier/events/event.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ func (worker *FetchEventsWorker) getNotificationSubscriptions(event moira.Notifi
sub, err := worker.Database.GetSubscription(*event.SubscriptionID)
if err != nil {
worker.Metrics.SubsMalformed.Mark(1)
return nil, fmt.Errorf("error while read subscription %s: %s", *event.SubscriptionID, err.Error())
return nil, fmt.Errorf("error while read subscription %s: %w", *event.SubscriptionID, err)
}
return &sub, nil
} else if event.ContactID != "" {
Expand Down
2 changes: 1 addition & 1 deletion notifier/events/event_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -539,7 +539,7 @@ func TestGetNotificationSubscriptions(t *testing.T) {
dataBase.EXPECT().GetSubscription(*event.SubscriptionID).Return(moira.SubscriptionData{}, err)
sub, expected := worker.getNotificationSubscriptions(event, logger)
So(sub, ShouldBeNil)
So(expected, ShouldResemble, fmt.Errorf("error while read subscription %s: %s", *event.SubscriptionID, err.Error()))
So(expected, ShouldResemble, fmt.Errorf("error while read subscription %s: %w", *event.SubscriptionID, err))
})

Convey("Error GetContact", t, func() {
Expand Down
2 changes: 1 addition & 1 deletion notifier/notifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ func NewNotifier(database moira.Database, logger moira.Logger, config Config, me
func (notifier *StandardNotifier) Send(pkg *NotificationPackage, waitGroup *sync.WaitGroup) {
ch, found := notifier.senders[pkg.Contact.Type]
if !found {
notifier.reschedule(pkg, fmt.Sprintf("Unknown contact type '%s' [%s]", pkg.Contact.Type, pkg))
notifier.reschedule(pkg, fmt.Sprintf("Unknown sender contact type '%s' [%s]", pkg.Contact.Type, pkg))
return
}
waitGroup.Add(1)
Expand Down
Loading

0 comments on commit 1f2b4ac

Please sign in to comment.