SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
feat(alert-channel-integrations): google chat backend (#12314)
Nikhil Mantrie9726776ab7a
diff --git a/pkg/alertmanager/alertmanagernotify/googlechat/googlechat.go b/pkg/alertmanager/alertmanagernotify/googlechat/googlechat.gonew file mode 100644index 0000000000..25875bf627--- /dev/null+++ b/pkg/alertmanager/alertmanagernotify/googlechat/googlechat.go@@ -0,0 +1,395 @@+package googlechat++import (+ "bytes"+ "context"+ "encoding/json"+ "fmt"+ "log/slog"+ "net/http"+ "net/url"+ "unicode/utf8"++ "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"+ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/templating/markdownrenderer"+ "github.com/SigNoz/signoz/pkg/types/alertmanagertypes"+ "github.com/SigNoz/signoz/pkg/types/ruletypes"+ "github.com/prometheus/alertmanager/notify"+ "github.com/prometheus/alertmanager/template"+ "github.com/prometheus/alertmanager/types"+ "github.com/prometheus/common/model"+)++const (+ Integration = "googlechat"+ // maxMessageBytes is the Google Chat message payload limit.+ // https://developers.google.com/chat/api/guides/message-formats/basic#maximum_size+ maxMessageBytes = 32000+ // maxAlertSections caps per-alert sections in a grouped card. Google Chat+ // allows 100 widgets per card and silently drops the section that crosses+ // that count and every section after it, so we cap well under the limit+ // (~63 widgets worst case) and add a "+N more" note for the overflow.+ // https://developers.google.com/workspace/chat/api/reference/rpc/google.apps.card.v1#card+ maxAlertSections = 30+)++// Notifier implements notify.Notifier for Google Chat.+type Notifier struct {+ conf *alertmanagertypes.GoogleChatReceiverConfig+ tmpl *template.Template+ logger *slog.Logger+ client *http.Client+ retrier *notify.Retrier+ templater alertmanagertypes.Templater+}++// Message is the Google Chat webhook payload. A message carries a short text+// summary (space list / push preview) and a rich card.+type Message struct {+ Text string `json:"text,omitempty"`+ CardsV2 []cardWithID `json:"cardsV2,omitempty"`+}++type cardWithID struct {+ CardID string `json:"cardId"`+ Card card `json:"card"`+}++type card struct {+ Header *cardHeader `json:"header,omitempty"`+ Sections []cardSection `json:"sections"`+}++type cardHeader struct {+ Title string `json:"title,omitempty"`+ Subtitle string `json:"subtitle,omitempty"`+}++type cardSection struct {+ Header string `json:"header,omitempty"`+ Widgets []widget `json:"widgets"`+}++// widget is a one-of: exactly one field is set per instance.+type widget struct {+ TextParagraph *textParagraph `json:"textParagraph,omitempty"`+ ButtonList *buttonList `json:"buttonList,omitempty"`+}++type textParagraph struct {+ Text string `json:"text"`+}++type buttonList struct {+ Buttons []button `json:"buttons"`+}++type button struct {+ Text string `json:"text"`+ OnClick onClick `json:"onClick"`+}++type onClick struct {+ OpenLink openLink `json:"openLink"`+}++type openLink struct {+ URL string `json:"url"`+}++// content holds the rendered title and the HTML bodies for a Google Chat message.+// bodies is per-alert (positionally aligned with the alerts slice) for a custom+// body template, but a single combined entry for the default template.+type content struct {+ title string+ bodies []string+}++func New(conf *alertmanagertypes.GoogleChatReceiverConfig, t *template.Template, l *slog.Logger, templater alertmanagertypes.Templater) (*Notifier, error) {+ if conf.HTTPConfig == nil {+ return nil, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat http_config is nil")+ }+ client, err := notify.NewClientWithTracing(*conf.HTTPConfig, Integration)+ if err != nil {+ return nil, err+ }+ return &Notifier{+ conf: conf,+ tmpl: t,+ logger: l,+ client: client,+ retrier: ¬ify.Retrier{RetryCodes: []int{http.StatusTooManyRequests}},+ templater: templater,+ }, nil+}++func (n *Notifier) Notify(ctx context.Context, alerts ...*types.Alert) (bool, error) {+ if n.conf.WebhookURL == nil {+ return false, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url is empty")+ }++ key, err := notify.ExtractGroupKey(ctx)+ if err != nil {+ return false, err+ }+ n.logger.DebugContext(ctx, "sending google chat notification", slog.Any("group_key", key))++ c, err := n.prepareContent(ctx, alerts)+ if err != nil {+ return false, err+ }+ // Empty title and every body empty means a misconfigured template, so fail+ // loudly and non-retryably instead of sending a card with no content.+ if c.title == "" && !isAnyNonEmpty(c.bodies) {+ return false, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat message rendered empty; check the channel title/text templates")+ }++ status := statusLine(alerts)++ // Cap per-alert sections well under Google Chat's 100-widget limit and keep+ // the card readable; the overflow count drives a "+N more" note. Capping+ // before the size guard keeps the trim loop working only on rendered bodies.+ capAlerts, capBodies, remaining := capAlertSections(alerts, c.bodies)++ // Serialized-size guard: keep the payload within Google Chat's byte limit by+ // trimming the longest body first, then the title (which appears in both the+ // summary and the card header). Banners/buttons are small and bounded, so+ // trimming the text fields always brings the payload under the limit.+ title := c.title+ bodies := append([]string(nil), capBodies...)+ // The shared "Open in SigNoz" button is per-rule (LabelRuleSource), so source+ // it from the original first alert, not the capped set which is empty when no+ // body renders.+ var footerAlert *types.Alert+ if len(alerts) > 0 {+ footerAlert = alerts[0]+ }+ buf, err := encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining, footerAlert))+ if err != nil {+ return false, err+ }+ for buf.Len() > maxMessageBytes {+ over := buf.Len() - maxMessageBytes+ if i := longestBodyIndex(bodies); i >= 0 {+ bodies[i] = truncateToByteLimit(bodies[i], max(len(bodies[i])-over, 0))+ } else if title != "" {+ title = truncateToByteLimit(title, max(len(title)-over, 0))+ } else {+ // TODO: button URLs aren't trimmed, so many long-URL buttons could+ // still overflow; drop trailing sections to fit once per-alert+ // templating makes that reachable.+ break+ }+ if buf, err = encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining, footerAlert)); err != nil {+ return false, err+ }+ }++ // Thread same-rule alerts together: threadKey is a stable hash of the+ // alert group key. Changing a rule's grouping starts a new thread.+ u, err := url.Parse(n.conf.WebhookURL.String())+ if err != nil {+ return false, errors.WrapInternalf(err, errors.CodeInternal, "parse google chat webhook url")+ }+ q := u.Query()+ q.Set("threadKey", key.Hash())+ q.Set("messageReplyOption", "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD")+ u.RawQuery = q.Encode()++ resp, err := notify.PostJSON(ctx, n.client, u.String(), buf) //nolint:bodyclose+ if err != nil {+ return true, notify.RedactURL(err)+ }+ defer notify.Drain(resp)++ shouldRetry, err := n.retrier.Check(resp.StatusCode, resp.Body)+ if err != nil {+ return shouldRetry, notify.NewErrorWithReason(notify.GetFailureReasonFromStatusCode(resp.StatusCode), err)+ }+ return shouldRetry, err+}++// prepareContent expands the title and body templates. Custom templates (from+// alert annotations) override the channel defaults. The title is used as a plain+// summary + card header; the body is converted to HTML for the card text widget.+func (n *Notifier) prepareContent(ctx context.Context, alerts []*types.Alert) (content, error) {+ customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(alerts)+ result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{+ TitleTemplate: customTitle,+ BodyTemplate: customBody,+ DefaultTitleTemplate: n.conf.Title,+ DefaultBodyTemplate: n.conf.Text,+ }, alerts)+ if err != nil {+ return content{}, err+ }++ // Each body goes into a per-alert card textParagraph, which renders HTML.+ // Default and custom templates are both standard markdown, so convert each+ // one. Bold/links/lists/code render well; tables flatten (rare in alerts).+ bodies := make([]string, len(result.Body))+ for i, body := range result.Body {+ if body == "" {+ continue+ }+ html, err := markdownrenderer.RenderHTML(body)+ if err != nil {+ return content{}, err+ }+ bodies[i] = html+ }++ return content{title: result.Title, bodies: bodies}, nil+}++// statusLine returns a colored firing/resolved banner for the card body.+func statusLine(alerts []*types.Alert) string {+ if types.Alerts(alerts...).Status() == model.AlertResolved {+ return `<font color="#33a853"><b>🟢 RESOLVED</b></font>`+ }+ return `<font color="#d32f2f"><b>🔴 FIRING</b></font>`+}++// relatedButtons builds the per-alert "View Related Logs/Traces" buttons from+// the annotations the ruler attaches to each alert. Empty links are skipped.+func relatedButtons(alert *types.Alert) []button {+ var buttons []button+ add := func(text, u string) {+ if u != "" {+ buttons = append(buttons, button{Text: text, OnClick: onClick{OpenLink: openLink{URL: u}}})+ }+ }+ add("View Related Logs", string(alert.Annotations[ruletypes.AnnotationRelatedLogs]))+ add("View Related Traces", string(alert.Annotations[ruletypes.AnnotationRelatedTraces]))+ return buttons+}++// sigNozButton builds the shared "Open in SigNoz" button from the ruleSource+// label, which is per-rule (identical for every alert in the group).+func sigNozButton(alert *types.Alert) *button {+ if u := string(alert.Labels[ruletypes.LabelRuleSource]); u != "" {+ return &button{Text: "Open in SigNoz", OnClick: onClick{OpenLink: openLink{URL: u}}}+ }+ return nil+}++// capAlertSections keeps the first maxAlertSections non-empty bodies (with their+// aligned alerts) and returns the count of non-empty bodies dropped beyond the+// cap. Capping the render set up front keeps the card within Google Chat's+// widget limit and bounds the size-guard trim loop.+func capAlertSections(alerts []*types.Alert, bodies []string) ([]*types.Alert, []string, int) {+ capAlerts := make([]*types.Alert, 0, maxAlertSections)+ capBodies := make([]string, 0, maxAlertSections)+ remaining := 0+ for i, body := range bodies {+ if body == "" {+ continue+ }+ if len(capBodies) >= maxAlertSections {+ remaining+++ continue+ }+ var alert *types.Alert+ if i < len(alerts) {+ alert = alerts[i]+ }+ capAlerts = append(capAlerts, alert)+ capBodies = append(capBodies, body)+ }+ return capAlerts, capBodies, remaining+}++// buildMessage assembles the text+card payload: a plain text summary plus a card+// with a status banner, one section per alert (its body + related-link buttons),+// an optional "+N more" note, and a shared "Open in SigNoz" footer button. The+// alerts and bodies slices are the already-capped, aligned render set; footerAlert+// is the original first alert, used for the per-rule footer button so it survives+// even when no body renders.+func buildMessage(title, statusHTML string, alerts []*types.Alert, bodies []string, remaining int, footerAlert *types.Alert) Message {+ sections := []cardSection{{Widgets: []widget{{TextParagraph: &textParagraph{Text: statusHTML}}}}}++ for i, body := range bodies {+ if body == "" {+ continue+ }+ widgets := []widget{{TextParagraph: &textParagraph{Text: body}}}+ if i < len(alerts) && alerts[i] != nil {+ if btns := relatedButtons(alerts[i]); len(btns) > 0 {+ widgets = append(widgets, widget{ButtonList: &buttonList{Buttons: btns}})+ }+ }+ sections = append(sections, cardSection{Widgets: widgets})+ }++ if remaining > 0 {+ note := fmt.Sprintf("<i>…and %d more alerts. Open in SigNoz for the full list.</i>", remaining)+ sections = append(sections, cardSection{Widgets: []widget{{TextParagraph: &textParagraph{Text: note}}}})+ }++ if footerAlert != nil {+ if btn := sigNozButton(footerAlert); btn != nil {+ sections = append(sections, cardSection{Widgets: []widget{{ButtonList: &buttonList{Buttons: []button{*btn}}}}})+ }+ }++ return Message{+ Text: title,+ CardsV2: []cardWithID{{+ CardID: "signoz-alert",+ Card: card{Header: &cardHeader{Title: title}, Sections: sections},+ }},+ }+}++// isAnyNonEmpty reports whether any string in ss is non-empty.+func isAnyNonEmpty(ss []string) bool {+ for _, s := range ss {+ if s != "" {+ return true+ }+ }+ return false+}++// longestBodyIndex returns the index of the longest non-empty body, or -1 when+// all bodies are empty.+func longestBodyIndex(bodies []string) int {+ idx, best := -1, 0+ for i, b := range bodies {+ if len(b) > best {+ idx, best = i, len(b)+ }+ }+ return idx+}++func encodeMessage(msg Message) (*bytes.Buffer, error) {+ var buf bytes.Buffer+ if err := json.NewEncoder(&buf).Encode(msg); err != nil {+ return nil, err+ }+ return &buf, nil+}++// truncateToByteLimit trims s to at most maxBytes bytes on a rune boundary,+// appending an ellipsis when it truncates.+func truncateToByteLimit(s string, maxBytes int) string {+ if len(s) <= maxBytes {+ return s+ }+ const ellipsis = "..."+ target := maxBytes - len(ellipsis)+ if target <= 0 {+ return ellipsis[:maxBytes]+ }+ truncated := s+ for len(truncated) > target {+ _, size := utf8.DecodeLastRuneInString(truncated)+ if size == 0 {+ break+ }+ truncated = truncated[:len(truncated)-size]+ }+ return truncated + ellipsis+}diff --git a/pkg/alertmanager/alertmanagernotify/googlechat/googlechat_test.go b/pkg/alertmanager/alertmanagernotify/googlechat/googlechat_test.gonew file mode 100644index 0000000000..335fcbde0e--- /dev/null+++ b/pkg/alertmanager/alertmanagernotify/googlechat/googlechat_test.go@@ -0,0 +1,578 @@+package googlechat++import (+ "context"+ "encoding/json"+ "io"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "net/url"+ "strings"+ "testing"+ "time"++ "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"+ "github.com/SigNoz/signoz/pkg/types/alertmanagertypes"+ "github.com/SigNoz/signoz/pkg/types/ruletypes"+ commoncfg "github.com/prometheus/common/config"+ "github.com/prometheus/common/model"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"++ "github.com/prometheus/alertmanager/config"+ "github.com/prometheus/alertmanager/notify"+ "github.com/prometheus/alertmanager/notify/test"+ "github.com/prometheus/alertmanager/template"+ "github.com/prometheus/alertmanager/types"+)++func newTestTemplater(tmpl *template.Template) alertmanagertypes.Templater {+ return alertmanagertemplate.New(tmpl, slog.New(slog.DiscardHandler))+}++func secretURLFromString(t *testing.T, rawURL string) *config.SecretURL {+ t.Helper()+ parsed, err := url.Parse(rawURL)+ require.NoError(t, err)+ return &config.SecretURL{URL: parsed}+}++func newTestNotifier(t *testing.T, webhookURL, title, text string) *Notifier {+ t.Helper()+ tmpl := test.CreateTmpl(t)+ n, err := New(&alertmanagertypes.GoogleChatReceiverConfig{+ HTTPConfig: &commoncfg.HTTPClientConfig{},+ WebhookURL: secretURLFromString(t, webhookURL),+ Title: title,+ Text: text,+ }, tmpl, slog.New(slog.DiscardHandler), newTestTemplater(tmpl))+ require.NoError(t, err)+ return n+}++func newTestAlerts(alertname string) []*types.Alert {+ return []*types.Alert{{+ Alert: model.Alert{+ Labels: model.LabelSet{"alertname": model.LabelValue(alertname)},+ Annotations: model.LabelSet{"summary": model.LabelValue("summary for " + alertname)},+ StartsAt: time.Now(),+ EndsAt: time.Now().Add(time.Minute),+ },+ }}+}++func newTestContext() context.Context {+ return notify.WithGroupKey(context.Background(), "test-receiver")+}++// captureServer starts an httptest server that decodes the posted Google Chat+// Message into got and replies 200.+func captureServer(t *testing.T, got *Message) *httptest.Server {+ t.Helper()+ return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if got != nil {+ _ = json.NewDecoder(r.Body).Decode(got)+ }+ w.WriteHeader(http.StatusOK)+ }))+}++func TestGoogleChatSend(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ n := newTestNotifier(t, server.URL, `[{{ .Status | toUpper }}] {{ .CommonLabels.alertname }}`, "")+ retry, err := n.Notify(newTestContext(), newTestAlerts("TestAlert")...)++ require.NoError(t, err)+ assert.False(t, retry)+ assert.Contains(t, got.Text, "FIRING")+ assert.Contains(t, got.Text, "TestAlert")+}++func TestGoogleChatTitleAndBody(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ n := newTestNotifier(t, server.URL, "TITLE", "BODY")+ retry, err := n.Notify(newTestContext(), newTestAlerts("TestAlert")...)++ require.NoError(t, err)+ assert.False(t, retry)+ // Title is the plain summary + card header; body lives in a card widget.+ assert.Equal(t, "TITLE", got.Text)+ require.NotEmpty(t, got.CardsV2)+ assert.Equal(t, "TITLE", got.CardsV2[0].Card.Header.Title)+ assert.Contains(t, cardBody(t, got), "BODY")+}++// cardBody concatenates the text of all textParagraph widgets in the message.+func cardBody(t *testing.T, m Message) string {+ t.Helper()+ require.NotEmpty(t, m.CardsV2)+ var b strings.Builder+ for _, s := range m.CardsV2[0].Card.Sections {+ for _, w := range s.Widgets {+ if w.TextParagraph != nil {+ b.WriteString(w.TextParagraph.Text)+ b.WriteByte('\n')+ }+ }+ }+ return b.String()+}++// cardButtons returns all buttons across every buttonList widget in the card.+func cardButtons(t *testing.T, m Message) []button {+ t.Helper()+ require.NotEmpty(t, m.CardsV2)+ var buttons []button+ for _, s := range m.CardsV2[0].Card.Sections {+ for _, w := range s.Widgets {+ if w.ButtonList != nil {+ buttons = append(buttons, w.ButtonList.Buttons...)+ }+ }+ }+ return buttons+}++// cardSectionCount returns the number of sections in the card.+func cardSectionCount(t *testing.T, m Message) int {+ t.Helper()+ require.NotEmpty(t, m.CardsV2)+ return len(m.CardsV2[0].Card.Sections)+}++func TestGoogleChatNilHTTPConfig(t *testing.T) {+ // A nil HTTPConfig must fail cleanly, not panic on the *conf.HTTPConfig deref.+ tmpl := test.CreateTmpl(t)+ n, err := New(&alertmanagertypes.GoogleChatReceiverConfig{+ HTTPConfig: nil,+ WebhookURL: secretURLFromString(t, "https://chat.googleapis.com/v1/spaces/test/messages"),+ }, tmpl, slog.New(slog.DiscardHandler), newTestTemplater(tmpl))+ require.Error(t, err)+ assert.Nil(t, n)+}++func TestGoogleChatRetryCodes(t *testing.T) {+ tmpl := test.CreateTmpl(t)+ n, err := New(&alertmanagertypes.GoogleChatReceiverConfig{+ HTTPConfig: &commoncfg.HTTPClientConfig{},+ WebhookURL: secretURLFromString(t, "https://chat.googleapis.com/v1/spaces/test/messages"),+ }, tmpl, slog.New(slog.DiscardHandler), newTestTemplater(tmpl))+ require.NoError(t, err)++ cases := []struct {+ code int+ retry bool+ }{+ {http.StatusOK, false},+ {http.StatusBadRequest, false}, // 400: malformed payload, permanent+ {http.StatusTooManyRequests, true}, // 429: rate limited, retry (our RetryCodes)+ {http.StatusInternalServerError, true}, // 5xx: retry+ {http.StatusServiceUnavailable, true},+ }+ for _, c := range cases {+ t.Run(http.StatusText(c.code), func(t *testing.T) {+ actual, _ := n.retrier.Check(c.code, nil)+ assert.Equal(t, c.retry, actual, "retry mismatch on status %d", c.code)+ })+ }+}++func TestGoogleChatRedactedURL(t *testing.T) {+ ctx, u, fn := test.GetContextWithCancelingURL()+ defer fn()+ ctx = notify.WithGroupKey(ctx, "test-receiver")++ tmpl := test.CreateTmpl(t)+ n, err := New(&alertmanagertypes.GoogleChatReceiverConfig{+ HTTPConfig: &commoncfg.HTTPClientConfig{},+ WebhookURL: &config.SecretURL{URL: u},+ Title: "alert", // non-empty so it reaches the POST (not the empty-text guard)+ }, tmpl, slog.New(slog.DiscardHandler), newTestTemplater(tmpl))+ require.NoError(t, err)++ test.AssertNotifyLeaksNoSecret(ctx, t, n, u.String())+}++func TestTruncateToByteLimit(t *testing.T) {+ cases := []struct {+ name string+ in string+ max int+ wantLen int // upper bound on byte length of result+ wantHas string // substring the result must contain (or "")+ }{+ {"under limit passthrough", "hello", 100, 5, "hello"},+ {"over limit trims with ellipsis", strings.Repeat("a", 50), 10, 10, "..."},+ {"exact limit passthrough", "hello", 5, 5, "hello"},+ {"tiny limit", "hello", 2, 2, ""},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ got := truncateToByteLimit(c.in, c.max)+ assert.LessOrEqual(t, len(got), c.wantLen)+ if c.wantHas != "" {+ assert.Contains(t, got, c.wantHas)+ }+ })+ }+}++func TestGoogleChatMessageSizeLimit(t *testing.T) {+ var bodyLen int+ var valid bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ raw, _ := io.ReadAll(r.Body)+ bodyLen = len(raw)+ valid = json.Valid(raw)+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()++ // Huge plain-ASCII title so one-time truncation lands deterministically under the limit.+ n := newTestNotifier(t, server.URL, strings.Repeat("A", 40000), "")+ retry, err := n.Notify(newTestContext(), newTestAlerts("Big")...)++ require.NoError(t, err)+ assert.False(t, retry)+ assert.True(t, valid, "posted body must be valid JSON")+ assert.LessOrEqual(t, bodyLen, maxMessageBytes, "posted body must be within the size limit")+}++func TestGoogleChatThreading(t *testing.T) {+ var query url.Values+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ query = r.URL.Query()+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()++ cases := []struct{ name, groupKey string }{+ {"rule a", "{ruleId=\"aaa\"}"},+ {"rule b", "{ruleId=\"bbb\"}"},+ }+ seen := map[string]string{}+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ n := newTestNotifier(t, server.URL, "T", "")+ ctx := notify.WithGroupKey(context.Background(), c.groupKey)+ _, err := n.Notify(ctx, newTestAlerts("X")...)+ require.NoError(t, err)++ assert.Equal(t, "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD", query.Get("messageReplyOption"))+ threadKey := query.Get("threadKey")+ assert.Equal(t, notify.Key(c.groupKey).Hash(), threadKey, "threadKey must be the group key hash")+ seen[c.name] = threadKey+ })+ }+ assert.NotEqual(t, seen["rule a"], seen["rule b"], "distinct group keys must yield distinct threadKeys")+}++func TestGoogleChatCustomTemplateMarkdown(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ // Custom body template (standard markdown) supplied via annotation → the+ // !IsDefaultBody path must convert it to Google Chat dialect.+ alerts := []*types.Alert{{+ Alert: model.Alert{+ Labels: model.LabelSet{"alertname": "X"},+ Annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "**bold** and [link](https://x)"},+ StartsAt: time.Now(),+ EndsAt: time.Now().Add(time.Minute),+ },+ }}+ n := newTestNotifier(t, server.URL, "Alert", "default body")+ _, err := n.Notify(newTestContext(), alerts...)+ require.NoError(t, err)++ // Custom body is standard markdown → converted to card HTML.+ body := cardBody(t, got)+ assert.Contains(t, body, "<strong>bold</strong>", "** should convert to HTML bold")+ assert.Contains(t, body, `<a href="https://x">link</a>`, "[t](u) should convert to an HTML link")+}++func TestGoogleChatSerializedSizeUnderLimit(t *testing.T) {+ var bodyLen int+ var valid bool+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ raw, _ := io.ReadAll(r.Body)+ bodyLen = len(raw)+ valid = json.Valid(raw)+ w.WriteHeader(http.StatusOK)+ }))+ defer server.Close()++ // Escaping-dense payload: <, >, & and newlines each expand under JSON+ // encoding, so this is the shape that would push the serialized body over+ // the limit if we measured the text bytes instead of the marshaled buffer.+ dense := strings.Repeat("<https://example.com/a?x=1&y=2|link>\n", 2000)+ n := newTestNotifier(t, server.URL, dense, "")+ _, err := n.Notify(newTestContext(), newTestAlerts("Dense")...)++ require.NoError(t, err)+ assert.True(t, valid, "posted body must be valid JSON")+ assert.LessOrEqual(t, bodyLen, maxMessageBytes, "serialized body must be within the limit")+}++func TestGoogleChatEmptyText(t *testing.T) {+ server := captureServer(t, nil)+ defer server.Close()++ // Empty title and body templates → must not POST; fail non-retryably.+ n := newTestNotifier(t, server.URL, "", "")+ retry, err := n.Notify(newTestContext(), newTestAlerts("X")...)++ require.Error(t, err)+ assert.False(t, retry)+}++func TestGoogleChatLinkButtons(t *testing.T) {+ cases := []struct {+ name string+ labels model.LabelSet+ annotations model.LabelSet+ wantButtons map[string]string+ }{+ {+ name: "all links present",+ labels: model.LabelSet{+ "alertname": "X",+ ruletypes.LabelRuleSource: "https://signoz.example/alerts/1",+ },+ annotations: model.LabelSet{+ ruletypes.AnnotationRelatedLogs: "https://signoz.example/logs",+ ruletypes.AnnotationRelatedTraces: "https://signoz.example/traces",+ },+ wantButtons: map[string]string{+ "Open in SigNoz": "https://signoz.example/alerts/1",+ "View Related Logs": "https://signoz.example/logs",+ "View Related Traces": "https://signoz.example/traces",+ },+ },+ {+ name: "no links → no buttons",+ labels: model.LabelSet{"alertname": "X"},+ annotations: model.LabelSet{"summary": "s"},+ wantButtons: map[string]string{},+ },+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ alerts := []*types.Alert{{Alert: model.Alert{+ Labels: c.labels,+ Annotations: c.annotations,+ StartsAt: time.Now(),+ EndsAt: time.Now().Add(time.Minute),+ }}}+ // Non-empty body so the alert section (which carries related buttons) exists.+ n := newTestNotifier(t, server.URL, "T", "an alert")+ _, err := n.Notify(newTestContext(), alerts...)+ require.NoError(t, err)++ buttons := cardButtons(t, got)+ assert.Len(t, buttons, len(c.wantButtons))+ for _, b := range buttons {+ assert.Equal(t, c.wantButtons[b.Text], b.OnClick.OpenLink.URL, "button %q", b.Text)+ }+ })+ }+}++func TestGoogleChatFooterButtonSurvivesEmptyBody(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ // Cleared Description (empty text template) → body renders empty while the+ // title still renders. The per-rule "Open in SigNoz" button must survive.+ alerts := []*types.Alert{{Alert: model.Alert{+ Labels: model.LabelSet{+ "alertname": "X",+ ruletypes.LabelRuleSource: "https://signoz.example/alerts/1",+ },+ StartsAt: time.Now(),+ EndsAt: time.Now().Add(time.Minute),+ }}}+ n := newTestNotifier(t, server.URL, "TITLE", "")+ _, err := n.Notify(newTestContext(), alerts...)+ require.NoError(t, err)++ buttons := cardButtons(t, got)+ require.Len(t, buttons, 1)+ assert.Equal(t, "Open in SigNoz", buttons[0].Text)+ assert.Equal(t, "https://signoz.example/alerts/1", buttons[0].OnClick.OpenLink.URL)+}++func TestGoogleChatMultiAlertSections(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ // A per-alert custom body template yields one card section per alert, each+ // with that alert's own related-link buttons, plus one shared SigNoz button.+ mkAlert := func(pod, logs string) *types.Alert {+ return &types.Alert{Alert: model.Alert{+ Labels: model.LabelSet{+ "alertname": "X",+ "pod": model.LabelValue(pod),+ ruletypes.LabelRuleSource: "https://signoz.example/alerts/1",+ },+ Annotations: model.LabelSet{+ ruletypes.AnnotationBodyTemplate: "an alert fired",+ ruletypes.AnnotationRelatedLogs: model.LabelValue(logs),+ },+ StartsAt: time.Now(),+ EndsAt: time.Now().Add(time.Minute),+ }}+ }+ alerts := []*types.Alert{+ mkAlert("pod-1", "https://signoz.example/logs?pod=pod-1"),+ mkAlert("pod-2", "https://signoz.example/logs?pod=pod-2"),+ }+ n := newTestNotifier(t, server.URL, "T", "default body")+ _, err := n.Notify(newTestContext(), alerts...)+ require.NoError(t, err)++ // banner + one section per alert + shared SigNoz footer.+ assert.Equal(t, 4, cardSectionCount(t, got))++ sigNoz := 0+ logsURLs := map[string]bool{}+ for _, b := range cardButtons(t, got) {+ switch b.Text {+ case "Open in SigNoz":+ sigNoz+++ case "View Related Logs":+ logsURLs[b.OnClick.OpenLink.URL] = true+ }+ }+ assert.Equal(t, 1, sigNoz, "SigNoz button must appear once (shared, per-rule)")+ assert.True(t, logsURLs["https://signoz.example/logs?pod=pod-1"], "pod-1's logs button")+ assert.True(t, logsURLs["https://signoz.example/logs?pod=pod-2"], "pod-2's logs button")+}++func TestGoogleChatDefaultBodyGrouped(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ // Default body template (no per-alert annotation): the templater combines all+ // grouped alerts into ONE section, carrying only the first alert's buttons.+ mkAlert := func(pod string) *types.Alert {+ return &types.Alert{Alert: model.Alert{+ Labels: model.LabelSet{+ "alertname": "X",+ "pod": model.LabelValue(pod),+ ruletypes.LabelRuleSource: "https://signoz.example/alerts/1",+ },+ Annotations: model.LabelSet{+ ruletypes.AnnotationRelatedLogs: model.LabelValue("https://signoz.example/logs?pod=" + pod),+ },+ StartsAt: time.Now(),+ EndsAt: time.Now().Add(time.Minute),+ }}+ }+ alerts := []*types.Alert{mkAlert("pod-1"), mkAlert("pod-2")}+ n := newTestNotifier(t, server.URL, "T", "{{ range .Alerts }}pod {{ .Labels.pod }} {{ end }}")+ _, err := n.Notify(newTestContext(), alerts...)+ require.NoError(t, err)++ // banner + one combined alert section + shared SigNoz footer = 3 sections.+ assert.Equal(t, 3, cardSectionCount(t, got))++ body := cardBody(t, got)+ assert.Contains(t, body, "pod-1")+ assert.Contains(t, body, "pod-2", "default template combines all alerts into one section")++ logs := 0+ for _, b := range cardButtons(t, got) {+ if b.Text == "View Related Logs" {+ logs+++ }+ }+ assert.Equal(t, 1, logs, "default path surfaces only the first alert's related buttons")+}++func TestGoogleChatSectionCap(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ // 35 grouped alerts (custom body → per-alert bodies) exceed the 30 cap.+ const total = 35+ alerts := make([]*types.Alert, 0, total)+ for range total {+ alerts = append(alerts, &types.Alert{Alert: model.Alert{+ Labels: model.LabelSet{+ "alertname": "X",+ ruletypes.LabelRuleSource: "https://signoz.example/alerts/1",+ },+ Annotations: model.LabelSet{ruletypes.AnnotationBodyTemplate: "an alert fired"},+ StartsAt: time.Now(),+ EndsAt: time.Now().Add(time.Minute),+ }})+ }+ n := newTestNotifier(t, server.URL, "T", "default body")+ _, err := n.Notify(newTestContext(), alerts...)+ require.NoError(t, err)++ // banner + 30 alert sections + "+N more" note + shared SigNoz footer.+ assert.Equal(t, 1+maxAlertSections+1+1, cardSectionCount(t, got))++ body := cardBody(t, got)+ assert.Contains(t, body, "5 more alerts", "overflow note must state the dropped count")++ // The SigNoz footer must survive after the note (last section).+ sigNoz := 0+ for _, b := range cardButtons(t, got) {+ if b.Text == "Open in SigNoz" {+ sigNoz+++ }+ }+ assert.Equal(t, 1, sigNoz, "SigNoz footer must be present despite the cap")+}++func TestGoogleChatStatusLine(t *testing.T) {+ cases := []struct {+ name string+ resolved bool+ want string+ }{+ {"firing", false, "🔴 FIRING"},+ {"resolved", true, "🟢 RESOLVED"},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ var got Message+ server := captureServer(t, &got)+ defer server.Close()++ endsAt := time.Now().Add(time.Minute)+ if c.resolved {+ endsAt = time.Now().Add(-time.Minute) // EndsAt in the past → resolved+ }+ alerts := []*types.Alert{{Alert: model.Alert{+ Labels: model.LabelSet{"alertname": "X"},+ StartsAt: time.Now().Add(-2 * time.Minute),+ EndsAt: endsAt,+ }}}+ n := newTestNotifier(t, server.URL, "T", "")+ _, err := n.Notify(newTestContext(), alerts...)+ require.NoError(t, err)++ assert.Contains(t, cardBody(t, got), c.want)+ })+ }+}diff --git a/pkg/alertmanager/alertmanagernotify/receiver.go b/pkg/alertmanager/alertmanagernotify/receiver.goindex 40665b7c1d..ac904873ce 100644--- a/pkg/alertmanager/alertmanagernotify/receiver.go+++ b/pkg/alertmanager/alertmanagernotify/receiver.go@@ -5,6 +5,7 @@ import ("slices""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/email"+ "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/googlechat""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/msteamsv2""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/opsgenie""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/pagerduty"@@ -24,6 +25,7 @@ var customNotifierIntegrations = []string{opsgenie.Integration,slack.Integration,msteamsv2.Integration,+ googlechat.Integration,}func NewReceiverIntegrations(nc *alertmanagertypes.Receiver, tmpl *template.Template, logger *slog.Logger, templater alertmanagertypes.Templater) ([]notify.Integration, error) {@@ -74,6 +76,11 @@ func NewReceiverIntegrations(nc *alertmanagertypes.Receiver, tmpl *template.Tempreturn msteamsv2.New(c, tmpl, `{{ template "msteamsv2.default.titleLink" . }}`, l, templater)})}+ for i, c := range nc.GoogleChatConfigs {+ add(googlechat.Integration, i, c, func(l *slog.Logger) (notify.Notifier, error) {+ return googlechat.New(c, tmpl, l, templater)+ })+ }if errs.Len() > 0 {return nil, &errsdiff --git a/pkg/types/alertmanagertypes/googlechat.go b/pkg/types/alertmanagertypes/googlechat.goindex 7a9dc08383..7719f0a814 100644--- a/pkg/types/alertmanagertypes/googlechat.go+++ b/pkg/types/alertmanagertypes/googlechat.go@@ -1,6 +1,10 @@package alertmanagertypesimport (+ "net/url"+ "strings"++ "github.com/SigNoz/signoz/pkg/errors""github.com/prometheus/alertmanager/config"commoncfg "github.com/prometheus/common/config")@@ -21,14 +25,30 @@ var DefaultGoogleChatReceiverConfig = GoogleChatReceiverConfig{},Title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,Text: `{{ range .Alerts -}}-*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }}-*Summary:* {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }}-*Description:* {{ .Annotations.description }}{{ end }}+**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }}+**Summary:** {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }}+**Description:** {{ .Annotations.description }}{{ end }}{{ end }}`,}func (c *GoogleChatReceiverConfig) UnmarshalYAML(unmarshal func(any) error) error {*c = DefaultGoogleChatReceiverConfigtype plain GoogleChatReceiverConfig- return unmarshal((*plain)(c))+ if err := unmarshal((*plain)(c)); err != nil {+ return err+ }+ if c.WebhookURL == nil {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url is required")+ }+ u, err := url.Parse(c.WebhookURL.String())+ if err != nil {+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid google chat webhook_url: %v", err)+ }+ if u.Scheme != "https" {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url must use https")+ }+ if strings.ToLower(u.Hostname()) != "chat.googleapis.com" {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url must use chat.googleapis.com")+ }+ return nil}diff --git a/pkg/types/alertmanagertypes/googlechat_test.go b/pkg/types/alertmanagertypes/googlechat_test.gonew file mode 100644index 0000000000..f81476d8fd--- /dev/null+++ b/pkg/types/alertmanagertypes/googlechat_test.go@@ -0,0 +1,30 @@+package alertmanagertypes++import (+ "testing"++ "github.com/stretchr/testify/require"+)++func TestNewReceiverGoogleChatWebhookURL(t *testing.T) {+ cases := []struct {+ name string+ config string+ wantErr bool+ }{+ {"valid", `{"name":"gc","googlechat_configs":[{"webhook_url":"https://chat.googleapis.com/v1/spaces/AAA/messages?key=k&token=t"}]}`, false},+ {"http scheme rejected", `{"name":"gc","googlechat_configs":[{"webhook_url":"http://chat.googleapis.com/v1/spaces/x/messages"}]}`, true},+ {"wrong host rejected", `{"name":"gc","googlechat_configs":[{"webhook_url":"https://example.com/x"}]}`, true},+ {"missing webhook_url", `{"name":"gc","googlechat_configs":[{"title":"x"}]}`, true},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ _, err := NewReceiver(c.config)+ if c.wantErr {+ require.Error(t, err)+ } else {+ require.NoError(t, err)+ }+ })+ }+}diff --git a/pkg/types/alertmanagertypes/receiver.go b/pkg/types/alertmanagertypes/receiver.goindex 39fa781add..474612dad6 100644--- a/pkg/types/alertmanagertypes/receiver.go+++ b/pkg/types/alertmanagertypes/receiver.go@@ -40,6 +40,8 @@ func NewReceiver(input string) (*Receiver, error) {receiver.Receiver = withDefaults// Extend this block when adding another native notifier type.+ // defaultedNotifierConfig triggers each config's UnmarshalYAML, which applies+ // defaults and validates (e.g. the Google Chat webhook URL).for i, gc := range receiver.GoogleChatConfigs {defaulted, err := defaultedNotifierConfig(gc)if err != nil {