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): incidentio channel integration (#12644)
Nikhil Mantrie84a61d43f7f
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 88ffeab944..cf3029e4f2 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -109,6 +109,25 @@ components:webhook_url:$ref: '#/components/schemas/ConfigSecretURL'type: object+ AlertmanagertypesIncidentIOReceiverConfig:+ properties:+ description:+ type: string+ http_config:+ $ref: '#/components/schemas/ConfigHTTPClientConfig'+ metadata:+ additionalProperties:+ type: string+ type: object+ send_resolved:+ type: boolean+ title:+ type: string+ token:+ type: string+ url:+ type: string+ type: objectAlertmanagertypesJSMOpsReceiverConfig:properties:api_key:@@ -217,12 +236,12 @@ components:- jira_configs- required:- jsmops_configs+ - required:+ - incidentio_configs- required:- discord_configs- required:- email_configs- - required:- - incidentio_configs- required:- pagerduty_configs- required:@@ -266,7 +285,7 @@ components:type: arrayincidentio_configs:items:- $ref: '#/components/schemas/ConfigIncidentioConfig'+ $ref: '#/components/schemas/AlertmanagertypesIncidentIOReceiverConfig'type: arrayjira_configs:items:@@ -397,7 +416,7 @@ components:type: arrayincidentio_configs:items:- $ref: '#/components/schemas/ConfigIncidentioConfig'+ $ref: '#/components/schemas/AlertmanagertypesIncidentIOReceiverConfig'type: arrayjira_configs:items:diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex b1d5ace6c7..1a4f8cc295 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -385,6 +385,38 @@ export interface AlertmanagertypesGoogleChatReceiverConfigDTO {webhook_url?: ConfigSecretURLDTO;}+export type AlertmanagertypesIncidentIOReceiverConfigDTOMetadata = {+ [key: string]: string;+};++export interface AlertmanagertypesIncidentIOReceiverConfigDTO {+ /**+ * @type string+ */+ description?: string;+ http_config?: ConfigHTTPClientConfigDTO;+ /**+ * @type object+ */+ metadata?: AlertmanagertypesIncidentIOReceiverConfigDTOMetadata;+ /**+ * @type boolean+ */+ send_resolved?: boolean;+ /**+ * @type string+ */+ title?: string;+ /**+ * @type string+ */+ token?: string;+ /**+ * @type string+ */+ url?: string;+}+export interface AlertmanagertypesJSMOpsReceiverConfigDTO {/*** @type string@@ -685,39 +717,6 @@ export interface ConfigEmailConfigDTO {to?: string;}-export type TimeDurationDTO = number;--export interface ConfigURLType2DTO {- [key: string]: unknown;-}--export interface ConfigIncidentioConfigDTO {- /**- * @type string- */- alert_source_token?: string;- /**- * @type string- */- alert_source_token_file?: string;- http_config?: ConfigHTTPClientConfigDTO;- /**- * @type integer- * @minimum 0- */- max_alerts?: number;- /**- * @type boolean- */- send_resolved?: boolean;- timeout?: TimeDurationDTO;- url?: ConfigURLType2DTO;- /**- * @type string- */- url_file?: string;-}-export interface ConfigMattermostFieldDTO {/*** @type boolean,null@@ -903,6 +902,10 @@ export interface ConfigMSTeamsV2ConfigDTO {webhook_url_file?: string;}+export interface ConfigURLType2DTO {+ [key: string]: unknown;+}+export interface ConfigOpsGenieConfigResponderDTO {/*** @type string@@ -1011,6 +1014,8 @@ export interface ConfigPagerdutyLinkDTO {text?: string;}+export type TimeDurationDTO = number;+export type ConfigPagerdutyConfigDTODetails = { [key: string]: unknown };export interface ConfigPagerdutyConfigDTO {@@ -1672,7 +1677,7 @@ export type AlertmanagertypesPostableChannelDTO = unknown & {/*** @type array*/- incidentio_configs?: ConfigIncidentioConfigDTO[];+ incidentio_configs?: AlertmanagertypesIncidentIOReceiverConfigDTO[];/*** @type array*/@@ -1803,7 +1808,7 @@ export interface AlertmanagertypesReceiverDTO {/*** @type array*/- incidentio_configs?: ConfigIncidentioConfigDTO[];+ incidentio_configs?: AlertmanagertypesIncidentIOReceiverConfigDTO[];/*** @type array*/@@ -3300,6 +3305,33 @@ export interface CommonJSONRefDTO {$ref?: string;}+export interface ConfigIncidentioConfigDTO {+ /**+ * @type string+ */+ alert_source_token?: string;+ /**+ * @type string+ */+ alert_source_token_file?: string;+ http_config?: ConfigHTTPClientConfigDTO;+ /**+ * @type integer+ * @minimum 0+ */+ max_alerts?: number;+ /**+ * @type boolean+ */+ send_resolved?: boolean;+ timeout?: TimeDurationDTO;+ url?: ConfigURLType2DTO;+ /**+ * @type string+ */+ url_file?: string;+}+export type ConfigJiraConfigDTOCustomFields = { [key: string]: unknown };export interface ConfigJiraFieldConfigDTO {diff --git a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsxindex 3c57da9620..a24a3a3868 100644--- a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx+++ b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx@@ -585,7 +585,7 @@ describe('Create Alert Channel', () => {description: 'jira_site_invalid',}),);- });+ }, 15000);it('Should send a jira_configs payload with basic auth', async () => {let requestBody: unknown;diff --git a/pkg/alertmanager/alertmanagernotify/incidentio/incidentio.go b/pkg/alertmanager/alertmanagernotify/incidentio/incidentio.gonew file mode 100644index 0000000000..db1392e81e--- /dev/null+++ b/pkg/alertmanager/alertmanagernotify/incidentio/incidentio.go@@ -0,0 +1,188 @@+package incidentio++import (+ "bytes"+ "context"+ "encoding/json"+ "log/slog"+ "maps"+ "net/http"+ "strings"++ "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"+ "github.com/SigNoz/signoz/pkg/errors"+ "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"+)++const (+ Integration = "incidentio"++ // incident.io rejects payloads over 512 KB with a 413. Runes cap the+ // description at 4 bytes each worst case (~400 KB), leaving headroom for+ // the other fields.+ maxDescriptionLenRunes = 100000++ statusFiring = "firing"+ statusResolved = "resolved"+)++// alertEvent is the body of incident.io's HTTP alert source endpoint+// (Alert Events V2 API). Title, status and deduplication_key are required;+// metadata values must be flat scalars. Repeat events for a firing key are+// dropped server-side and resolves for unknown keys are safe no-ops, so+// events are sent unconditionally.+type alertEvent struct {+ Title string `json:"title"`+ Description string `json:"description,omitempty"`+ Status string `json:"status"`+ DeduplicationKey string `json:"deduplication_key"`+ SourceURL string `json:"source_url,omitempty"`+ Metadata map[string]string `json:"metadata,omitempty"`+}++type Notifier struct {+ conf *alertmanagertypes.IncidentIOReceiverConfig+ tmpl *template.Template+ logger *slog.Logger+ client *http.Client+ retrier *notify.Retrier+ templater alertmanagertypes.Templater+}++func New(conf *alertmanagertypes.IncidentIOReceiverConfig, t *template.Template, l *slog.Logger, templater alertmanagertypes.Templater) (*Notifier, error) {+ if conf.HTTPConfig == nil {+ return nil, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "incidentio 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, as ...*types.Alert) (bool, error) {+ key, err := notify.ExtractGroupKey(ctx)+ if err != nil {+ return false, err+ }+ firing := types.Alerts(as...).HasFiring()+ n.logger.DebugContext(ctx, "sending incidentio notification", slog.String("group_key", key.String()), slog.Bool("firing", firing))++ customTitle, customBody := alertmanagertemplate.ExtractTemplatesFromAnnotations(as)+ result, err := n.templater.Expand(ctx, alertmanagertypes.ExpandRequest{+ TitleTemplate: customTitle,+ BodyTemplate: customBody,+ DefaultTitleTemplate: n.conf.Title,+ DefaultBodyTemplate: n.conf.Description,+ }, as)+ if err != nil {+ return false, err+ }++ // title is required by the API; a channel title template can render empty,+ // so fall back to the rule name, then to a static last resort.+ title := result.Title+ if strings.TrimSpace(title) == "" && len(as) > 0 {+ title = string(as[0].Labels[ruletypes.LabelAlertName])+ }+ if strings.TrimSpace(title) == "" {+ title = "SigNoz alert"+ }++ var parts []string+ for _, body := range result.Body {+ if body != "" {+ parts = append(parts, body)+ }+ }+ description := truncateRunes(strings.Join(parts, "\n\n---\n\n"), maxDescriptionLenRunes)++ status := statusFiring+ if !firing {+ status = statusResolved+ }++ event := alertEvent{+ Title: title,+ Description: description,+ Status: status,+ DeduplicationKey: key.Hash(),+ SourceURL: sourceURL(as),+ Metadata: n.metadata(ctx, as),+ }++ var buf bytes.Buffer+ if err := json.NewEncoder(&buf).Encode(event); err != nil {+ return false, err+ }++ req, err := http.NewRequestWithContext(ctx, http.MethodPost, n.conf.URL, &buf)+ if err != nil {+ return false, err+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+string(n.conf.Token))++ resp, err := n.client.Do(req) //nolint:bodyclose // notify.Drain closes the body+ 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, nil+}++// metadata copies the group's common labels wholesale (the Opsgenie details+// precedent), so severity, ruleId and any user-defined rule labels arrive as+// flat strings ready for incident.io attribute mapping. Channel-configured+// pairs are template-expanded and laid on top (channel wins on key clash);+// a value that fails to expand is sent raw so delivery never breaks on it.+func (n *Notifier) metadata(ctx context.Context, as []*types.Alert) map[string]string {+ data := notify.GetTemplateData(ctx, n.tmpl, as, n.logger)+ out := make(map[string]string, len(data.CommonLabels)+len(n.conf.Metadata))+ maps.Copy(out, data.CommonLabels)+ for k, v := range n.conf.Metadata {+ expanded, err := n.tmpl.ExecuteTextString(v, data)+ if err != nil {+ n.logger.WarnContext(ctx, "failed to expand incidentio metadata value, sending it raw", slog.String("metadata_key", k))+ expanded = v+ }+ out[k] = expanded+ }+ if len(out) == 0 {+ return nil+ }+ return out+}++// sourceURL returns the per-rule SigNoz link from the ruleSource label, which+// is identical for every alert in the group.+func sourceURL(as []*types.Alert) string {+ if len(as) == 0 {+ return ""+ }+ return string(as[0].Labels[ruletypes.LabelRuleSource])+}++func truncateRunes(s string, max int) string {+ runes := []rune(s)+ if len(runes) <= max {+ return s+ }+ return string(runes[:max-1]) + "…"+}diff --git a/pkg/alertmanager/alertmanagernotify/incidentio/incidentio_test.go b/pkg/alertmanager/alertmanagernotify/incidentio/incidentio_test.gonew file mode 100644index 0000000000..86ffdd973a--- /dev/null+++ b/pkg/alertmanager/alertmanagernotify/incidentio/incidentio_test.go@@ -0,0 +1,216 @@+package incidentio++import (+ "context"+ "encoding/json"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync"+ "testing"+ "time"++ "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagertemplate"+ "github.com/SigNoz/signoz/pkg/types/alertmanagertypes"+ "github.com/prometheus/alertmanager/notify"+ "github.com/prometheus/alertmanager/notify/test"+ "github.com/prometheus/alertmanager/types"+ commoncfg "github.com/prometheus/common/config"+ "github.com/prometheus/common/model"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type mockIncidentIO struct {+ srv *httptest.Server+ mu sync.Mutex+ events []alertEvent+ auths []string+ status int+}++func newMockIncidentIO(t *testing.T) *mockIncidentIO {+ t.Helper()+ m := &mockIncidentIO{status: http.StatusAccepted}+ m.srv = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ var ev alertEvent+ _ = json.NewDecoder(r.Body).Decode(&ev)+ m.mu.Lock()+ m.events = append(m.events, ev)+ m.auths = append(m.auths, r.Header.Get("Authorization"))+ status := m.status+ m.mu.Unlock()+ w.WriteHeader(status)+ if status == http.StatusAccepted {+ _, _ = w.Write([]byte(`{"status":"accepted","message":"Event accepted for processing","deduplication_key":"` + ev.DeduplicationKey + `"}`))+ } else {+ _, _ = w.Write([]byte(`{"type":"validation_error","status":422,"errors":[{"code":"is_required","message":"Deduplication key is required"}]}`))+ }+ }))+ t.Cleanup(m.srv.Close)+ return m+}++func (m *mockIncidentIO) lastEvent(t *testing.T) alertEvent {+ t.Helper()+ m.mu.Lock()+ defer m.mu.Unlock()+ require.NotEmpty(t, m.events)+ return m.events[len(m.events)-1]+}++func newNotifier(t *testing.T, m *mockIncidentIO) *Notifier {+ t.Helper()+ tmpl := test.CreateTmpl(t)+ n, err := New(&alertmanagertypes.IncidentIOReceiverConfig{+ URL: m.srv.URL + "/v2/alert_events/http/src-1",+ Token: "tok-1",+ Title: alertmanagertypes.DefaultIncidentIOTitleTemplate,+ Description: alertmanagertypes.DefaultIncidentIODescriptionTemplate,+ HTTPConfig: &commoncfg.HTTPClientConfig{},+ }, tmpl, slog.New(slog.DiscardHandler), alertmanagertemplate.New(tmpl, slog.New(slog.DiscardHandler)))+ require.NoError(t, err)+ return n+}++func alert(firing bool) *types.Alert {+ a := &types.Alert{Alert: model.Alert{+ Labels: model.LabelSet{+ "alertname": "HighCPU",+ "severity": "critical",+ "ruleSource": "https://signoz.example/alerts/edit?ruleId=1",+ },+ Annotations: model.LabelSet{"summary": "cpu high", "related_logs": "https://signoz.example/logs?q=1"},+ GeneratorURL: "https://signoz.example/alerts/edit?ruleId=1",+ StartsAt: time.Now().Add(-time.Minute),+ }}+ if firing {+ a.EndsAt = time.Now().Add(time.Hour)+ } else {+ a.EndsAt = time.Now().Add(-time.Minute)+ }+ return a+}++func ctx() context.Context {+ return notify.WithGroupKey(context.Background(), "test-incidentio")+}++func TestNotifyFiringEvent(t *testing.T) {+ m := newMockIncidentIO(t)+ retry, err := newNotifier(t, m).Notify(ctx(), alert(true))+ require.NoError(t, err)+ assert.False(t, retry)++ ev := m.lastEvent(t)+ assert.Equal(t, "[FIRING:1] HighCPU", ev.Title)+ assert.Equal(t, "firing", ev.Status)+ assert.NotEmpty(t, ev.DeduplicationKey)+ assert.Equal(t, "https://signoz.example/alerts/edit?ruleId=1", ev.SourceURL)+ assert.Contains(t, ev.Description, "**Alert:** HighCPU (critical)")+ assert.Contains(t, ev.Description, "**Summary:** cpu high")+ assert.Contains(t, ev.Description, "[View in SigNoz](https://signoz.example/alerts/edit?ruleId=1)")+ assert.Contains(t, ev.Description, "[View related logs](https://signoz.example/logs?q=1)")+ assert.Equal(t, map[string]string{+ "alertname": "HighCPU",+ "severity": "critical",+ "ruleSource": "https://signoz.example/alerts/edit?ruleId=1",+ }, ev.Metadata)+ assert.Equal(t, "Bearer tok-1", m.auths[0])+}++func TestNotifyResolvedEventReusesDedupKey(t *testing.T) {+ m := newMockIncidentIO(t)+ n := newNotifier(t, m)++ _, err := n.Notify(ctx(), alert(true))+ require.NoError(t, err)+ firingKey := m.lastEvent(t).DeduplicationKey++ _, err = n.Notify(ctx(), alert(false))+ require.NoError(t, err)++ ev := m.lastEvent(t)+ assert.Equal(t, "resolved", ev.Status)+ assert.Equal(t, firingKey, ev.DeduplicationKey)+}++func TestNotifyPermanentFailureDoesNotRetry(t *testing.T) {+ m := newMockIncidentIO(t)+ m.status = http.StatusUnprocessableEntity++ retry, err := newNotifier(t, m).Notify(ctx(), alert(true))+ require.Error(t, err)+ assert.False(t, retry)+ assert.Contains(t, err.Error(), "Deduplication key is required") // response body surfaces to the user+}++func TestNotifyRateLimitRetries(t *testing.T) {+ m := newMockIncidentIO(t)+ m.status = http.StatusTooManyRequests++ retry, err := newNotifier(t, m).Notify(ctx(), alert(true))+ require.Error(t, err)+ assert.True(t, retry)+}++func TestNotifyMergesChannelMetadata(t *testing.T) {+ m := newMockIncidentIO(t)+ tmpl := test.CreateTmpl(t)+ n, err := New(&alertmanagertypes.IncidentIOReceiverConfig{+ URL: m.srv.URL + "/v2/alert_events/http/src-1",+ Token: "tok-1",+ Title: alertmanagertypes.DefaultIncidentIOTitleTemplate,+ Description: alertmanagertypes.DefaultIncidentIODescriptionTemplate,+ HTTPConfig: &commoncfg.HTTPClientConfig{},+ Metadata: map[string]string{+ "env": "prod",+ "sev": "{{ .CommonLabels.severity }}",+ "alertname": "channel-wins",+ "broken": "{{ .Nope",+ },+ }, tmpl, slog.New(slog.DiscardHandler), alertmanagertemplate.New(tmpl, slog.New(slog.DiscardHandler)))+ require.NoError(t, err)++ _, err = n.Notify(ctx(), alert(true))+ require.NoError(t, err) // a broken metadata template must not fail delivery++ md := m.lastEvent(t).Metadata+ assert.Equal(t, "prod", md["env"])+ assert.Equal(t, "critical", md["sev"]) // values are template-expanded+ assert.Equal(t, "channel-wins", md["alertname"]) // channel overrides the rule label+ assert.Equal(t, "{{ .Nope", md["broken"]) // unexpandable value sent raw+ assert.Equal(t, "critical", md["severity"]) // rule labels still present+}++func TestNotifyEmptyTitleFallsBackToRuleName(t *testing.T) {+ m := newMockIncidentIO(t)+ tmpl := test.CreateTmpl(t)+ n, err := New(&alertmanagertypes.IncidentIOReceiverConfig{+ URL: m.srv.URL + "/v2/alert_events/http/src-1",+ Token: "tok-1",+ Title: `{{ .CommonLabels.nonexistent }}`,+ Description: alertmanagertypes.DefaultIncidentIODescriptionTemplate,+ HTTPConfig: &commoncfg.HTTPClientConfig{},+ }, tmpl, slog.New(slog.DiscardHandler), alertmanagertemplate.New(tmpl, slog.New(slog.DiscardHandler)))+ require.NoError(t, err)++ _, err = n.Notify(ctx(), alert(true))+ require.NoError(t, err)++ assert.Equal(t, "HighCPU", m.lastEvent(t).Title)+}++func TestNotifyTruncatesLongDescription(t *testing.T) {+ m := newMockIncidentIO(t)+ a := alert(true)+ a.Annotations["description"] = model.LabelValue(strings.Repeat("x", maxDescriptionLenRunes+1000))++ _, err := newNotifier(t, m).Notify(ctx(), a)+ require.NoError(t, err)++ desc := []rune(m.lastEvent(t).Description)+ assert.LessOrEqual(t, len(desc), maxDescriptionLenRunes)+ assert.Equal(t, '…', desc[len(desc)-1])+}diff --git a/pkg/alertmanager/alertmanagernotify/receiver.go b/pkg/alertmanager/alertmanagernotify/receiver.goindex bdc3d14c4c..f7f561b0fe 100644--- a/pkg/alertmanager/alertmanagernotify/receiver.go+++ b/pkg/alertmanager/alertmanagernotify/receiver.go@@ -6,6 +6,7 @@ import ("github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/email""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/googlechat"+ "github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/incidentio""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/jira""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/jsmops""github.com/SigNoz/signoz/pkg/alertmanager/alertmanagernotify/msteamsv2"@@ -30,6 +31,7 @@ var customNotifierIntegrations = []string{googlechat.Integration,jira.Integration,jsmops.Integration,+ incidentio.Integration,}func NewReceiverIntegrations(nc *alertmanagertypes.Receiver, tmpl *template.Template, logger *slog.Logger, templater alertmanagertypes.Templater) ([]notify.Integration, error) {@@ -95,6 +97,11 @@ func NewReceiverIntegrations(nc *alertmanagertypes.Receiver, tmpl *template.Tempreturn jsmops.New(c, tmpl, l, templater, true)})}+ for i, c := range nc.IncidentIOConfigs {+ add(incidentio.Integration, i, c, func(l *slog.Logger) (notify.Notifier, error) {+ return incidentio.New(c, tmpl, l, templater)+ })+ }if errs.Len() > 0 {return nil, &errsdiff --git a/pkg/types/alertmanagertypes/config.go b/pkg/types/alertmanagertypes/config.goindex 7505cfea23..82c52e8aad 100644--- a/pkg/types/alertmanagertypes/config.go+++ b/pkg/types/alertmanagertypes/config.go@@ -72,10 +72,11 @@ type customReceiverConfigs struct {GoogleChat []*GoogleChatReceiverConfigJira []*JiraReceiverConfigJSMOps []*JSMOpsReceiverConfig+ IncidentIO []*IncidentIOReceiverConfig}func (c customReceiverConfigs) isEmpty() bool {- return len(c.GoogleChat) == 0 && len(c.Jira) == 0 && len(c.JSMOps) == 0+ return len(c.GoogleChat) == 0 && len(c.Jira) == 0 && len(c.JSMOps) == 0 && len(c.IncidentIO) == 0}func customConfigsOf(receiver *Receiver) customReceiverConfigs {@@ -83,6 +84,7 @@ func customConfigsOf(receiver *Receiver) customReceiverConfigs {GoogleChat: receiver.GoogleChatConfigs,Jira: receiver.JiraConfigs,JSMOps: receiver.JSMOpsConfigs,+ IncidentIO: receiver.IncidentIOConfigs,}}@@ -193,6 +195,7 @@ func extendedReceivers(c *config.Config, customConfigs map[string]customReceiverGoogleChatConfigs: custom.GoogleChat,JiraConfigs: custom.Jira,JSMOpsConfigs: custom.JSMOps,+ IncidentIOConfigs: custom.IncidentIO,}}@@ -370,6 +373,7 @@ func (c *Config) GetReceiver(name string) (*Receiver, error) {GoogleChatConfigs: custom.GoogleChat,JiraConfigs: custom.Jira,JSMOpsConfigs: custom.JSMOps,+ IncidentIOConfigs: custom.IncidentIO,}, nil}}@@ -459,6 +463,11 @@ func (c *Config) applyNativeDefaults() {jc.HTTPConfig = httpDefault}}+ for _, ic := range custom.IncidentIO {+ if ic.HTTPConfig == nil {+ ic.HTTPConfig = httpDefault+ }+ }}}diff --git a/pkg/types/alertmanagertypes/incidentio.go b/pkg/types/alertmanagertypes/incidentio.gonew file mode 100644index 0000000000..2a06a54be0--- /dev/null+++ b/pkg/types/alertmanagertypes/incidentio.go@@ -0,0 +1,109 @@+package alertmanagertypes++import (+ "fmt"+ "net/url"+ "strings"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/prometheus/alertmanager/config"+ commoncfg "github.com/prometheus/common/config"+)++// incidentIOEventsPathPrefix is the path of incident.io's HTTP alert source+// endpoint (Alert Events V2 API). The full URL is per-source:+// https://api.incident.io/v2/alert_events/http/<source_config_id>.+const incidentIOEventsPathPrefix = "/v2/alert_events/http/"++// The description is markdown; incident.io renders it natively. The templates+// mirror Google Chat / Jira / JSM for a consistent default across channels.+const (+ DefaultIncidentIOTitleTemplate = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`++ DefaultIncidentIODescriptionTemplate = `{{ 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 }}{{ if .GeneratorURL }}[View in SigNoz]({{ .GeneratorURL }})++{{ end }}{{ if .Annotations.related_logs }}[View related logs]({{ .Annotations.related_logs }})++{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})++{{ end }}{{ end }}`+)++// IncidentIOReceiverConfig is the SigNoz incident.io receiver, backed by an+// incident.io HTTP alert source. URL is the per-source alert events endpoint+// and Token its secret, both copied from the source's setup page.+type IncidentIOReceiverConfig struct {+ config.NotifierConfig `yaml:",inline" json:",inline"`++ HTTPConfig *commoncfg.HTTPClientConfig `yaml:"http_config,omitempty" json:"http_config,omitempty"`++ URL string `yaml:"url,omitempty" json:"url,omitempty"`+ Token config.Secret `yaml:"token,omitempty" json:"token,omitempty"`+ Title string `yaml:"title,omitempty" json:"title,omitempty"`+ Description string `yaml:"description,omitempty" json:"description,omitempty"`+ // Metadata is merged into the event's metadata on top of the group's common+ // labels (channel wins on key clash). Values are template-expanded.+ Metadata map[string]string `yaml:"metadata,omitempty" json:"metadata,omitempty"`+}++// send_resolved has no omitempty upstream, so a var default here is overwritten+// by the yaml round-trip to the request value (false when omitted); the UI sends+// it explicitly, defaulted on, so incident.io alerts resolve with the rule.+var DefaultIncidentIOReceiverConfig = IncidentIOReceiverConfig{+ NotifierConfig: config.NotifierConfig{+ VSendResolved: false,+ },+ Title: DefaultIncidentIOTitleTemplate,+ Description: DefaultIncidentIODescriptionTemplate,+}++func (c *IncidentIOReceiverConfig) UnmarshalYAML(unmarshal func(any) error) error {+ *c = DefaultIncidentIOReceiverConfig+ type plain IncidentIOReceiverConfig+ if err := unmarshal((*plain)(c)); err != nil {+ return err+ }++ if c.Title == "" {+ c.Title = DefaultIncidentIOTitleTemplate+ }+ if c.Description == "" {+ c.Description = DefaultIncidentIODescriptionTemplate+ }++ // Values are stored and sent exactly as configured, so anything that is+ // not already canonical is rejected rather than rewritten.+ if c.URL != strings.TrimSpace(c.URL) {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "incidentio url must not have leading or trailing whitespace")+ }+ u, err := url.Parse(c.URL)+ if c.URL == "" || err != nil || u.Scheme != "https" || u.Host == "" ||+ !strings.Contains(u.Path, incidentIOEventsPathPrefix) ||+ strings.HasSuffix(u.Path, incidentIOEventsPathPrefix) {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, fmt.Sprintf("incidentio url must be an alert events URL (https://api.incident.io%s<source_config_id>)", incidentIOEventsPathPrefix))+ }+ if strings.HasSuffix(c.URL, "/") {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "incidentio url must not end with a trailing slash")+ }++ token := string(c.Token)+ if token == "" {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "incidentio token is required")+ }+ if token != strings.TrimSpace(token) {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "incidentio token must not have leading or trailing whitespace")+ }+ // incident.io's setup page shows the header value as "Bearer <token>"; a+ // pasted prefix would be sent doubled, so reject it instead.+ if strings.EqualFold(token, "bearer") || (len(token) >= 7 && strings.EqualFold(token[:7], "bearer ")) {+ return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "incidentio token must be the source's secret token only, without the Bearer prefix")+ }+ return nil+}diff --git a/pkg/types/alertmanagertypes/incidentio_test.go b/pkg/types/alertmanagertypes/incidentio_test.gonew file mode 100644index 0000000000..bbdaed3c02--- /dev/null+++ b/pkg/types/alertmanagertypes/incidentio_test.go@@ -0,0 +1,65 @@+package alertmanagertypes++import (+ "fmt"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++const testIncidentIOURL = "https://api.incident.io/v2/alert_events/http/01M0D1JNVBGBGVTWX053EM12XV"++func TestIncidentIOReceiverConfigDefaults(t *testing.T) {+ r, err := NewReceiver(fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s","token":"tok-123"}]}`, testIncidentIOURL))+ require.NoError(t, err)+ require.Len(t, r.IncidentIOConfigs, 1)++ c := r.IncidentIOConfigs[0]+ assert.Equal(t, testIncidentIOURL, c.URL)+ assert.Equal(t, "tok-123", string(c.Token))+ assert.Equal(t, DefaultIncidentIOTitleTemplate, c.Title)+ assert.Equal(t, DefaultIncidentIODescriptionTemplate, c.Description)+ assert.False(t, c.SendResolved()) // default off when omitted, like other channels++ ch, err := NewChannelFromReceiver(r, "org-1")+ require.NoError(t, err)+ assert.Equal(t, "incidentio", ch.Type)+}++func TestIncidentIOReceiverConfigOverrides(t *testing.T) {+ r, err := NewReceiver(fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s","token":"k","title":"t","description":"d","send_resolved":true}]}`, testIncidentIOURL))+ require.NoError(t, err)+ require.Len(t, r.IncidentIOConfigs, 1)++ c := r.IncidentIOConfigs[0]+ assert.Equal(t, testIncidentIOURL, c.URL)+ assert.Equal(t, "t", c.Title)+ assert.Equal(t, "d", c.Description)+ assert.True(t, c.SendResolved())+}++func TestIncidentIOReceiverConfigValidation(t *testing.T) {+ cases := []struct {+ name string+ json string+ }{+ {"missing url", `{"name":"incio","incidentio_configs":[{"token":"k"}]}`},+ {"http url", `{"name":"incio","incidentio_configs":[{"url":"http://api.incident.io/v2/alert_events/http/abc","token":"k"}]}`},+ {"not an alert events url", `{"name":"incio","incidentio_configs":[{"url":"https://api.incident.io/v2/incidents","token":"k"}]}`},+ {"missing source config id", `{"name":"incio","incidentio_configs":[{"url":"https://api.incident.io/v2/alert_events/http/","token":"k"}]}`},+ {"trailing slash", fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s/","token":"k"}]}`, testIncidentIOURL)},+ {"whitespace around url", fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":" %s ","token":"k"}]}`, testIncidentIOURL)},+ {"missing token", fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s"}]}`, testIncidentIOURL)},+ {"bearer prefixed token", fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s","token":"Bearer tok-123"}]}`, testIncidentIOURL)},+ {"lowercase bearer prefixed token", fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s","token":"bearer tok-123"}]}`, testIncidentIOURL)},+ {"bearer only token", fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s","token":"Bearer"}]}`, testIncidentIOURL)},+ {"whitespace around token", fmt.Sprintf(`{"name":"incio","incidentio_configs":[{"url":"%s","token":" tok-123 "}]}`, testIncidentIOURL)},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ _, err := NewReceiver(c.json)+ assert.Error(t, err)+ })+ }+}diff --git a/pkg/types/alertmanagertypes/receiver.go b/pkg/types/alertmanagertypes/receiver.goindex d6752a08c8..1c84c0cd61 100644--- a/pkg/types/alertmanagertypes/receiver.go+++ b/pkg/types/alertmanagertypes/receiver.go@@ -28,6 +28,9 @@ type Receiver struct {JiraConfigs []*JiraReceiverConfig `json:"jira_configs,omitempty" yaml:"jira_configs,omitempty"`// JSM Ops (ex-Opsgenie alert API); delivered by reusing the Opsgenie notifier.JSMOpsConfigs []*JSMOpsReceiverConfig `json:"jsmops_configs,omitempty" yaml:"jsmops_configs,omitempty"`+ // Shadows upstream's incidentio_configs so our custom notifier (templater,+ // group-key dedup, label metadata) handles it instead of upstream's.+ IncidentIOConfigs []*IncidentIOReceiverConfig `json:"incidentio_configs,omitempty" yaml:"incidentio_configs,omitempty"`}// NewReceiver builds a Receiver from its JSON input, applying each notifier@@ -72,6 +75,14 @@ func NewReceiver(input string) (*Receiver, error) {receiver.JSMOpsConfigs[i] = defaulted}+ for i, ic := range receiver.IncidentIOConfigs {+ defaulted, err := defaultedNotifierConfig(ic)+ if err != nil {+ return nil, err+ }+ receiver.IncidentIOConfigs[i] = defaulted+ }+return receiver, nil}