diff --git a/pkg/services/ngalert/state/historian/annotation.go b/pkg/services/ngalert/state/historian/annotation.go index 2c90d1d9a09..be7318a3879 100644 --- a/pkg/services/ngalert/state/historian/annotation.go +++ b/pkg/services/ngalert/state/historian/annotation.go @@ -62,6 +62,11 @@ func (h *AnnotationBackend) Record(ctx context.Context, rule history_model.RuleM panel := parsePanelKey(rule, logger) errCh := make(chan error, 1) + if len(annotations) == 0 { + close(errCh) + return errCh + } + go func() { defer close(errCh) errCh <- h.recordAnnotations(ctx, panel, annotations, rule.OrgID, logger) @@ -180,10 +185,6 @@ func buildAnnotations(rule history_model.RuleMeta, states []state.StateTransitio } func (h *AnnotationBackend) recordAnnotations(ctx context.Context, panel *panelKey, annotations []annotations.Item, orgID int64, logger log.Logger) error { - if len(annotations) == 0 { - return nil - } - if panel != nil { dashID, err := h.dashboards.getID(ctx, panel.orgID, panel.dashUID) if err != nil { diff --git a/pkg/services/ngalert/state/historian/loki.go b/pkg/services/ngalert/state/historian/loki.go index 2585e667173..047fca0cbad 100644 --- a/pkg/services/ngalert/state/historian/loki.go +++ b/pkg/services/ngalert/state/historian/loki.go @@ -72,7 +72,13 @@ func (h *RemoteLokiBackend) TestConnection(ctx context.Context) error { func (h *RemoteLokiBackend) Record(ctx context.Context, rule history_model.RuleMeta, states []state.StateTransition) <-chan error { logger := h.log.FromContext(ctx) streams := statesToStreams(rule, states, h.externalLabels, logger) + errCh := make(chan error, 1) + if len(streams) == 0 { + close(errCh) + return errCh + } + go func() { defer close(errCh) diff --git a/pkg/services/ngalert/state/historian/loki_test.go b/pkg/services/ngalert/state/historian/loki_test.go index 39f26f1cf2a..11966324933 100644 --- a/pkg/services/ngalert/state/historian/loki_test.go +++ b/pkg/services/ngalert/state/historian/loki_test.go @@ -311,6 +311,18 @@ grafana_alerting_state_history_writes_total{org="1"} 2 ) require.NoError(t, err) }) + + t.Run("elides request if nothing to send", func(t *testing.T) { + req := NewFakeRequester() + loki := createTestLokiBackend(req, metrics.NewHistorianMetrics(prometheus.NewRegistry())) + rule := createTestRule() + states := []state.StateTransition{} + + err := <-loki.Record(context.Background(), rule, states) + + require.NoError(t, err) + require.Nil(t, req.lastRequest) + }) } func createTestLokiBackend(req client.Requester, met *metrics.Historian) *RemoteLokiBackend {