Chore: Remove result field from alert commands and queries (#62714)

* remove result field from alert notification commands and queries

* fix a few more tests

* ok, linter

* remove alert result fields

* fix api calls

* et tu, linter
This commit is contained in:
Serge Zaitsev 2023-02-02 09:41:05 +01:00 committed by GitHub
parent d9fd807375
commit b1c98f7119
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
21 changed files with 412 additions and 444 deletions

View File

@ -32,12 +32,13 @@ func (hs *HTTPServer) ValidateOrgAlert(c *contextmodel.ReqContext) {
}
query := alertmodels.GetAlertByIdQuery{Id: id}
if err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query); err != nil {
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
if err != nil {
c.JsonApiErr(404, "Alert not found", nil)
return
}
if c.OrgID != query.Result.OrgId {
if c.OrgID != res.OrgId {
c.JsonApiErr(403, "You are not allowed to edit/view alert", nil)
return
}
@ -64,11 +65,12 @@ func (hs *HTTPServer) GetAlertStatesForDashboard(c *contextmodel.ReqContext) res
DashboardId: c.QueryInt64("dashboardId"),
}
if err := hs.AlertEngine.AlertStore.GetAlertStatesForDashboard(c.Req.Context(), &query); err != nil {
res, err := hs.AlertEngine.AlertStore.GetAlertStatesForDashboard(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Failed to fetch alert states", err)
}
return response.JSON(http.StatusOK, query.Result)
return response.JSON(http.StatusOK, res)
}
// swagger:route GET /alerts legacy_alerts getAlerts
@ -145,15 +147,16 @@ func (hs *HTTPServer) GetAlerts(c *contextmodel.ReqContext) response.Response {
query.State = states
}
if err := hs.AlertEngine.AlertStore.HandleAlertsQuery(c.Req.Context(), &query); err != nil {
res, err := hs.AlertEngine.AlertStore.HandleAlertsQuery(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "List alerts failed", err)
}
for _, alert := range query.Result {
for _, alert := range res {
alert.Url = dashboards.GetDashboardURL(alert.DashboardUid, alert.DashboardSlug)
}
return response.JSON(http.StatusOK, query.Result)
return response.JSON(http.StatusOK, res)
}
// swagger:route POST /alerts/test legacy_alerts testAlert
@ -227,11 +230,12 @@ func (hs *HTTPServer) GetAlert(c *contextmodel.ReqContext) response.Response {
}
query := alertmodels.GetAlertByIdQuery{Id: id}
if err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query); err != nil {
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "List alerts failed", err)
}
return response.JSON(http.StatusOK, &query.Result)
return response.JSON(http.StatusOK, &res)
}
func (hs *HTTPServer) GetAlertNotifiers(ngalertEnabled bool) func(*contextmodel.ReqContext) response.Response {
@ -299,12 +303,7 @@ func (hs *HTTPServer) GetAlertNotifications(c *contextmodel.ReqContext) response
func (hs *HTTPServer) getAlertNotificationsInternal(c *contextmodel.ReqContext) ([]*alertmodels.AlertNotification, error) {
query := &alertmodels.GetAllAlertNotificationsQuery{OrgId: c.OrgID}
if err := hs.AlertNotificationService.GetAllAlertNotifications(c.Req.Context(), query); err != nil {
return nil, err
}
return query.Result, nil
return hs.AlertNotificationService.GetAllAlertNotifications(c.Req.Context(), query)
}
// swagger:route GET /alert-notifications/{notification_channel_id} legacy_alerts_notification_channels getAlertNotificationChannelByID
@ -333,15 +332,16 @@ func (hs *HTTPServer) GetAlertNotificationByID(c *contextmodel.ReqContext) respo
return response.Error(404, "Alert notification not found", nil)
}
if err := hs.AlertNotificationService.GetAlertNotifications(c.Req.Context(), query); err != nil {
res, err := hs.AlertNotificationService.GetAlertNotifications(c.Req.Context(), query)
if err != nil {
return response.Error(500, "Failed to get alert notifications", err)
}
if query.Result == nil {
if res == nil {
return response.Error(404, "Alert notification not found", nil)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(query.Result))
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
}
// swagger:route GET /alert-notifications/uid/{notification_channel_uid} legacy_alerts_notification_channels getAlertNotificationChannelByUID
@ -366,15 +366,16 @@ func (hs *HTTPServer) GetAlertNotificationByUID(c *contextmodel.ReqContext) resp
return response.Error(404, "Alert notification not found", nil)
}
if err := hs.AlertNotificationService.GetAlertNotificationsWithUid(c.Req.Context(), query); err != nil {
res, err := hs.AlertNotificationService.GetAlertNotificationsWithUid(c.Req.Context(), query)
if err != nil {
return response.Error(500, "Failed to get alert notifications", err)
}
if query.Result == nil {
if res == nil {
return response.Error(404, "Alert notification not found", nil)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(query.Result))
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
}
// swagger:route POST /alert-notifications legacy_alerts_notification_channels createAlertNotificationChannel
@ -396,7 +397,8 @@ func (hs *HTTPServer) CreateAlertNotification(c *contextmodel.ReqContext) respon
}
cmd.OrgId = c.OrgID
if err := hs.AlertNotificationService.CreateAlertNotificationCommand(c.Req.Context(), &cmd); err != nil {
res, err := hs.AlertNotificationService.CreateAlertNotificationCommand(c.Req.Context(), &cmd)
if err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationWithSameNameExists) || errors.Is(err, alertmodels.ErrAlertNotificationWithSameUIDExists) {
return response.Error(409, "Failed to create alert notification", err)
}
@ -407,7 +409,7 @@ func (hs *HTTPServer) CreateAlertNotification(c *contextmodel.ReqContext) respon
return response.Error(500, "Failed to create alert notification", err)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(cmd.Result))
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
}
// swagger:route PUT /alert-notifications/{notification_channel_id} legacy_alerts_notification_channels updateAlertNotificationChannel
@ -434,7 +436,7 @@ func (hs *HTTPServer) UpdateAlertNotification(c *contextmodel.ReqContext) respon
return response.Error(500, "Failed to update alert notification", err)
}
if err := hs.AlertNotificationService.UpdateAlertNotification(c.Req.Context(), &cmd); err != nil {
if _, err := hs.AlertNotificationService.UpdateAlertNotification(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationNotFound) {
return response.Error(404, err.Error(), err)
}
@ -450,11 +452,12 @@ func (hs *HTTPServer) UpdateAlertNotification(c *contextmodel.ReqContext) respon
Id: cmd.Id,
}
if err := hs.AlertNotificationService.GetAlertNotifications(c.Req.Context(), &query); err != nil {
res, err := hs.AlertNotificationService.GetAlertNotifications(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Failed to get alert notification", err)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(query.Result))
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
}
// swagger:route PUT /alert-notifications/uid/{notification_channel_uid} legacy_alerts_notification_channels updateAlertNotificationChannelByUID
@ -482,7 +485,7 @@ func (hs *HTTPServer) UpdateAlertNotificationByUID(c *contextmodel.ReqContext) r
return response.Error(500, "Failed to update alert notification", err)
}
if err := hs.AlertNotificationService.UpdateAlertNotificationWithUid(c.Req.Context(), &cmd); err != nil {
if _, err := hs.AlertNotificationService.UpdateAlertNotificationWithUid(c.Req.Context(), &cmd); err != nil {
if errors.Is(err, alertmodels.ErrAlertNotificationNotFound) {
return response.Error(404, err.Error(), nil)
}
@ -494,11 +497,12 @@ func (hs *HTTPServer) UpdateAlertNotificationByUID(c *contextmodel.ReqContext) r
Uid: cmd.Uid,
}
if err := hs.AlertNotificationService.GetAlertNotificationsWithUid(c.Req.Context(), &query); err != nil {
res, err := hs.AlertNotificationService.GetAlertNotificationsWithUid(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Failed to get alert notification", err)
}
return response.JSON(http.StatusOK, dtos.NewAlertNotification(query.Result))
return response.JSON(http.StatusOK, dtos.NewAlertNotification(res))
}
func (hs *HTTPServer) fillWithSecureSettingsData(ctx context.Context, cmd *alertmodels.UpdateAlertNotificationCommand) error {
@ -511,11 +515,12 @@ func (hs *HTTPServer) fillWithSecureSettingsData(ctx context.Context, cmd *alert
Id: cmd.Id,
}
if err := hs.AlertNotificationService.GetAlertNotifications(ctx, query); err != nil {
res, err := hs.AlertNotificationService.GetAlertNotifications(ctx, query)
if err != nil {
return err
}
secureSettings, err := hs.EncryptionService.DecryptJsonData(ctx, query.Result.SecureSettings, setting.SecretKey)
secureSettings, err := hs.EncryptionService.DecryptJsonData(ctx, res.SecureSettings, setting.SecretKey)
if err != nil {
return err
}
@ -539,11 +544,12 @@ func (hs *HTTPServer) fillWithSecureSettingsDataByUID(ctx context.Context, cmd *
Uid: cmd.Uid,
}
if err := hs.AlertNotificationService.GetAlertNotificationsWithUid(ctx, query); err != nil {
res, err := hs.AlertNotificationService.GetAlertNotificationsWithUid(ctx, query)
if err != nil {
return err
}
secureSettings, err := hs.EncryptionService.DecryptJsonData(ctx, query.Result.SecureSettings, setting.SecretKey)
secureSettings, err := hs.EncryptionService.DecryptJsonData(ctx, res.SecureSettings, setting.SecretKey)
if err != nil {
return err
}
@ -693,11 +699,12 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmod
result["alertId"] = alertID
query := alertmodels.GetAlertByIdQuery{Id: alertID}
if err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query); err != nil {
res, err := hs.AlertEngine.AlertStore.GetAlertById(c.Req.Context(), &query)
if err != nil {
return response.Error(500, "Get Alert failed", err)
}
guardian, err := guardian.New(c.Req.Context(), query.Result.DashboardId, c.OrgID, c.SignedInUser)
guardian, err := guardian.New(c.Req.Context(), res.DashboardId, c.OrgID, c.SignedInUser)
if err != nil {
return response.ErrOrFallback(http.StatusInternalServerError, "Error while creating permission guardian", err)
}
@ -710,11 +717,11 @@ func (hs *HTTPServer) PauseAlert(legacyAlertingEnabled *bool) func(c *contextmod
}
// Alert state validation
if query.Result.State != alertmodels.AlertStatePaused && !dto.Paused {
if res.State != alertmodels.AlertStatePaused && !dto.Paused {
result["state"] = "un-paused"
result["message"] = "Alert is already un-paused"
return response.JSON(http.StatusOK, result)
} else if query.Result.State == alertmodels.AlertStatePaused && dto.Paused {
} else if res.State == alertmodels.AlertStatePaused && dto.Paused {
result["state"] = alertmodels.AlertStatePaused
result["message"] = "Alert is already paused"
return response.JSON(http.StatusOK, result)

View File

@ -29,12 +29,12 @@ type UsageStatsQuerier interface {
// configured in Grafana.
func (e *AlertEngine) QueryUsageStats(ctx context.Context) (*UsageStats, error) {
cmd := &models.GetAllAlertsQuery{}
err := e.AlertStore.GetAllAlertQueryHandler(ctx, cmd)
res, err := e.AlertStore.GetAllAlertQueryHandler(ctx, cmd)
if err != nil {
return nil, err
}
dsUsage, err := e.mapRulesToUsageStats(ctx, cmd.Result)
dsUsage, err := e.mapRulesToUsageStats(ctx, res)
if err != nil {
return nil, err
}

View File

@ -30,7 +30,7 @@ func TestAlertingUsageStats(t *testing.T) {
datasourceService: dsMock,
}
store.getAllAlerts = func(ctx context.Context, query *models.GetAllAlertsQuery) error {
store.getAllAlerts = func(ctx context.Context, query *models.GetAllAlertsQuery) (res []*models.Alert, err error) {
var createFake = func(file string) *simplejson.Json {
// Ignore gosec warning G304 since it's a test
// nolint:gosec
@ -42,13 +42,12 @@ func TestAlertingUsageStats(t *testing.T) {
return j
}
query.Result = []*models.Alert{
return []*models.Alert{
{Id: 1, Settings: createFake("testdata/settings/one_condition.json")},
{Id: 2, Settings: createFake("testdata/settings/two_conditions.json")},
{Id: 2, Settings: createFake("testdata/settings/three_conditions.json")},
{Id: 3, Settings: createFake("testdata/settings/empty.json")},
}
return nil
}, nil
}
result, err := ae.QueryUsageStats(context.Background())

View File

@ -50,38 +50,38 @@ func (handler *FakeResultHandler) handle(evalContext *EvalContext) error {
// A mock implementation of the AlertStore interface, allowing to override certain methods individually
type AlertStoreMock struct {
getAllAlerts func(context.Context, *models.GetAllAlertsQuery) error
getAlertNotificationsWithUidToSend func(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error
getOrCreateNotificationState func(ctx context.Context, query *models.GetOrCreateNotificationStateQuery) error
getAllAlerts func(context.Context, *models.GetAllAlertsQuery) ([]*models.Alert, error)
getAlertNotificationsWithUidToSend func(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) ([]*models.AlertNotification, error)
getOrCreateNotificationState func(ctx context.Context, query *models.GetOrCreateNotificationStateQuery) (*models.AlertNotificationState, error)
}
func (a *AlertStoreMock) GetAlertById(c context.Context, cmd *models.GetAlertByIdQuery) error {
return nil
func (a *AlertStoreMock) GetAlertById(c context.Context, cmd *models.GetAlertByIdQuery) (res *models.Alert, err error) {
return nil, nil
}
func (a *AlertStoreMock) GetAllAlertQueryHandler(c context.Context, cmd *models.GetAllAlertsQuery) error {
func (a *AlertStoreMock) GetAllAlertQueryHandler(c context.Context, cmd *models.GetAllAlertsQuery) (res []*models.Alert, err error) {
if a.getAllAlerts != nil {
return a.getAllAlerts(c, cmd)
}
return nil
return nil, nil
}
func (a *AlertStoreMock) GetAlertNotificationUidWithId(c context.Context, query *models.GetAlertNotificationUidQuery) error {
return nil
func (a *AlertStoreMock) GetAlertNotificationUidWithId(c context.Context, query *models.GetAlertNotificationUidQuery) (res string, err error) {
return "", nil
}
func (a *AlertStoreMock) GetAlertNotificationsWithUidToSend(c context.Context, cmd *models.GetAlertNotificationsWithUidToSendQuery) error {
func (a *AlertStoreMock) GetAlertNotificationsWithUidToSend(c context.Context, cmd *models.GetAlertNotificationsWithUidToSendQuery) (res []*models.AlertNotification, err error) {
if a.getAlertNotificationsWithUidToSend != nil {
return a.getAlertNotificationsWithUidToSend(c, cmd)
}
return nil
return nil, nil
}
func (a *AlertStoreMock) GetOrCreateAlertNotificationState(c context.Context, cmd *models.GetOrCreateNotificationStateQuery) error {
func (a *AlertStoreMock) GetOrCreateAlertNotificationState(c context.Context, cmd *models.GetOrCreateNotificationStateQuery) (res *models.AlertNotificationState, err error) {
if a.getOrCreateNotificationState != nil {
return a.getOrCreateNotificationState(c, cmd)
}
return nil
return nil, nil
}
func (a *AlertStoreMock) GetDashboardUIDById(_ context.Context, _ *dashboards.GetDashboardRefByIDQuery) error {
@ -96,16 +96,16 @@ func (a *AlertStoreMock) SetAlertNotificationStateToPendingCommand(_ context.Con
return nil
}
func (a *AlertStoreMock) SetAlertState(_ context.Context, _ *models.SetAlertStateCommand) error {
return nil
func (a *AlertStoreMock) SetAlertState(_ context.Context, _ *models.SetAlertStateCommand) (res models.Alert, err error) {
return models.Alert{}, nil
}
func (a *AlertStoreMock) GetAlertStatesForDashboard(_ context.Context, _ *models.GetAlertStatesForDashboardQuery) error {
return nil
func (a *AlertStoreMock) GetAlertStatesForDashboard(_ context.Context, _ *models.GetAlertStatesForDashboardQuery) (res []*models.AlertStateInfoDTO, err error) {
return nil, nil
}
func (a *AlertStoreMock) HandleAlertsQuery(context.Context, *models.GetAlertsQuery) error {
return nil
func (a *AlertStoreMock) HandleAlertsQuery(context.Context, *models.GetAlertsQuery) (res []*models.AlertListItemDTO, err error) {
return nil, nil
}
func (a *AlertStoreMock) PauseAlert(context.Context, *models.PauseAlertCommand) error {
@ -139,13 +139,12 @@ func TestEngineProcessJob(t *testing.T) {
job := &Job{running: true, Rule: &Rule{}}
t.Run("Should register usage metrics func", func(t *testing.T) {
store.getAllAlerts = func(ctx context.Context, q *models.GetAllAlertsQuery) error {
store.getAllAlerts = func(ctx context.Context, q *models.GetAllAlertsQuery) (res []*models.Alert, err error) {
settings, err := simplejson.NewJson([]byte(`{"conditions": [{"query": { "datasourceId": 1}}]}`))
if err != nil {
return err
return nil, err
}
q.Result = []*models.Alert{{Settings: settings}}
return nil
return []*models.Alert{{Settings: settings}}, nil
}
report, err := usMock.GetUsageReport(context.Background())

View File

@ -207,11 +207,11 @@ func TestAlertRuleExtraction(t *testing.T) {
sqlStore := sqlStore{db: sqlstore.InitTestDB(t)}
firstNotification := models.CreateAlertNotificationCommand{Uid: "notifier1", OrgId: 1, Name: "1"}
err = sqlStore.CreateAlertNotificationCommand(context.Background(), &firstNotification)
_, err = sqlStore.CreateAlertNotificationCommand(context.Background(), &firstNotification)
require.Nil(t, err)
secondNotification := models.CreateAlertNotificationCommand{Uid: "notifier2", OrgId: 1, Name: "2"}
err = sqlStore.CreateAlertNotificationCommand(context.Background(), &secondNotification)
_, err = sqlStore.CreateAlertNotificationCommand(context.Background(), &secondNotification)
require.Nil(t, err)
json, err := os.ReadFile("./testdata/influxdb-alert.json")

View File

@ -158,8 +158,6 @@ type SetAlertStateCommand struct {
State AlertStateType
Error string
EvalData *simplejson.Json
Result Alert
}
// Queries
@ -171,25 +169,17 @@ type GetAlertsQuery struct {
Limit int64
Query string
User *user.SignedInUser
Result []*AlertListItemDTO
}
type GetAllAlertsQuery struct {
Result []*Alert
}
type GetAllAlertsQuery struct{}
type GetAlertByIdQuery struct {
Id int64
Result *Alert
}
type GetAlertStatesForDashboardQuery struct {
OrgId int64
DashboardId int64
Result []*AlertStateInfoDTO
}
type AlertListItemDTO struct {

View File

@ -54,8 +54,6 @@ type CreateAlertNotificationCommand struct {
OrgId int64 `json:"-"`
EncryptedSecureSettings map[string][]byte `json:"-"`
Result *AlertNotification `json:"-"`
}
type UpdateAlertNotificationCommand struct {
@ -72,8 +70,6 @@ type UpdateAlertNotificationCommand struct {
OrgId int64 `json:"-"`
EncryptedSecureSettings map[string][]byte `json:"-"`
Result *AlertNotification `json:"-"`
}
type UpdateAlertNotificationWithUidCommand struct {
@ -88,8 +84,7 @@ type UpdateAlertNotificationWithUidCommand struct {
Settings *simplejson.Json `json:"settings" binding:"Required"`
SecureSettings map[string]string `json:"secureSettings"`
OrgId int64 `json:"-"`
Result *AlertNotification `json:"-"`
OrgId int64 `json:"-"`
}
type DeleteAlertNotificationCommand struct {
@ -106,36 +101,26 @@ type DeleteAlertNotificationWithUidCommand struct {
type GetAlertNotificationUidQuery struct {
Id int64
OrgId int64
Result string
}
type GetAlertNotificationsQuery struct {
Name string
Id int64
OrgId int64
Result *AlertNotification
}
type GetAlertNotificationsWithUidQuery struct {
Uid string
OrgId int64
Result *AlertNotification
}
type GetAlertNotificationsWithUidToSendQuery struct {
Uids []string
OrgId int64
Result []*AlertNotification
}
type GetAllAlertNotificationsQuery struct {
OrgId int64
Result []*AlertNotification
}
type AlertNotificationState struct {
@ -166,6 +151,4 @@ type GetOrCreateNotificationStateQuery struct {
OrgId int64
AlertId int64
NotifierId int64
Result *AlertNotificationState
}

View File

@ -259,12 +259,13 @@ func (n *notificationService) renderAndUploadImage(evalCtx *EvalContext, timeout
func (n *notificationService) getNeededNotifiers(orgID int64, notificationUids []string, evalContext *EvalContext) (notifierStateSlice, error) {
query := &alertmodels.GetAlertNotificationsWithUidToSendQuery{OrgId: orgID, Uids: notificationUids}
if err := n.sqlStore.GetAlertNotificationsWithUidToSend(evalContext.Ctx, query); err != nil {
res, err := n.sqlStore.GetAlertNotificationsWithUidToSend(evalContext.Ctx, query)
if err != nil {
return nil, err
}
var result notifierStateSlice
for _, notification := range query.Result {
for _, notification := range res {
not, err := InitNotifier(notification, n.decryptFn, n.notificationService)
if err != nil {
n.log.Error("Could not create notifier", "notifier", notification.Uid, "error", err)
@ -277,16 +278,16 @@ func (n *notificationService) getNeededNotifiers(orgID int64, notificationUids [
OrgId: evalContext.Rule.OrgID,
}
err = n.sqlStore.GetOrCreateAlertNotificationState(evalContext.Ctx, query)
state, err := n.sqlStore.GetOrCreateAlertNotificationState(evalContext.Ctx, query)
if err != nil {
n.log.Error("Could not get notification state.", "notifier", notification.Id, "error", err)
continue
}
if not.ShouldNotify(evalContext.Ctx, evalContext, query.Result) {
if not.ShouldNotify(evalContext.Ctx, evalContext, state) {
result = append(result, &notifierState{
notifier: not,
state: query.Result,
state: state,
})
}
}

View File

@ -182,8 +182,8 @@ func notificationServiceScenario(t *testing.T, name string, evalCtx *EvalContext
store := evalCtx.Store.(*AlertStoreMock)
store.getAlertNotificationsWithUidToSend = func(ctx context.Context, query *alertmodels.GetAlertNotificationsWithUidToSendQuery) error {
query.Result = []*alertmodels.AlertNotification{
store.getAlertNotificationsWithUidToSend = func(ctx context.Context, query *alertmodels.GetAlertNotificationsWithUidToSendQuery) (res []*alertmodels.AlertNotification, err error) {
return []*alertmodels.AlertNotification{
{
Id: 1,
Type: "test",
@ -191,19 +191,17 @@ func notificationServiceScenario(t *testing.T, name string, evalCtx *EvalContext
"uploadImage": uploadImage,
}),
},
}
return nil
}, nil
}
store.getOrCreateNotificationState = func(ctx context.Context, query *alertmodels.GetOrCreateNotificationStateQuery) error {
query.Result = &alertmodels.AlertNotificationState{
store.getOrCreateNotificationState = func(ctx context.Context, query *alertmodels.GetOrCreateNotificationStateQuery) (res *alertmodels.AlertNotificationState, err error) {
return &alertmodels.AlertNotificationState{
AlertId: evalCtx.Rule.ID,
AlertRuleStateUpdatedVersion: 1,
Id: 1,
OrgId: evalCtx.Rule.OrgID,
State: alertmodels.AlertNotificationStateUnknown,
}
return nil
}, nil
}
setting.AlertingNotificationTimeout = 30 * time.Second

View File

@ -31,13 +31,14 @@ func newRuleReader(sqlStore AlertStore) *defaultRuleReader {
func (arr *defaultRuleReader) fetch(ctx context.Context) []*Rule {
cmd := &models.GetAllAlertsQuery{}
if err := arr.sqlStore.GetAllAlertQueryHandler(ctx, cmd); err != nil {
alerts, err := arr.sqlStore.GetAllAlertQueryHandler(ctx, cmd)
if err != nil {
arr.log.Error("Could not load alerts", "error", err)
return []*Rule{}
}
res := make([]*Rule, 0)
for _, ruleDef := range cmd.Result {
for _, ruleDef := range alerts {
if model, err := NewRuleFromDBAlert(ctx, arr.sqlStore, ruleDef, false); err != nil {
arr.log.Error("Could not build alert model for rule", "ruleId", ruleDef.Id, "error", err)
} else {

View File

@ -59,7 +59,8 @@ func (handler *defaultResultHandler) handle(evalContext *EvalContext) error {
EvalData: annotationData,
}
if err := handler.sqlStore.SetAlertState(evalContext.Ctx, cmd); err != nil {
alert, err := handler.sqlStore.SetAlertState(evalContext.Ctx, cmd)
if err != nil {
if errors.Is(err, models.ErrCannotChangeStateOnPausedAlert) {
handler.log.Error("Cannot change state on alert that's paused", "error", err)
return err
@ -75,7 +76,7 @@ func (handler *defaultResultHandler) handle(evalContext *EvalContext) error {
// StateChanges is used for de duping alert notifications
// when two servers are raising. This makes sure that the server
// with the last state change always sends a notification.
evalContext.Rule.StateChanges = cmd.Result.StateChanges
evalContext.Rule.StateChanges = alert.StateChanges
// Update the last state change of the alert rule in memory
evalContext.Rule.LastStateChange = time.Now()

View File

@ -226,11 +226,12 @@ func getAlertNotificationUIDByIDAndOrgID(ctx context.Context, store AlertStore,
Id: notificationID,
}
if err := store.GetAlertNotificationUidWithId(ctx, query); err != nil {
uid, err := store.GetAlertNotificationUidWithId(ctx, query)
if err != nil {
return "", err
}
return query.Result, nil
return uid, nil
}
// ConditionFactory is the function signature for creating `Conditions`.

View File

@ -92,10 +92,10 @@ func TestAlertRuleModel(t *testing.T) {
})
firstNotification := models.CreateAlertNotificationCommand{Uid: "notifier1", OrgId: 1, Name: "1"}
err := sqlStore.CreateAlertNotificationCommand(context.Background(), &firstNotification)
_, err := sqlStore.CreateAlertNotificationCommand(context.Background(), &firstNotification)
require.Nil(t, err)
secondNotification := models.CreateAlertNotificationCommand{Uid: "notifier2", OrgId: 1, Name: "2"}
err = sqlStore.CreateAlertNotificationCommand(context.Background(), &secondNotification)
_, err = sqlStore.CreateAlertNotificationCommand(context.Background(), &secondNotification)
require.Nil(t, err)
t.Run("Testing alert rule with notification id and uid", func(t *testing.T) {

View File

@ -29,19 +29,18 @@ func ProvideService(store db.DB, encryptionService encryption.Internal,
return s
}
func (s *AlertNotificationService) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) error {
func (s *AlertNotificationService) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) (res *models.AlertNotification, err error) {
return s.SQLStore.GetAlertNotifications(ctx, query)
}
func (s *AlertNotificationService) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) error {
func (s *AlertNotificationService) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) (res *models.AlertNotification, err error) {
if util.IsShortUIDTooLong(cmd.Uid) {
return ValidationError{Reason: "Invalid UID: Must be 40 characters or less"}
return nil, ValidationError{Reason: "Invalid UID: Must be 40 characters or less"}
}
var err error
cmd.EncryptedSecureSettings, err = s.EncryptionService.EncryptJsonData(ctx, cmd.SecureSettings, setting.SecretKey)
if err != nil {
return err
return nil, err
}
model := models.AlertNotification{
@ -51,21 +50,20 @@ func (s *AlertNotificationService) CreateAlertNotificationCommand(ctx context.Co
}
if err := s.validateAlertNotification(ctx, &model, cmd.SecureSettings); err != nil {
return err
return nil, err
}
return s.SQLStore.CreateAlertNotificationCommand(ctx, cmd)
}
func (s *AlertNotificationService) UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) error {
func (s *AlertNotificationService) UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) (res *models.AlertNotification, err error) {
if util.IsShortUIDTooLong(cmd.Uid) {
return ValidationError{Reason: "Invalid UID: Must be 40 characters or less"}
return nil, ValidationError{Reason: "Invalid UID: Must be 40 characters or less"}
}
var err error
cmd.EncryptedSecureSettings, err = s.EncryptionService.EncryptJsonData(ctx, cmd.SecureSettings, setting.SecretKey)
if err != nil {
return err
return nil, err
}
model := models.AlertNotification{
@ -77,7 +75,7 @@ func (s *AlertNotificationService) UpdateAlertNotification(ctx context.Context,
}
if err := s.validateAlertNotification(ctx, &model, cmd.SecureSettings); err != nil {
return err
return nil, err
}
return s.SQLStore.UpdateAlertNotification(ctx, cmd)
@ -87,11 +85,11 @@ func (s *AlertNotificationService) DeleteAlertNotification(ctx context.Context,
return s.SQLStore.DeleteAlertNotification(ctx, cmd)
}
func (s *AlertNotificationService) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) error {
func (s *AlertNotificationService) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) (res []*models.AlertNotification, err error) {
return s.SQLStore.GetAllAlertNotifications(ctx, query)
}
func (s *AlertNotificationService) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) error {
func (s *AlertNotificationService) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) (res *models.AlertNotificationState, err error) {
return s.SQLStore.GetOrCreateAlertNotificationState(ctx, cmd)
}
@ -103,13 +101,13 @@ func (s *AlertNotificationService) SetAlertNotificationStateToPendingCommand(ctx
return s.SQLStore.SetAlertNotificationStateToPendingCommand(ctx, cmd)
}
func (s *AlertNotificationService) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) error {
func (s *AlertNotificationService) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) (res *models.AlertNotification, err error) {
return s.SQLStore.GetAlertNotificationsWithUid(ctx, query)
}
func (s *AlertNotificationService) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) error {
func (s *AlertNotificationService) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) (res *models.AlertNotification, err error) {
if util.IsShortUIDTooLong(cmd.Uid) || util.IsShortUIDTooLong(cmd.NewUid) {
return ValidationError{Reason: "Invalid UID: Must be 40 characters or less"}
return nil, ValidationError{Reason: "Invalid UID: Must be 40 characters or less"}
}
return s.SQLStore.UpdateAlertNotificationWithUid(ctx, cmd)
@ -119,7 +117,7 @@ func (s *AlertNotificationService) DeleteAlertNotificationWithUid(ctx context.Co
return s.SQLStore.DeleteAlertNotificationWithUid(ctx, cmd)
}
func (s *AlertNotificationService) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error {
func (s *AlertNotificationService) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) (res []*models.AlertNotification, err error) {
return s.SQLStore.GetAlertNotificationsWithUidToSend(ctx, query)
}
@ -131,17 +129,18 @@ func (s *AlertNotificationService) createNotifier(ctx context.Context, model *mo
OrgId: model.OrgId,
Id: model.Id,
}
if err := s.SQLStore.GetAlertNotifications(ctx, query); err != nil {
res, err := s.SQLStore.GetAlertNotifications(ctx, query)
if err != nil {
return nil, err
}
if query.Result == nil {
if res == nil {
return nil, fmt.Errorf("unable to find the alert notification")
}
if query.Result.SecureSettings != nil {
if res.SecureSettings != nil {
var err error
secureSettingsMap, err = s.EncryptionService.DecryptJsonData(ctx, query.Result.SecureSettings, setting.SecretKey)
secureSettingsMap, err = s.EncryptionService.DecryptJsonData(ctx, res.SecureSettings, setting.SecretKey)
if err != nil {
return nil, err
}

View File

@ -53,7 +53,7 @@ func TestService(t *testing.T) {
ss := map[string]string{"password": "12345"}
cmd := models.CreateAlertNotificationCommand{SecureSettings: ss}
err := s.CreateAlertNotificationCommand(ctx, &cmd)
_, err := s.CreateAlertNotificationCommand(ctx, &cmd)
require.Error(t, err)
})
@ -63,18 +63,17 @@ func TestService(t *testing.T) {
ss := map[string]string{"password": "12345"}
cmd := models.CreateAlertNotificationCommand{SecureSettings: ss, Type: nType}
err := s.CreateAlertNotificationCommand(ctx, &cmd)
an, err := s.CreateAlertNotificationCommand(ctx, &cmd)
require.NoError(t, err)
an := cmd.Result
decrypted, err := s.EncryptionService.DecryptJsonData(ctx, an.SecureSettings, setting.SecretKey)
require.NoError(t, err)
require.Equal(t, ss, decrypted)
// Delete the created alert notification
delCmd := models.DeleteAlertNotificationCommand{
Id: cmd.Result.Id,
OrgId: cmd.Result.OrgId,
Id: an.Id,
OrgId: an.OrgId,
}
err = s.DeleteAlertNotification(context.Background(), &delCmd)
require.NoError(t, err)
@ -87,18 +86,18 @@ func TestService(t *testing.T) {
ss := map[string]string{"password": "12345"}
createCmd := models.CreateAlertNotificationCommand{SecureSettings: ss, Type: nType}
err := s.CreateAlertNotificationCommand(ctx, &createCmd)
n, err := s.CreateAlertNotificationCommand(ctx, &createCmd)
require.NoError(t, err)
// Try to update it with an invalid type.
updateCmd := models.UpdateAlertNotificationCommand{Id: createCmd.Result.Id, Settings: simplejson.New(), SecureSettings: ss, Type: "invalid"}
err = s.UpdateAlertNotification(ctx, &updateCmd)
updateCmd := models.UpdateAlertNotificationCommand{Id: n.Id, Settings: simplejson.New(), SecureSettings: ss, Type: "invalid"}
_, err = s.UpdateAlertNotification(ctx, &updateCmd)
require.Error(t, err)
// Delete the created alert notification.
delCmd := models.DeleteAlertNotificationCommand{
Id: createCmd.Result.Id,
OrgId: createCmd.Result.OrgId,
Id: n.Id,
OrgId: n.OrgId,
}
err = s.DeleteAlertNotification(context.Background(), &delCmd)
require.NoError(t, err)
@ -111,22 +110,22 @@ func TestService(t *testing.T) {
ss := map[string]string{"password": "12345"}
createCmd := models.CreateAlertNotificationCommand{SecureSettings: ss, Type: nType}
err := s.CreateAlertNotificationCommand(ctx, &createCmd)
n, err := s.CreateAlertNotificationCommand(ctx, &createCmd)
require.NoError(t, err)
// Update test notification.
updateCmd := models.UpdateAlertNotificationCommand{Id: createCmd.Result.Id, Settings: simplejson.New(), SecureSettings: ss, Type: nType}
err = s.UpdateAlertNotification(ctx, &updateCmd)
updateCmd := models.UpdateAlertNotificationCommand{Id: n.Id, Settings: simplejson.New(), SecureSettings: ss, Type: nType}
n2, err := s.UpdateAlertNotification(ctx, &updateCmd)
require.NoError(t, err)
decrypted, err := s.EncryptionService.DecryptJsonData(ctx, updateCmd.Result.SecureSettings, setting.SecretKey)
decrypted, err := s.EncryptionService.DecryptJsonData(ctx, n2.SecureSettings, setting.SecretKey)
require.NoError(t, err)
require.Equal(t, ss, decrypted)
// Delete the created alert notification.
delCmd := models.DeleteAlertNotificationCommand{
Id: createCmd.Result.Id,
OrgId: createCmd.Result.OrgId,
Id: n.Id,
OrgId: n.OrgId,
}
err = s.DeleteAlertNotification(context.Background(), &delCmd)
require.NoError(t, err)
@ -135,7 +134,7 @@ func TestService(t *testing.T) {
t.Run("create alert notification should reject an invalid command", func(t *testing.T) {
uid := strings.Repeat("A", 41)
err := s.CreateAlertNotificationCommand(context.Background(), &models.CreateAlertNotificationCommand{Uid: uid})
_, err := s.CreateAlertNotificationCommand(context.Background(), &models.CreateAlertNotificationCommand{Uid: uid})
require.ErrorIs(t, err, ValidationError{Reason: "Invalid UID: Must be 40 characters or less"})
})
@ -145,10 +144,10 @@ func TestService(t *testing.T) {
uid := strings.Repeat("A", 41)
expectedErr := ValidationError{Reason: "Invalid UID: Must be 40 characters or less"}
err := s.UpdateAlertNotification(ctx, &models.UpdateAlertNotificationCommand{Uid: uid})
_, err := s.UpdateAlertNotification(ctx, &models.UpdateAlertNotificationCommand{Uid: uid})
require.ErrorIs(t, err, expectedErr)
err = s.UpdateAlertNotificationWithUid(ctx, &models.UpdateAlertNotificationWithUidCommand{NewUid: uid})
_, err = s.UpdateAlertNotificationWithUid(ctx, &models.UpdateAlertNotificationWithUidCommand{NewUid: uid})
require.ErrorIs(t, err, expectedErr)
})
}

View File

@ -19,16 +19,16 @@ import (
// AlertStore is a subset of SQLStore API to satisfy the needs of the alerting service.
// A subset is needed to make it easier to mock during the tests.
type AlertStore interface {
GetAlertById(context.Context, *alertmodels.GetAlertByIdQuery) error
GetAllAlertQueryHandler(context.Context, *alertmodels.GetAllAlertsQuery) error
GetAlertStatesForDashboard(context.Context, *alertmodels.GetAlertStatesForDashboardQuery) error
HandleAlertsQuery(context.Context, *alertmodels.GetAlertsQuery) error
GetAlertById(context.Context, *alertmodels.GetAlertByIdQuery) (*alertmodels.Alert, error)
GetAllAlertQueryHandler(context.Context, *alertmodels.GetAllAlertsQuery) ([]*alertmodels.Alert, error)
GetAlertStatesForDashboard(context.Context, *alertmodels.GetAlertStatesForDashboardQuery) ([]*alertmodels.AlertStateInfoDTO, error)
HandleAlertsQuery(context.Context, *alertmodels.GetAlertsQuery) ([]*alertmodels.AlertListItemDTO, error)
SetAlertNotificationStateToCompleteCommand(context.Context, *alertmodels.SetAlertNotificationStateToCompleteCommand) error
SetAlertNotificationStateToPendingCommand(context.Context, *alertmodels.SetAlertNotificationStateToPendingCommand) error
GetAlertNotificationUidWithId(context.Context, *alertmodels.GetAlertNotificationUidQuery) error
GetAlertNotificationsWithUidToSend(context.Context, *alertmodels.GetAlertNotificationsWithUidToSendQuery) error
GetOrCreateAlertNotificationState(context.Context, *alertmodels.GetOrCreateNotificationStateQuery) error
SetAlertState(context.Context, *alertmodels.SetAlertStateCommand) error
GetAlertNotificationUidWithId(context.Context, *alertmodels.GetAlertNotificationUidQuery) (string, error)
GetAlertNotificationsWithUidToSend(context.Context, *alertmodels.GetAlertNotificationsWithUidToSendQuery) ([]*alertmodels.AlertNotification, error)
GetOrCreateAlertNotificationState(context.Context, *alertmodels.GetOrCreateNotificationStateQuery) (*alertmodels.AlertNotificationState, error)
SetAlertState(context.Context, *alertmodels.SetAlertStateCommand) (alertmodels.Alert, error)
PauseAlert(context.Context, *alertmodels.PauseAlertCommand) error
PauseAllAlerts(context.Context, *alertmodels.PauseAllAlertCommand) error
}
@ -53,8 +53,8 @@ func ProvideAlertStore(
}
}
func (ss *sqlStore) GetAlertById(ctx context.Context, query *alertmodels.GetAlertByIdQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) GetAlertById(ctx context.Context, query *alertmodels.GetAlertByIdQuery) (res *alertmodels.Alert, err error) {
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
alert := alertmodels.Alert{}
has, err := sess.ID(query.Id).Get(&alert)
if !has {
@ -64,22 +64,24 @@ func (ss *sqlStore) GetAlertById(ctx context.Context, query *alertmodels.GetAler
return err
}
query.Result = &alert
res = &alert
return nil
})
return res, err
}
func (ss *sqlStore) GetAllAlertQueryHandler(ctx context.Context, query *alertmodels.GetAllAlertsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) GetAllAlertQueryHandler(ctx context.Context, query *alertmodels.GetAllAlertsQuery) (res []*alertmodels.Alert, err error) {
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var alerts []*alertmodels.Alert
err := sess.SQL("select * from alert").Find(&alerts)
if err != nil {
return err
}
query.Result = alerts
res = alerts
return nil
})
return res, err
}
func deleteAlertByIdInternal(alertId int64, reason string, sess *db.Session, log *log.ConcreteLogger) error {
@ -104,8 +106,8 @@ func deleteAlertByIdInternal(alertId int64, reason string, sess *db.Session, log
return nil
}
func (ss *sqlStore) HandleAlertsQuery(ctx context.Context, query *alertmodels.GetAlertsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) HandleAlertsQuery(ctx context.Context, query *alertmodels.GetAlertsQuery) (res []*alertmodels.AlertListItemDTO, err error) {
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
builder := db.NewSqlBuilder(ss.cfg, ss.db.GetDialect())
builder.Write(`SELECT
@ -179,9 +181,10 @@ func (ss *sqlStore) HandleAlertsQuery(ctx context.Context, query *alertmodels.Ge
}
}
query.Result = alerts
res = alerts
return nil
})
return res, err
}
func (ss *sqlStore) SaveAlerts(ctx context.Context, dashID int64, alerts []*alertmodels.Alert) error {
@ -297,8 +300,8 @@ func GetAlertsByDashboardId2(dashboardId int64, sess *db.Session) ([]*alertmodel
return alerts, nil
}
func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *alertmodels.SetAlertStateCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *alertmodels.SetAlertStateCommand) (res alertmodels.Alert, err error) {
err = ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
alert := alertmodels.Alert{}
if has, err := sess.ID(cmd.AlertId).Get(&alert); err != nil {
@ -331,9 +334,10 @@ func (ss *sqlStore) SetAlertState(ctx context.Context, cmd *alertmodels.SetAlert
return err
}
cmd.Result = alert
res = alert
return nil
})
return res, err
}
func (ss *sqlStore) PauseAlert(ctx context.Context, cmd *alertmodels.PauseAlertCommand) error {
@ -388,8 +392,8 @@ func (ss *sqlStore) PauseAllAlerts(ctx context.Context, cmd *alertmodels.PauseAl
})
}
func (ss *sqlStore) GetAlertStatesForDashboard(ctx context.Context, query *alertmodels.GetAlertStatesForDashboardQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) GetAlertStatesForDashboard(ctx context.Context, query *alertmodels.GetAlertStatesForDashboardQuery) (res []*alertmodels.AlertStateInfoDTO, err error) {
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var rawSQL = `SELECT
id,
dashboard_id,
@ -399,9 +403,8 @@ func (ss *sqlStore) GetAlertStatesForDashboard(ctx context.Context, query *alert
FROM alert
WHERE org_id = ? AND dashboard_id = ?`
query.Result = make([]*alertmodels.AlertStateInfoDTO, 0)
err := sess.SQL(rawSQL, query.OrgId, query.DashboardId).Find(&query.Result)
return err
res = make([]*alertmodels.AlertStateInfoDTO, 0)
return sess.SQL(rawSQL, query.OrgId, query.DashboardId).Find(&res)
})
return res, err
}

View File

@ -16,17 +16,17 @@ import (
type AlertNotificationStore interface {
DeleteAlertNotification(ctx context.Context, cmd *models.DeleteAlertNotificationCommand) error
DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) error
GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) error
GetAlertNotificationUidWithId(ctx context.Context, query *models.GetAlertNotificationUidQuery) error
GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) error
GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) error
GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error
CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) error
UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) error
UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) error
GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) (*models.AlertNotification, error)
GetAlertNotificationUidWithId(ctx context.Context, query *models.GetAlertNotificationUidQuery) (string, error)
GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) (*models.AlertNotification, error)
GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) ([]*models.AlertNotification, error)
GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) ([]*models.AlertNotification, error)
CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) (*models.AlertNotification, error)
UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) (*models.AlertNotification, error)
UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) (*models.AlertNotification, error)
SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error
SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToPendingCommand) error
GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) error
GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) (*models.AlertNotificationState, error)
}
// timeNow makes it possible to test usage of time
@ -56,79 +56,80 @@ func (ss *sqlStore) DeleteAlertNotification(ctx context.Context, cmd *models.Del
})
}
func (ss *sqlStore) DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) error {
existingNotification := &models.GetAlertNotificationsWithUidQuery{OrgId: cmd.OrgId, Uid: cmd.Uid}
if err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationWithUidInternal(ctx, existingNotification, sess)
func (ss *sqlStore) DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) (err error) {
var res *models.AlertNotification
if err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
existingNotification := &models.GetAlertNotificationsWithUidQuery{OrgId: cmd.OrgId, Uid: cmd.Uid}
res, err = getAlertNotificationWithUidInternal(ctx, existingNotification, sess)
return err
}); err != nil {
return err
}
if existingNotification.Result == nil {
if res == nil {
return models.ErrAlertNotificationNotFound
}
cmd.DeletedAlertNotificationId = existingNotification.Result.Id
cmd.DeletedAlertNotificationId = res.Id
deleteCommand := &models.DeleteAlertNotificationCommand{
Id: existingNotification.Result.Id,
OrgId: existingNotification.Result.OrgId,
Id: res.Id,
OrgId: res.OrgId,
}
if err := ss.DeleteAlertNotification(ctx, deleteCommand); err != nil {
return ss.DeleteAlertNotification(ctx, deleteCommand)
}
func (ss *sqlStore) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) (res *models.AlertNotification, err error) {
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
res, err = getAlertNotificationInternal(ctx, query, sess)
return err
}
return nil
}
func (ss *sqlStore) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationInternal(ctx, query, sess)
})
return res, err
}
func (ss *sqlStore) GetAlertNotificationUidWithId(ctx context.Context, query *models.GetAlertNotificationUidQuery) error {
func (ss *sqlStore) GetAlertNotificationUidWithId(ctx context.Context, query *models.GetAlertNotificationUidQuery) (res string, err error) {
cacheKey := newAlertNotificationUidCacheKey(query.OrgId, query.Id)
if cached, found := ss.cache.Get(cacheKey); found {
query.Result = cached.(string)
return nil
return cached.(string), nil
}
if err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationUidInternal(ctx, query, sess)
}); err != nil {
res, err = getAlertNotificationUidInternal(ctx, query, sess)
return err
}); err != nil {
return "", err
}
ss.cache.Set(cacheKey, query.Result, -1) // Infinite, never changes
return nil
ss.cache.Set(cacheKey, res, -1) // Infinite, never changes
return res, nil
}
func newAlertNotificationUidCacheKey(orgID, notificationId int64) string {
return fmt.Sprintf("notification-uid-by-org-%d-and-id-%d", orgID, notificationId)
}
func (ss *sqlStore) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationWithUidInternal(ctx, query, sess)
func (ss *sqlStore) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) (res *models.AlertNotification, err error) {
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
res, err = getAlertNotificationWithUidInternal(ctx, query, sess)
return err
})
return res, err
}
func (ss *sqlStore) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
results := make([]*models.AlertNotification, 0)
if err := sess.Where("org_id = ?", query.OrgId).Asc("name").Find(&results); err != nil {
func (ss *sqlStore) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) (res []*models.AlertNotification, err error) {
res = make([]*models.AlertNotification, 0)
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
if err := sess.Where("org_id = ?", query.OrgId).Asc("name").Find(&res); err != nil {
return err
}
query.Result = results
return nil
})
return res, err
}
func (ss *sqlStore) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error {
return ss.db.WithDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) (res []*models.AlertNotification, err error) {
res = make([]*models.AlertNotification, 0)
err = ss.db.WithDbSession(ctx, func(sess *db.Session) error {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -163,17 +164,12 @@ func (ss *sqlStore) GetAlertNotificationsWithUidToSend(ctx context.Context, quer
}
sql.WriteString(`)`)
results := make([]*models.AlertNotification, 0)
if err := sess.SQL(sql.String(), params...).Find(&results); err != nil {
return err
}
query.Result = results
return nil
return sess.SQL(sql.String(), params...).Find(&res)
})
return res, err
}
func getAlertNotificationUidInternal(ctx context.Context, query *models.GetAlertNotificationUidQuery, sess *db.Session) error {
func getAlertNotificationUidInternal(ctx context.Context, query *models.GetAlertNotificationUidQuery, sess *db.Session) (res string, err error) {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -190,19 +186,18 @@ func getAlertNotificationUidInternal(ctx context.Context, query *models.GetAlert
results := make([]string, 0)
if err := sess.SQL(sql.String(), params...).Find(&results); err != nil {
return err
return "", err
}
if len(results) == 0 {
return models.ErrAlertNotificationFailedTranslateUniqueID
return "", models.ErrAlertNotificationFailedTranslateUniqueID
}
query.Result = results[0]
return nil
res = results[0]
return res, nil
}
func getAlertNotificationInternal(ctx context.Context, query *models.GetAlertNotificationsQuery, sess *db.Session) error {
func getAlertNotificationInternal(ctx context.Context, query *models.GetAlertNotificationsQuery, sess *db.Session) (res *models.AlertNotification, err error) {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -240,19 +235,16 @@ func getAlertNotificationInternal(ctx context.Context, query *models.GetAlertNot
results := make([]*models.AlertNotification, 0)
if err := sess.SQL(sql.String(), params...).Find(&results); err != nil {
return err
return nil, err
}
if len(results) == 0 {
query.Result = nil
} else {
query.Result = results[0]
return nil, nil
}
return nil
return results[0], nil
}
func getAlertNotificationWithUidInternal(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery, sess *db.Session) error {
func getAlertNotificationWithUidInternal(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery, sess *db.Session) (res *models.AlertNotification, err error) {
var sql bytes.Buffer
params := make([]interface{}, 0)
@ -278,20 +270,17 @@ func getAlertNotificationWithUidInternal(ctx context.Context, query *models.GetA
results := make([]*models.AlertNotification, 0)
if err := sess.SQL(sql.String(), params...).Find(&results); err != nil {
return err
return nil, err
}
if len(results) == 0 {
query.Result = nil
} else {
query.Result = results[0]
return nil, nil
}
return nil
return results[0], nil
}
func (ss *sqlStore) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) (res *models.AlertNotification, err error) {
err = ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
if cmd.Uid == "" {
uid, uidGenerationErr := generateNewAlertNotificationUid(ctx, sess, cmd.OrgId)
if uidGenerationErr != nil {
@ -301,23 +290,17 @@ func (ss *sqlStore) CreateAlertNotificationCommand(ctx context.Context, cmd *mod
cmd.Uid = uid
}
existingQuery := &models.GetAlertNotificationsWithUidQuery{OrgId: cmd.OrgId, Uid: cmd.Uid}
err := getAlertNotificationWithUidInternal(ctx, existingQuery, sess)
if err != nil {
if notification, err := getAlertNotificationWithUidInternal(ctx, existingQuery, sess); err != nil {
return err
}
if existingQuery.Result != nil {
} else if notification != nil {
return models.ErrAlertNotificationWithSameUIDExists
}
// check if name exists
sameNameQuery := &models.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
if err := getAlertNotificationInternal(ctx, sameNameQuery, sess); err != nil {
if notification, err := getAlertNotificationInternal(ctx, sameNameQuery, sess); err != nil {
return err
}
if sameNameQuery.Result != nil {
} else if notification != nil {
return models.ErrAlertNotificationWithSameNameExists
}
@ -359,9 +342,10 @@ func (ss *sqlStore) CreateAlertNotificationCommand(ctx context.Context, cmd *mod
return err
}
cmd.Result = alertNotification
res = alertNotification
return nil
})
return res, err
}
func generateNewAlertNotificationUid(ctx context.Context, sess *db.Session, orgId int64) (string, error) {
@ -380,8 +364,8 @@ func generateNewAlertNotificationUid(ctx context.Context, sess *db.Session, orgI
return "", models.ErrAlertNotificationFailedGenerateUniqueUid
}
func (ss *sqlStore) UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) (err error) {
func (ss *sqlStore) UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) (res *models.AlertNotification, err error) {
err = ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) (err error) {
current := models.AlertNotification{}
if _, err = sess.ID(cmd.Id).Get(&current); err != nil {
@ -394,11 +378,12 @@ func (ss *sqlStore) UpdateAlertNotification(ctx context.Context, cmd *models.Upd
// check if name exists
sameNameQuery := &models.GetAlertNotificationsQuery{OrgId: cmd.OrgId, Name: cmd.Name}
if err := getAlertNotificationInternal(ctx, sameNameQuery, sess); err != nil {
notification, err := getAlertNotificationInternal(ctx, sameNameQuery, sess)
if err != nil {
return err
}
if sameNameQuery.Result != nil && sameNameQuery.Result.Id != current.Id {
if notification != nil && notification.Id != current.Id {
return fmt.Errorf("alert notification name %q already exists", cmd.Name)
}
@ -443,24 +428,25 @@ func (ss *sqlStore) UpdateAlertNotification(ctx context.Context, cmd *models.Upd
return fmt.Errorf("could not update alert notification")
}
cmd.Result = &current
res = &current
return nil
})
return res, err
}
func (ss *sqlStore) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) error {
func (ss *sqlStore) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) (res *models.AlertNotification, err error) {
getAlertNotificationWithUidQuery := &models.GetAlertNotificationsWithUidQuery{OrgId: cmd.OrgId, Uid: cmd.Uid}
if err := ss.db.WithDbSession(ctx, func(sess *db.Session) error {
return getAlertNotificationWithUidInternal(ctx, getAlertNotificationWithUidQuery, sess)
}); err != nil {
res, err = getAlertNotificationWithUidInternal(ctx, getAlertNotificationWithUidQuery, sess)
return err
}); err != nil {
return nil, err
}
current := getAlertNotificationWithUidQuery.Result
current := res
if current == nil {
return models.ErrAlertNotificationNotFound
return nil, models.ErrAlertNotificationNotFound
}
if cmd.NewUid == "" {
@ -482,13 +468,7 @@ func (ss *sqlStore) UpdateAlertNotificationWithUid(ctx context.Context, cmd *mod
OrgId: cmd.OrgId,
}
if err := ss.UpdateAlertNotification(ctx, updateNotification); err != nil {
return err
}
cmd.Result = updateNotification.Result
return nil
return ss.UpdateAlertNotification(ctx, updateNotification)
}
func (ss *sqlStore) SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error {
@ -556,8 +536,8 @@ func (ss *sqlStore) SetAlertNotificationStateToPendingCommand(ctx context.Contex
})
}
func (ss *sqlStore) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) error {
return ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
func (ss *sqlStore) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) (res *models.AlertNotificationState, err error) {
err = ss.db.WithTransactionalDbSession(ctx, func(sess *db.Session) error {
nj := &models.AlertNotificationState{}
exist, err := getAlertNotificationState(ctx, sess, cmd, nj)
@ -568,7 +548,7 @@ func (ss *sqlStore) GetOrCreateAlertNotificationState(ctx context.Context, cmd *
}
if exist {
cmd.Result = nj
res = nj
return nil
}
@ -592,16 +572,17 @@ func (ss *sqlStore) GetOrCreateAlertNotificationState(ctx context.Context, cmd *
return errors.New("should not happen")
}
cmd.Result = nj
res = nj
return nil
}
return err
}
cmd.Result = notificationState
res = notificationState
return nil
})
return res, err
}
func getAlertNotificationState(ctx context.Context, sess *db.Session, cmd *models.GetOrCreateNotificationStateQuery, nj *models.AlertNotificationState) (bool, error) {

View File

@ -41,24 +41,24 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
t.Run("Get no existing state should create a new state", func(t *testing.T) {
query := &models.GetOrCreateNotificationStateQuery{AlertId: alertID, OrgId: orgID, NotifierId: notifierID}
err := store.GetOrCreateAlertNotificationState(context.Background(), query)
res, err := store.GetOrCreateAlertNotificationState(context.Background(), query)
require.Nil(t, err)
require.NotNil(t, query.Result)
require.Equal(t, models.AlertNotificationStateUnknown, query.Result.State)
require.Equal(t, int64(0), query.Result.Version)
require.Equal(t, now.Unix(), query.Result.UpdatedAt)
require.NotNil(t, res)
require.Equal(t, models.AlertNotificationStateUnknown, res.State)
require.Equal(t, int64(0), res.Version)
require.Equal(t, now.Unix(), res.UpdatedAt)
t.Run("Get existing state should not create a new state", func(t *testing.T) {
query2 := &models.GetOrCreateNotificationStateQuery{AlertId: alertID, OrgId: orgID, NotifierId: notifierID}
err := store.GetOrCreateAlertNotificationState(context.Background(), query2)
res2, err := store.GetOrCreateAlertNotificationState(context.Background(), query2)
require.Nil(t, err)
require.NotNil(t, query2.Result)
require.Equal(t, query.Result.Id, query2.Result.Id)
require.Equal(t, now.Unix(), query2.Result.UpdatedAt)
require.NotNil(t, res2)
require.Equal(t, res.Id, res2.Id)
require.Equal(t, now.Unix(), res2.UpdatedAt)
})
t.Run("Update existing state to pending with correct version should update database", func(t *testing.T) {
s := *query.Result
s := *res
cmd := models.SetAlertNotificationStateToPendingCommand{
Id: s.Id,
@ -71,14 +71,14 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
require.Equal(t, int64(1), cmd.ResultVersion)
query2 := &models.GetOrCreateNotificationStateQuery{AlertId: alertID, OrgId: orgID, NotifierId: notifierID}
err = store.GetOrCreateAlertNotificationState(context.Background(), query2)
res2, err := store.GetOrCreateAlertNotificationState(context.Background(), query2)
require.Nil(t, err)
require.Equal(t, int64(1), query2.Result.Version)
require.Equal(t, models.AlertNotificationStatePending, query2.Result.State)
require.Equal(t, now.Unix(), query2.Result.UpdatedAt)
require.Equal(t, int64(1), res2.Version)
require.Equal(t, models.AlertNotificationStatePending, res2.State)
require.Equal(t, now.Unix(), res2.UpdatedAt)
t.Run("Update existing state to completed should update database", func(t *testing.T) {
s := *query.Result
s := *res
setStateCmd := models.SetAlertNotificationStateToCompleteCommand{
Id: s.Id,
Version: cmd.ResultVersion,
@ -87,15 +87,15 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
require.Nil(t, err)
query3 := &models.GetOrCreateNotificationStateQuery{AlertId: alertID, OrgId: orgID, NotifierId: notifierID}
err = store.GetOrCreateAlertNotificationState(context.Background(), query3)
res3, err := store.GetOrCreateAlertNotificationState(context.Background(), query3)
require.Nil(t, err)
require.Equal(t, int64(2), query3.Result.Version)
require.Equal(t, models.AlertNotificationStateCompleted, query3.Result.State)
require.Equal(t, now.Unix(), query3.Result.UpdatedAt)
require.Equal(t, int64(2), res3.Version)
require.Equal(t, models.AlertNotificationStateCompleted, res3.State)
require.Equal(t, now.Unix(), res3.UpdatedAt)
})
t.Run("Update existing state to completed should update database. regardless of version", func(t *testing.T) {
s := *query.Result
s := *res
unknownVersion := int64(1000)
cmd := models.SetAlertNotificationStateToCompleteCommand{
Id: s.Id,
@ -105,16 +105,16 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
require.Nil(t, err)
query3 := &models.GetOrCreateNotificationStateQuery{AlertId: alertID, OrgId: orgID, NotifierId: notifierID}
err = store.GetOrCreateAlertNotificationState(context.Background(), query3)
res3, err := store.GetOrCreateAlertNotificationState(context.Background(), query3)
require.Nil(t, err)
require.Equal(t, unknownVersion+1, query3.Result.Version)
require.Equal(t, models.AlertNotificationStateCompleted, query3.Result.State)
require.Equal(t, now.Unix(), query3.Result.UpdatedAt)
require.Equal(t, unknownVersion+1, res3.Version)
require.Equal(t, models.AlertNotificationStateCompleted, res3.State)
require.Equal(t, now.Unix(), res3.UpdatedAt)
})
})
t.Run("Update existing state to pending with incorrect version should return version mismatch error", func(t *testing.T) {
s := *query.Result
s := *res
s.Version = 1000
cmd := models.SetAlertNotificationStateToPendingCommand{
Id: s.NotifierId,
@ -126,7 +126,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
})
t.Run("Updating existing state to pending with incorrect version since alert rule state update version is higher", func(t *testing.T) {
s := *query.Result
s := *res
cmd := models.SetAlertNotificationStateToPendingCommand{
Id: s.Id,
Version: s.Version,
@ -139,7 +139,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
})
t.Run("different version and same alert state change version should return error", func(t *testing.T) {
s := *query.Result
s := *res
s.Version = 1000
cmd := models.SetAlertNotificationStateToPendingCommand{
Id: s.Id,
@ -159,9 +159,9 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Name: "email",
}
err := store.GetAlertNotifications(context.Background(), cmd)
res, err := store.GetAlertNotifications(context.Background(), cmd)
require.Nil(t, err)
require.Nil(t, cmd.Result)
require.Nil(t, res)
})
t.Run("Cannot save alert notifier with send reminder = true", func(t *testing.T) {
@ -175,13 +175,13 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
}
t.Run("and missing frequency", func(t *testing.T) {
err := store.CreateAlertNotificationCommand(context.Background(), cmd)
_, err := store.CreateAlertNotificationCommand(context.Background(), cmd)
require.Equal(t, models.ErrNotificationFrequencyNotFound, err)
})
t.Run("invalid frequency", func(t *testing.T) {
cmd.Frequency = "invalid duration"
err := store.CreateAlertNotificationCommand(context.Background(), cmd)
_, err := store.CreateAlertNotificationCommand(context.Background(), cmd)
require.True(t, regexp.MustCompile(`^time: invalid duration "?invalid duration"?$`).MatchString(
err.Error()))
})
@ -197,23 +197,23 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Settings: simplejson.New(),
}
err := store.CreateAlertNotificationCommand(context.Background(), cmd)
res, err := store.CreateAlertNotificationCommand(context.Background(), cmd)
require.Nil(t, err)
updateCmd := &models.UpdateAlertNotificationCommand{
Id: cmd.Result.Id,
Id: res.Id,
SendReminder: true,
}
t.Run("and missing frequency", func(t *testing.T) {
err := store.UpdateAlertNotification(context.Background(), updateCmd)
_, err := store.UpdateAlertNotification(context.Background(), updateCmd)
require.Equal(t, models.ErrNotificationFrequencyNotFound, err)
})
t.Run("invalid frequency", func(t *testing.T) {
updateCmd.Frequency = "invalid duration"
err := store.UpdateAlertNotification(context.Background(), updateCmd)
_, err := store.UpdateAlertNotification(context.Background(), updateCmd)
require.Error(t, err)
require.True(t, regexp.MustCompile(`^time: invalid duration "?invalid duration"?$`).MatchString(
err.Error()))
@ -231,17 +231,17 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Settings: simplejson.New(),
}
err := store.CreateAlertNotificationCommand(context.Background(), cmd)
res, err := store.CreateAlertNotificationCommand(context.Background(), cmd)
require.Nil(t, err)
require.NotEqual(t, 0, cmd.Result.Id)
require.NotEqual(t, 0, cmd.Result.OrgId)
require.Equal(t, "email", cmd.Result.Type)
require.Equal(t, 10*time.Second, cmd.Result.Frequency)
require.False(t, cmd.Result.DisableResolveMessage)
require.NotEmpty(t, cmd.Result.Uid)
require.NotEqual(t, 0, res.Id)
require.NotEqual(t, 0, res.OrgId)
require.Equal(t, "email", res.Type)
require.Equal(t, 10*time.Second, res.Frequency)
require.False(t, res.DisableResolveMessage)
require.NotEmpty(t, res.Uid)
t.Run("Cannot save Alert Notification with the same name", func(t *testing.T) {
err = store.CreateAlertNotificationCommand(context.Background(), cmd)
_, err = store.CreateAlertNotificationCommand(context.Background(), cmd)
require.Error(t, err)
})
t.Run("Cannot save Alert Notification with the same name and another uid", func(t *testing.T) {
@ -254,7 +254,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Settings: cmd.Settings,
Uid: "notifier1",
}
err = store.CreateAlertNotificationCommand(context.Background(), anotherUidCmd)
_, err = store.CreateAlertNotificationCommand(context.Background(), anotherUidCmd)
require.Error(t, err)
})
t.Run("Can save Alert Notification with another name and another uid", func(t *testing.T) {
@ -267,7 +267,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Settings: cmd.Settings,
Uid: "notifier2",
}
err = store.CreateAlertNotificationCommand(context.Background(), anotherUidCmd)
_, err = store.CreateAlertNotificationCommand(context.Background(), anotherUidCmd)
require.Nil(t, err)
})
@ -275,32 +275,32 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
newCmd := &models.UpdateAlertNotificationCommand{
Name: "NewName",
Type: "webhook",
OrgId: cmd.Result.OrgId,
OrgId: res.OrgId,
SendReminder: true,
DisableResolveMessage: true,
Frequency: "60s",
Settings: simplejson.New(),
Id: cmd.Result.Id,
Id: res.Id,
}
err := store.UpdateAlertNotification(context.Background(), newCmd)
newres, err := store.UpdateAlertNotification(context.Background(), newCmd)
require.Nil(t, err)
require.Equal(t, "NewName", newCmd.Result.Name)
require.Equal(t, time.Minute, newCmd.Result.Frequency)
require.True(t, newCmd.Result.DisableResolveMessage)
require.Equal(t, "NewName", newres.Name)
require.Equal(t, time.Minute, newres.Frequency)
require.True(t, newres.DisableResolveMessage)
})
t.Run("Can update alert notification to disable sending of reminders", func(t *testing.T) {
newCmd := &models.UpdateAlertNotificationCommand{
Name: "NewName",
Type: "webhook",
OrgId: cmd.Result.OrgId,
OrgId: res.OrgId,
SendReminder: false,
Settings: simplejson.New(),
Id: cmd.Result.Id,
Id: res.Id,
}
err := store.UpdateAlertNotification(context.Background(), newCmd)
newres, err := store.UpdateAlertNotification(context.Background(), newCmd)
require.Nil(t, err)
require.False(t, newCmd.Result.SendReminder)
require.False(t, newres.SendReminder)
})
})
@ -313,21 +313,26 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
otherOrg := models.CreateAlertNotificationCommand{Name: "default", Type: "email", OrgId: 2, SendReminder: true, Frequency: "10s", Settings: simplejson.New()}
require.Nil(t, store.CreateAlertNotificationCommand(context.Background(), &cmd1))
require.Nil(t, store.CreateAlertNotificationCommand(context.Background(), &cmd2))
require.Nil(t, store.CreateAlertNotificationCommand(context.Background(), &cmd3))
require.Nil(t, store.CreateAlertNotificationCommand(context.Background(), &cmd4))
require.Nil(t, store.CreateAlertNotificationCommand(context.Background(), &otherOrg))
res1, err := store.CreateAlertNotificationCommand(context.Background(), &cmd1)
require.NoError(t, err)
res2, err := store.CreateAlertNotificationCommand(context.Background(), &cmd2)
require.NoError(t, err)
_, err = store.CreateAlertNotificationCommand(context.Background(), &cmd3)
require.NoError(t, err)
_, err = store.CreateAlertNotificationCommand(context.Background(), &cmd4)
require.NoError(t, err)
_, err = store.CreateAlertNotificationCommand(context.Background(), &otherOrg)
require.NoError(t, err)
t.Run("search", func(t *testing.T) {
query := &models.GetAlertNotificationsWithUidToSendQuery{
Uids: []string{cmd1.Result.Uid, cmd2.Result.Uid, "112341231"},
Uids: []string{res1.Uid, res2.Uid, "112341231"},
OrgId: 1,
}
err := store.GetAlertNotificationsWithUidToSend(context.Background(), query)
res, err := store.GetAlertNotificationsWithUidToSend(context.Background(), query)
require.Nil(t, err)
require.Equal(t, 3, len(query.Result))
require.Equal(t, 3, len(res))
})
t.Run("all", func(t *testing.T) {
@ -335,13 +340,13 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
OrgId: 1,
}
err := store.GetAllAlertNotifications(context.Background(), query)
res, err := store.GetAllAlertNotifications(context.Background(), query)
require.Nil(t, err)
require.Equal(t, 4, len(query.Result))
require.Equal(t, cmd4.Name, query.Result[0].Name)
require.Equal(t, cmd1.Name, query.Result[1].Name)
require.Equal(t, cmd3.Name, query.Result[2].Name)
require.Equal(t, cmd2.Name, query.Result[3].Name)
require.Equal(t, 4, len(res))
require.Equal(t, cmd4.Name, res[0].Name)
require.Equal(t, cmd1.Name, res[1].Name)
require.Equal(t, cmd3.Name, res[2].Name)
require.Equal(t, cmd2.Name, res[3].Name)
})
})
@ -349,7 +354,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
setup()
notification := &models.CreateAlertNotificationCommand{Uid: "aNotificationUid", OrgId: 1, Name: "aNotificationUid"}
err := store.CreateAlertNotificationCommand(context.Background(), notification)
_, err := store.CreateAlertNotificationCommand(context.Background(), notification)
require.Nil(t, err)
byUidQuery := &models.GetAlertNotificationsWithUidQuery{
@ -357,13 +362,13 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
OrgId: notification.OrgId,
}
notificationByUidErr := store.GetAlertNotificationsWithUid(context.Background(), byUidQuery)
res, notificationByUidErr := store.GetAlertNotificationsWithUid(context.Background(), byUidQuery)
require.Nil(t, notificationByUidErr)
t.Run("Can cache notification Uid", func(t *testing.T) {
byIdQuery := &models.GetAlertNotificationUidQuery{
Id: byUidQuery.Result.Id,
OrgId: byUidQuery.Result.OrgId,
Id: res.Id,
OrgId: res.OrgId,
}
cacheKey := newAlertNotificationUidCacheKey(byIdQuery.OrgId, byIdQuery.Id)
@ -372,7 +377,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
require.False(t, foundBeforeCaching)
require.Nil(t, resultBeforeCaching)
notificationByIdErr := store.GetAlertNotificationUidWithId(context.Background(), byIdQuery)
_, notificationByIdErr := store.GetAlertNotificationUidWithId(context.Background(), byIdQuery)
require.Nil(t, notificationByIdErr)
resultAfterCaching, foundAfterCaching := store.cache.Get(cacheKey)
@ -388,9 +393,9 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
cacheKey := newAlertNotificationUidCacheKey(query.OrgId, query.Id)
store.cache.Set(cacheKey, "a-cached-uid", -1)
err := store.GetAlertNotificationUidWithId(context.Background(), query)
res, err := store.GetAlertNotificationUidWithId(context.Background(), query)
require.Nil(t, err)
require.Equal(t, "a-cached-uid", query.Result)
require.Equal(t, "a-cached-uid", res)
})
t.Run("Returns an error without populating cache when the notification doesn't exist in the database", func(t *testing.T) {
@ -399,8 +404,8 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
OrgId: 100,
}
err := store.GetAlertNotificationUidWithId(context.Background(), query)
require.Equal(t, "", query.Result)
res, err := store.GetAlertNotificationUidWithId(context.Background(), query)
require.Equal(t, "", res)
require.Error(t, err)
require.True(t, errors.Is(err, models.ErrAlertNotificationFailedTranslateUniqueID))
@ -423,7 +428,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Settings: simplejson.New(),
Id: 1,
}
err := store.UpdateAlertNotification(context.Background(), updateCmd)
_, err := store.UpdateAlertNotification(context.Background(), updateCmd)
require.Equal(t, models.ErrAlertNotificationNotFound, err)
t.Run("using UID", func(t *testing.T) {
@ -438,7 +443,7 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Uid: "uid",
NewUid: "newUid",
}
err := store.UpdateAlertNotificationWithUid(context.Background(), updateWithUidCmd)
_, err := store.UpdateAlertNotificationWithUid(context.Background(), updateWithUidCmd)
require.Equal(t, models.ErrAlertNotificationNotFound, err)
})
})
@ -453,28 +458,28 @@ func TestIntegrationAlertNotificationSQLAccess(t *testing.T) {
Settings: simplejson.New(),
}
err := store.CreateAlertNotificationCommand(context.Background(), cmd)
res, err := store.CreateAlertNotificationCommand(context.Background(), cmd)
require.Nil(t, err)
deleteCmd := &models.DeleteAlertNotificationCommand{
Id: cmd.Result.Id,
Id: res.Id,
OrgId: 1,
}
err = store.DeleteAlertNotification(context.Background(), deleteCmd)
require.Nil(t, err)
t.Run("using UID", func(t *testing.T) {
err := store.CreateAlertNotificationCommand(context.Background(), cmd)
res, err := store.CreateAlertNotificationCommand(context.Background(), cmd)
require.Nil(t, err)
deleteWithUidCmd := &models.DeleteAlertNotificationWithUidCommand{
Uid: cmd.Result.Uid,
Uid: res.Uid,
OrgId: 1,
}
err = store.DeleteAlertNotificationWithUid(context.Background(), deleteWithUidCmd)
require.Nil(t, err)
require.Equal(t, cmd.Result.Id, deleteWithUidCmd.DeletedAlertNotificationId)
require.Equal(t, res.Id, deleteWithUidCmd.DeletedAlertNotificationId)
})
})

View File

@ -82,10 +82,10 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
// Get alert so we can use its ID in tests
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
result, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
require.Nil(t, err2)
insertedAlert := alertQuery.Result[0]
insertedAlert := result[0]
t.Run("new state ok", func(t *testing.T) {
cmd := &models.SetAlertStateCommand{
@ -93,7 +93,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
State: models.AlertStateOK,
}
err := store.SetAlertState(context.Background(), cmd)
_, err := store.SetAlertState(context.Background(), cmd)
require.Nil(t, err)
})
@ -110,7 +110,7 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
State: models.AlertStateOK,
}
err = store.SetAlertState(context.Background(), cmd)
_, err = store.SetAlertState(context.Background(), cmd)
require.Error(t, err)
})
@ -139,9 +139,9 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
t.Run("Can read properties", func(t *testing.T) {
setup(t)
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
result, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
alert := alertQuery.Result[0]
alert := result[0]
require.Nil(t, err2)
require.Greater(t, alert.Id, int64(0))
require.Equal(t, testDash.ID, alert.DashboardId)
@ -161,10 +161,10 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
setup(t)
viewerUser := &user.SignedInUser{OrgRole: org.RoleViewer, OrgID: 1}
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: viewerUser}
err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
res, err2 := store.HandleAlertsQuery(context.Background(), &alertQuery)
require.Nil(t, err2)
require.Equal(t, 1, len(alertQuery.Result))
require.Equal(t, 1, len(res))
})
t.Run("Alerts with same dashboard id and panel id should update", func(t *testing.T) {
@ -180,14 +180,14 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
t.Run("Alerts should be updated", func(t *testing.T) {
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &query)
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
require.Nil(t, err2)
require.Equal(t, 1, len(query.Result))
require.Equal(t, "Name", query.Result[0].Name)
require.Equal(t, 1, len(res))
require.Equal(t, "Name", res[0].Name)
t.Run("Alert state should not be updated", func(t *testing.T) {
require.Equal(t, models.AlertStateUnknown, query.Result[0].State)
require.Equal(t, models.AlertStateUnknown, res[0].State)
})
})
@ -229,10 +229,10 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
require.Nil(t, err)
queryForDashboard := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &queryForDashboard)
res, err2 := store.HandleAlertsQuery(context.Background(), &queryForDashboard)
require.Nil(t, err2)
require.Equal(t, 3, len(queryForDashboard.Result))
require.Equal(t, 3, len(res))
})
t.Run("should updated two dashboards and delete one", func(t *testing.T) {
@ -242,9 +242,9 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
t.Run("should delete the missing alert", func(t *testing.T) {
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &query)
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
require.Nil(t, err2)
require.Equal(t, 2, len(query.Result))
require.Equal(t, 2, len(res))
})
})
})
@ -272,10 +272,10 @@ func TestIntegrationAlertingDataAccess(t *testing.T) {
t.Run("Alerts should be removed", func(t *testing.T) {
query := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := store.HandleAlertsQuery(context.Background(), &query)
res, err2 := store.HandleAlertsQuery(context.Background(), &query)
require.Nil(t, err2)
require.Equal(t, 0, len(query.Result))
require.Equal(t, 0, len(res))
})
})
}
@ -300,10 +300,10 @@ func TestIntegrationPausingAlerts(t *testing.T) {
// Get alert so we can use its ID in tests
alertQuery := models.GetAlertsQuery{DashboardIDs: []int64{testDash.ID}, PanelId: 1, OrgId: 1, User: &user.SignedInUser{OrgRole: org.RoleAdmin}}
err2 := sqlStore.HandleAlertsQuery(context.Background(), &alertQuery)
res, err2 := sqlStore.HandleAlertsQuery(context.Background(), &alertQuery)
require.Nil(t, err2)
insertedAlert := alertQuery.Result[0]
insertedAlert := res[0]
t.Run("when paused", func(t *testing.T) {
_, err := sqlStore.pauseAlert(t, testDash.OrgID, insertedAlert.Id, true)
@ -365,9 +365,9 @@ func getAlertById(t *testing.T, id int64, ss *sqlStore) (*models.Alert, error) {
q := &models.GetAlertByIdQuery{
Id: id,
}
err := ss.GetAlertById(context.Background(), q)
res, err := ss.GetAlertById(context.Background(), q)
require.Nil(t, err)
return q.Result, err
return res, err
}
func (ss *sqlStore) pauseAllAlerts(t *testing.T, pauseState bool) error {

View File

@ -11,18 +11,18 @@ import (
)
type Manager interface {
GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) error
CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) error
UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) error
GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) (*models.AlertNotification, error)
CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) (*models.AlertNotification, error)
UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) (*models.AlertNotification, error)
DeleteAlertNotification(ctx context.Context, cmd *models.DeleteAlertNotificationCommand) error
GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) error
GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) error
GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) ([]*models.AlertNotification, error)
GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) (*models.AlertNotificationState, error)
SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error
SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToPendingCommand) error
GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) error
GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) (*models.AlertNotification, error)
DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) error
GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error
UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) error
GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) ([]*models.AlertNotification, error)
UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) (*models.AlertNotification, error)
}
// Provision alert notifiers
@ -82,12 +82,13 @@ func (dc *NotificationProvisioner) deleteNotifications(ctx context.Context, noti
getNotification := &models.GetAlertNotificationsWithUidQuery{Uid: notification.UID, OrgId: notification.OrgID}
if err := dc.alertingManager.GetAlertNotificationsWithUid(ctx, getNotification); err != nil {
res, err := dc.alertingManager.GetAlertNotificationsWithUid(ctx, getNotification)
if err != nil {
return err
}
if getNotification.Result != nil {
cmd := &models.DeleteAlertNotificationWithUidCommand{Uid: getNotification.Result.Uid, OrgId: getNotification.OrgId}
if res != nil {
cmd := &models.DeleteAlertNotificationWithUidCommand{Uid: res.Uid, OrgId: getNotification.OrgId}
if err := dc.alertingManager.DeleteAlertNotificationWithUid(ctx, cmd); err != nil {
return err
}
@ -111,12 +112,12 @@ func (dc *NotificationProvisioner) mergeNotifications(ctx context.Context, notif
}
cmd := &models.GetAlertNotificationsWithUidQuery{OrgId: notification.OrgID, Uid: notification.UID}
err := dc.alertingManager.GetAlertNotificationsWithUid(ctx, cmd)
res, err := dc.alertingManager.GetAlertNotificationsWithUid(ctx, cmd)
if err != nil {
return err
}
if cmd.Result == nil {
if res == nil {
dc.log.Debug("inserting alert notification from configuration", "name", notification.Name, "uid", notification.UID)
insertCmd := &models.CreateAlertNotificationCommand{
Uid: notification.UID,
@ -131,7 +132,8 @@ func (dc *NotificationProvisioner) mergeNotifications(ctx context.Context, notif
SendReminder: notification.SendReminder,
}
if err := dc.alertingManager.CreateAlertNotificationCommand(ctx, insertCmd); err != nil {
_, err := dc.alertingManager.CreateAlertNotificationCommand(ctx, insertCmd)
if err != nil {
return err
}
} else {
@ -149,7 +151,7 @@ func (dc *NotificationProvisioner) mergeNotifications(ctx context.Context, notif
SendReminder: notification.SendReminder,
}
if err := dc.alertingManager.UpdateAlertNotificationWithUid(ctx, updateCmd); err != nil {
if _, err := dc.alertingManager.UpdateAlertNotificationWithUid(ctx, updateCmd); err != nil {
return err
}
}

View File

@ -168,14 +168,14 @@ func TestNotificationAsConfig(t *testing.T) {
Uid: "notifier1",
Type: "slack",
}
err := ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
res, err := ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
require.NoError(t, err)
require.NotNil(t, existingNotificationCmd.Result)
require.NotNil(t, res)
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = ns.SQLStore.GetAllAlertNotifications(context.Background(), &notificationsQuery)
results, err := ns.SQLStore.GetAllAlertNotifications(context.Background(), &notificationsQuery)
require.NoError(t, err)
require.NotNil(t, notificationsQuery.Result)
require.Equal(t, len(notificationsQuery.Result), 1)
require.NotNil(t, results)
require.Equal(t, len(results), 1)
t.Run("should update one notification", func(t *testing.T) {
dc := newNotificationProvisioner(orgService, &fakeAlertNotification{}, encryptionService, nil, logger)
@ -205,7 +205,7 @@ func TestNotificationAsConfig(t *testing.T) {
Uid: "notifier0",
Type: "slack",
}
err := ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
_, err := ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
require.NoError(t, err)
existingNotificationCmd = models.CreateAlertNotificationCommand{
Name: "channel3",
@ -213,14 +213,14 @@ func TestNotificationAsConfig(t *testing.T) {
Uid: "notifier3",
Type: "slack",
}
err = ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
_, err = ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
require.NoError(t, err)
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = ns.GetAllAlertNotifications(context.Background(), &notificationsQuery)
res, err := ns.GetAllAlertNotifications(context.Background(), &notificationsQuery)
require.NoError(t, err)
require.NotNil(t, notificationsQuery.Result)
require.Equal(t, len(notificationsQuery.Result), 2)
require.NotNil(t, res)
require.Equal(t, len(res), 2)
t.Run("should have two new notifications", func(t *testing.T) {
dc := newNotificationProvisioner(orgService, &fakeAlertNotification{}, encryptionService, nil, logger)
@ -241,7 +241,7 @@ func TestNotificationAsConfig(t *testing.T) {
Uid: "notifier2",
Type: "slack",
}
err := ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
_, err := ns.SQLStore.CreateAlertNotificationCommand(context.Background(), &existingNotificationCmd)
require.NoError(t, err)
dc := newNotificationProvisioner(orgService, &fakeAlertNotification{}, encryptionService, nil, logger)
@ -273,9 +273,9 @@ func TestNotificationAsConfig(t *testing.T) {
t.Fatalf("applyChanges return an error %v", err)
}
notificationsQuery := models.GetAllAlertNotificationsQuery{OrgId: 1}
err = ns.GetAllAlertNotifications(context.Background(), &notificationsQuery)
res, err := ns.GetAllAlertNotifications(context.Background(), &notificationsQuery)
require.NoError(t, err)
require.Empty(t, notificationsQuery.Result)
require.Empty(t, res)
})
})
@ -332,24 +332,23 @@ type fakeAlertNotification struct {
ExpectedAlertNotification *models.AlertNotification
}
func (f *fakeAlertNotification) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) error {
query.Result = f.ExpectedAlertNotification
return nil
func (f *fakeAlertNotification) GetAlertNotifications(ctx context.Context, query *models.GetAlertNotificationsQuery) (*models.AlertNotification, error) {
return f.ExpectedAlertNotification, nil
}
func (f *fakeAlertNotification) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) error {
return nil
func (f *fakeAlertNotification) CreateAlertNotificationCommand(ctx context.Context, cmd *models.CreateAlertNotificationCommand) (*models.AlertNotification, error) {
return nil, nil
}
func (f *fakeAlertNotification) UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) error {
return nil
func (f *fakeAlertNotification) UpdateAlertNotification(ctx context.Context, cmd *models.UpdateAlertNotificationCommand) (*models.AlertNotification, error) {
return nil, nil
}
func (f *fakeAlertNotification) DeleteAlertNotification(ctx context.Context, cmd *models.DeleteAlertNotificationCommand) error {
return nil
}
func (f *fakeAlertNotification) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) error {
return nil
func (f *fakeAlertNotification) GetAllAlertNotifications(ctx context.Context, query *models.GetAllAlertNotificationsQuery) ([]*models.AlertNotification, error) {
return nil, nil
}
func (f *fakeAlertNotification) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) error {
return nil
func (f *fakeAlertNotification) GetOrCreateAlertNotificationState(ctx context.Context, cmd *models.GetOrCreateNotificationStateQuery) (*models.AlertNotificationState, error) {
return nil, nil
}
func (f *fakeAlertNotification) SetAlertNotificationStateToCompleteCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToCompleteCommand) error {
return nil
@ -357,16 +356,16 @@ func (f *fakeAlertNotification) SetAlertNotificationStateToCompleteCommand(ctx c
func (f *fakeAlertNotification) SetAlertNotificationStateToPendingCommand(ctx context.Context, cmd *models.SetAlertNotificationStateToPendingCommand) error {
return nil
}
func (f *fakeAlertNotification) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) error {
return nil
func (f *fakeAlertNotification) GetAlertNotificationsWithUid(ctx context.Context, query *models.GetAlertNotificationsWithUidQuery) (*models.AlertNotification, error) {
return nil, nil
}
func (f *fakeAlertNotification) DeleteAlertNotificationWithUid(ctx context.Context, cmd *models.DeleteAlertNotificationWithUidCommand) error {
return nil
}
func (f *fakeAlertNotification) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) error {
return nil
func (f *fakeAlertNotification) GetAlertNotificationsWithUidToSend(ctx context.Context, query *models.GetAlertNotificationsWithUidToSendQuery) ([]*models.AlertNotification, error) {
return nil, nil
}
func (f *fakeAlertNotification) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) error {
return nil
func (f *fakeAlertNotification) UpdateAlertNotificationWithUid(ctx context.Context, cmd *models.UpdateAlertNotificationWithUidCommand) (*models.AlertNotification, error) {
return nil, nil
}