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 final leg (#12335)
Ashwin Bhatkal06dd0ed3d38c
diff --git a/frontend/public/locales/en-GB/channels.json b/frontend/public/locales/en-GB/channels.jsonindex 4c1980fe9d..8553d8c88d 100644--- a/frontend/public/locales/en-GB/channels.json+++ b/frontend/public/locales/en-GB/channels.json@@ -24,6 +24,8 @@"tooltip_opsgenie_api_key": "Learn how to obtain the API key from your OpsGenie account [here](https://support.atlassian.com/opsgenie/docs/integrate-opsgenie-with-prometheus/).","tooltip_email_to": "Enter email addresses separated by commas.","tooltip_ms_teams_url": "The URL of the Microsoft Teams [webhook](https://support.microsoft.com/en-us/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498) to send alerts to. Learn more about Microsoft Teams integration in the docs [here](https://signoz.io/docs/alerts-management/notification-channel/ms-teams/).",+ "tooltip_google_chat_url": "The URL of the Google Chat space [incoming webhook](https://developers.google.com/workspace/chat/quickstart/webhooks) to send alerts to. It must be an https URL on chat.googleapis.com.",+ "google_chat_webhook_url_invalid": "Webhook URL must be an https URL on chat.googleapis.com","field_slack_recipient": "Recipient","field_slack_title": "Title",diff --git a/frontend/public/locales/en/channels.json b/frontend/public/locales/en/channels.jsonindex 5068e125f7..26786a32b9 100644--- a/frontend/public/locales/en/channels.json+++ b/frontend/public/locales/en/channels.json@@ -24,6 +24,8 @@"tooltip_opsgenie_api_key": "Learn how to obtain the API key from your OpsGenie account [here](https://support.atlassian.com/opsgenie/docs/integrate-opsgenie-with-prometheus/).","tooltip_email_to": "Enter email addresses separated by commas.","tooltip_ms_teams_url": "The URL of the Microsoft Teams [webhook](https://support.microsoft.com/en-us/office/create-incoming-webhooks-with-workflows-for-microsoft-teams-8ae491c7-0394-4861-ba59-055e33f75498) to send alerts to. Learn more about Microsoft Teams integration in the docs [here](https://signoz.io/docs/alerts-management/notification-channel/ms-teams/).",+ "tooltip_google_chat_url": "The URL of the Google Chat space [incoming webhook](https://developers.google.com/workspace/chat/quickstart/webhooks) to send alerts to. It must be an https URL on chat.googleapis.com.",+ "google_chat_webhook_url_invalid": "Webhook URL must be an https URL on chat.googleapis.com","field_slack_recipient": "Recipient","field_slack_title": "Title","field_slack_description": "Description",diff --git a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsxindex 83ab7e33ab..3602e6e1b1 100644--- a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx+++ b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx@@ -1,18 +1,28 @@import CreateAlertChannels from 'container/CreateAlertChannels';import { ChannelType } from 'container/CreateAlertChannels/config';+import { GoogleChatInitialConfig } from 'container/CreateAlertChannels/defaults';import {+ googleChatDescriptionDefaultValue,+ googleChatTitleDefaultValue,opsGenieDescriptionDefaultValue,opsGenieMessageDefaultValue,opsGeniePriorityDefaultValue,pagerDutyAdditionalDetailsDefaultValue,- pagerDutyDescriptionDefaultVaule,+ pagerDutyDescriptionDefaultValue,pagerDutySeverityTextDefaultValue,slackDescriptionDefaultValue,slackTitleDefaultValue,} from 'mocks-server/__mockdata__/alerts';import { server } from 'mocks-server/server';import { rest } from 'msw';-import { act, fireEvent, render, screen, waitFor } from 'tests/test-utils';+import {+ act,+ fireEvent,+ render,+ screen,+ userEvent,+ waitFor,+} from 'tests/test-utils';import { testLabelInputAndHelpValue } from './testUtils';@@ -225,7 +235,7 @@ describe('Create Alert Channel', () => {);expect(descriptionTextArea).toHaveTextContent(- pagerDutyDescriptionDefaultVaule,+ pagerDutyDescriptionDefaultValue,);});it('Should check if Severity label, info (help_pager_severity), and textbox are displayed properly', () => {@@ -419,5 +429,150 @@ describe('Create Alert Channel', () => {expect(descriptionTextArea).toHaveTextContent(slackDescriptionDefaultValue);});});+ describe('Google Chat', () => {+ const validWebhookUrl =+ 'https://chat.googleapis.com/v1/spaces/AAAA/messages?key=dummy_key&token=dummy_token';++ beforeEach(() => {+ render(<CreateAlertChannels preType={ChannelType.GoogleChat} />);+ });++ it('Should check if the selected item in the type dropdown has text "Google Chat"', () => {+ expect(screen.getByText('Google Chat')).toBeInTheDocument();+ });++ it('Should check if Webhook URL label and input are displayed properly', () => {+ testLabelInputAndHelpValue({+ labelText: 'field_webhook_url',+ testId: 'webhook-url-textbox',+ });+ });++ it('Should check if Title contains the google chat template', () => {+ expect(screen.getByTestId('title-textarea')).toHaveTextContent(+ googleChatTitleDefaultValue,+ );+ });++ it('Should check if Description contains the google chat template', () => {+ expect(screen.getByTestId('description-textarea')).toHaveTextContent(+ googleChatDescriptionDefaultValue,+ );+ });++ it('Should check if saving with a webhook url outside chat.googleapis.com displays error notification', async () => {+ const user = userEvent.setup();++ await user.type(+ screen.getByTestId('channel-name-textbox'),+ 'gchat-channel',+ );+ await user.type(+ screen.getByTestId('webhook-url-textbox'),+ 'https://example.com/webhook',+ );++ await user.click(screen.getByTestId('save-channel-button'));++ await waitFor(() =>+ expect(errorNotification).toHaveBeenCalledWith({+ message: 'Error',+ description: 'google_chat_webhook_url_invalid',+ }),+ );+ });++ it('Should check if saving sends a googlechat_configs payload', async () => {+ let requestBody: unknown;+ server.use(+ rest.post('http://localhost/api/v1/channels', async (req, res, ctx) => {+ requestBody = await req.json();+ return res(+ ctx.status(201),+ ctx.json({ status: 'success', data: 'channel created' }),+ );+ }),+ );++ const user = userEvent.setup();++ await user.type(+ screen.getByTestId('channel-name-textbox'),+ 'gchat-channel',+ );+ await user.type(screen.getByTestId('webhook-url-textbox'), validWebhookUrl);++ await user.click(screen.getByTestId('save-channel-button'));++ await waitFor(() =>+ expect(successNotification).toHaveBeenCalledWith({+ message: 'Success',+ description: 'channel_creation_done',+ }),+ );++ expect(requestBody).toStrictEqual({+ name: 'gchat-channel',+ googlechat_configs: [+ {+ webhook_url: validWebhookUrl,+ title: GoogleChatInitialConfig.title,+ text: GoogleChatInitialConfig.text,+ send_resolved: true,+ },+ ],+ });+ });+ });+ describe('Changing the channel type', () => {+ async function selectType(+ user: ReturnType<typeof userEvent.setup>,+ optionText: string,+ ): Promise<void> {+ // the type dropdown opens on the inner search input of the antd select+ await user.click(screen.getByRole('combobox'));+ await user.click(await screen.findByTitle(optionText));+ }++ it('Should check if switching to Google Chat and back swaps the prefilled templates', async () => {+ const user = userEvent.setup();+ render(<CreateAlertChannels preType={ChannelType.Slack} />);++ await selectType(user, 'Google Chat');++ await waitFor(() =>+ expect(screen.getByTestId('title-textarea')).toHaveTextContent(+ googleChatTitleDefaultValue,+ ),+ );+ expect(screen.getByTestId('description-textarea')).toHaveTextContent(+ googleChatDescriptionDefaultValue,+ );++ await selectType(user, 'Slack');++ await waitFor(() =>+ expect(screen.getByTestId('title-textarea')).toHaveTextContent(+ slackTitleDefaultValue,+ ),+ );+ expect(screen.getByTestId('description-textarea')).toHaveTextContent(+ slackDescriptionDefaultValue,+ );+ });++ it('Should check if switching to Pagerduty prefills the pagerduty description and not the opsgenie one', async () => {+ const user = userEvent.setup();+ render(<CreateAlertChannels preType={ChannelType.Opsgenie} />);++ await selectType(user, 'Pagerduty');++ await waitFor(() =>+ expect(screen.getByTestId('pager-description-textarea')).toHaveTextContent(+ pagerDutyDescriptionDefaultValue,+ ),+ );+ });+ });});});diff --git a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannelNormalUser.test.tsx b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannelNormalUser.test.tsxindex ae41548b31..119c75f8da 100644--- a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannelNormalUser.test.tsx+++ b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannelNormalUser.test.tsx@@ -5,7 +5,7 @@ import {opsGenieMessageDefaultValue,opsGeniePriorityDefaultValue,pagerDutyAdditionalDetailsDefaultValue,- pagerDutyDescriptionDefaultVaule,+ pagerDutyDescriptionDefaultValue,pagerDutySeverityTextDefaultValue,slackDescriptionDefaultValue,slackTitleDefaultValue,@@ -150,7 +150,7 @@ describe('Create Alert Channel (Normal User)', () => {);expect(descriptionTextArea).toHaveTextContent(- pagerDutyDescriptionDefaultVaule,+ pagerDutyDescriptionDefaultValue,);});it('Should check if Severity label, info (help_pager_severity), and textbox are displayed properly', () => {diff --git a/frontend/src/container/CreateAlertChannels/config.ts b/frontend/src/container/CreateAlertChannels/config.tsindex 3ee3882cc1..59ca50ac0b 100644--- a/frontend/src/container/CreateAlertChannels/config.ts+++ b/frontend/src/container/CreateAlertChannels/config.ts@@ -104,6 +104,7 @@ export enum ChannelType {Pagerduty = 'pagerduty',Opsgenie = 'opsgenie',MsTeams = 'msteams',+ GoogleChat = 'googlechat',}// LabelFilterStatement will be used for preparing filter conditions / matchers@@ -125,3 +126,11 @@ export interface MsTeamsChannel extends Channel {title?: string;text?: string;}++export interface GoogleChatChannel extends Channel {+ // incoming webhook url of the google chat space, must be an+ // https url on chat.googleapis.com+ webhook_url?: string;+ title?: string;+ text?: string;+}diff --git a/frontend/src/container/CreateAlertChannels/defaults.ts b/frontend/src/container/CreateAlertChannels/defaults.tsindex 10c23f1303..3214babfd6 100644--- a/frontend/src/container/CreateAlertChannels/defaults.ts+++ b/frontend/src/container/CreateAlertChannels/defaults.ts@@ -1,4 +1,51 @@-import { EmailChannel, OpsgenieChannel, PagerChannel } from './config';+import {+ ChannelType,+ EmailChannel,+ GoogleChatChannel,+ MsTeamsChannel,+ OpsgenieChannel,+ PagerChannel,+ SlackChannel,+ WebhookChannel,+} from './config';++// shared by slack and ms teams, both render the same title / description boxes+export const SlackInitialConfig: Partial<SlackChannel> = {+ text: `{{ range .Alerts -}}+ *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}++ *Summary:* {{ .Annotations.summary }}+ *Description:* {{ .Annotations.description }}+ *RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}+ *RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}++ *Details:*+ {{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}+ {{ end }}+ {{ end }}`,+ title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}+ {{- if gt (len .CommonLabels) (len .GroupLabels) -}}+ {{" "}}(+ {{- with .CommonLabels.Remove .GroupLabels.Names }}+ {{- range $index, $label := .SortedPairs -}}+ {{ if $index }}, {{ end }}+ {{- $label.Name }}="{{ $label.Value -}}"+ {{- end }}+ {{- end -}}+ )+ {{- end }}`,+};++// mirrors DefaultGoogleChatReceiverConfig in pkg/types/alertmanagertypes/googlechat.go,+// which the backend applies when title / text are left empty+export const GoogleChatInitialConfig: Partial<GoogleChatChannel> = {+ 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 }}+{{ end }}`,+};export const PagerInitialConfig: Partial<PagerChannel> = {description: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}@@ -446,3 +493,26 @@ export const EmailInitialConfig: Partial<EmailChannel> = {</body></html>`,};++// prefilled values of every channel type, keyed by type so the form can apply+// exactly one set of defaults and swap it when the type changes+export const ChannelInitialConfig: Record<+ ChannelType,+ Partial<+ SlackChannel &+ WebhookChannel &+ PagerChannel &+ MsTeamsChannel &+ OpsgenieChannel &+ EmailChannel &+ GoogleChatChannel+ >+> = {+ [ChannelType.Slack]: SlackInitialConfig,+ [ChannelType.MsTeams]: SlackInitialConfig,+ [ChannelType.GoogleChat]: GoogleChatInitialConfig,+ [ChannelType.Pagerduty]: PagerInitialConfig,+ [ChannelType.Opsgenie]: OpsgenieInitialConfig,+ [ChannelType.Email]: EmailInitialConfig,+ [ChannelType.Webhook]: {},+};diff --git a/frontend/src/container/CreateAlertChannels/index.tsx b/frontend/src/container/CreateAlertChannels/index.tsxindex 5944b802a4..a2134a4283 100644--- a/frontend/src/container/CreateAlertChannels/index.tsx+++ b/frontend/src/container/CreateAlertChannels/index.tsx@@ -14,16 +14,24 @@ import testPagerApi from 'api/channels/testPager';import testSlackApi from 'api/channels/testSlack';import testWebhookApi from 'api/channels/testWebhook';import logEvent from 'api/common/logEvent';+import {+ useCreateChannel,+ useTestChannel,+} from 'api/generated/services/channels';+import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';+import { ErrorType } from 'api/generatedAPIInstance';import ROUTES from 'constants/routes';import FormAlertChannels from 'container/FormAlertChannels';import { useNotifications } from 'hooks/useNotifications';import history from 'lib/history';import { useErrorModal } from 'providers/ErrorModalProvider';import APIError from 'types/api/error';+import { toAPIError } from 'utils/errorUtils';import {ChannelType,EmailChannel,+ GoogleChatChannel,MsTeamsChannel,OpsgenieChannel,PagerChannel,@@ -31,12 +39,12 @@ import {ValidatePagerChannel,WebhookChannel,} from './config';+import { ChannelInitialConfig } from './defaults';import {- EmailInitialConfig,- OpsgenieInitialConfig,- PagerInitialConfig,-} from './defaults';-import { isChannelType } from './utils';+ isChannelType,+ isValidGoogleChatWebhookURL,+ prepareGoogleChatRequest,+} from './utils';import './CreateAlertChannels.styles.scss';@@ -60,69 +68,38 @@ function CreateAlertChannels({PagerChannel &MsTeamsChannel &OpsgenieChannel &- EmailChannel+ EmailChannel &+ GoogleChatChannel>- >({+ >(() => ({send_resolved: true,- text: `{{ range .Alerts -}}- *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}-- *Summary:* {{ .Annotations.summary }}- *Description:* {{ .Annotations.description }}- *RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}}- *RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}}-- *Details:*- {{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}- {{ end }}- {{ end }}`,- title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}- {{- if gt (len .CommonLabels) (len .GroupLabels) -}}- {{" "}}(- {{- with .CommonLabels.Remove .GroupLabels.Names }}- {{- range $index, $label := .SortedPairs -}}- {{ if $index }}, {{ end }}- {{- $label.Name }}="{{ $label.Value -}}"- {{- end }}- {{- end -}}- )- {{- end }}`,- });+ ...ChannelInitialConfig[preType],+ }));const [savingState, setSavingState] = useState<boolean>(false);const [testingState, setTestingState] = useState<boolean>(false);const { notifications } = useNotifications();+ const { mutateAsync: createChannel } = useCreateChannel();+ const { mutateAsync: testChannel } = useTestChannel();+const [type, setType] = useState<ChannelType>(preType);const onTypeChangeHandler = useCallback((value: string) => {- const currentType = type;- setType(value as ChannelType);-- if (value === ChannelType.Pagerduty && currentType !== value) {- // reset config to pager defaults- setSelectedConfig({- name: selectedConfig?.name,- send_resolved: selectedConfig.send_resolved,- ...PagerInitialConfig,- });+ const nextType = value as ChannelType;+ if (nextType === type) {+ return;}- if (value === ChannelType.Opsgenie && currentType !== value) {- setSelectedConfig((selectedConfig) => ({- ...selectedConfig,- ...OpsgenieInitialConfig,- }));- }+ setType(nextType);- // reset config to email defaults- if (value === ChannelType.Email && currentType !== value) {- setSelectedConfig((selectedConfig) => ({- ...selectedConfig,- ...EmailInitialConfig,- }));- }+ // the fields the types share (title, text, description) keep the value of+ // the type that was selected before, so the new type's defaults have to be+ // written to both the config and the form+ const defaults = ChannelInitialConfig[nextType];+ setSelectedConfig((selectedConfig) => ({ ...selectedConfig, ...defaults }));+ formInstance.setFieldsValue(defaults);},- [type, selectedConfig],+ [type, formInstance],);const prepareSlackRequest = useCallback(@@ -407,6 +384,56 @@ function CreateAlertChannels({showErrorModal,]);+ const validateGoogleChatConfig = useCallback((): boolean => {+ if (!selectedConfig.webhook_url) {+ notifications.error({+ message: 'Error',+ description: t('webhook_url_required'),+ });+ return false;+ }++ if (!isValidGoogleChatWebhookURL(selectedConfig.webhook_url)) {+ notifications.error({+ message: 'Error',+ description: t('google_chat_webhook_url_invalid'),+ });+ return false;+ }++ return true;+ }, [selectedConfig.webhook_url, notifications, t]);++ const onGoogleChatHandler = useCallback(async () => {+ if (!validateGoogleChatConfig()) {+ return { status: 'failed', statusMessage: t('channel_creation_failed') };+ }++ setSavingState(true);++ try {+ await createChannel({ data: prepareGoogleChatRequest(selectedConfig) });+ notifications.success({+ message: 'Success',+ description: t('channel_creation_done'),+ });+ history.replace(ROUTES.ALL_CHANNELS);+ return { status: 'success', statusMessage: t('channel_creation_done') };+ } catch (error) {+ showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));+ return { status: 'failed', statusMessage: t('channel_creation_failed') };+ } finally {+ setSavingState(false);+ }+ }, [+ validateGoogleChatConfig,+ createChannel,+ selectedConfig,+ notifications,+ t,+ showErrorModal,+ ]);+const onSaveHandler = useCallback(async (value: ChannelType) => {if (!selectedConfig.name) {@@ -424,6 +451,7 @@ function CreateAlertChannels({[ChannelType.Opsgenie]: onOpsgenieHandler,[ChannelType.MsTeams]: onMsTeamsHandler,[ChannelType.Email]: onEmailHandler,+ [ChannelType.GoogleChat]: onGoogleChatHandler,};if (isChannelType(value)) {@@ -455,6 +483,7 @@ function CreateAlertChannels({onOpsgenieHandler,onMsTeamsHandler,onEmailHandler,+ onGoogleChatHandler,notifications,t,],@@ -492,6 +521,13 @@ function CreateAlertChannels({request = prepareEmailRequest();await testEmail(request);break;+ case ChannelType.GoogleChat:+ if (!validateGoogleChatConfig()) {+ setTestingState(false);+ return;+ }+ await testChannel({ data: prepareGoogleChatRequest(selectedConfig) });+ break;default:notifications.error({message: 'Error',@@ -513,7 +549,11 @@ function CreateAlertChannels({status: 'Test success',});} catch (error) {- showErrorModal(error as APIError);+ showErrorModal(+ error instanceof APIError+ ? error+ : toAPIError(error as ErrorType<RenderErrorResponseDTO>),+ );logEvent('Alert Channel: Test notification', {type: channelType,@@ -535,6 +575,8 @@ function CreateAlertChannels({prepareSlackRequest,prepareMsTeamsRequest,prepareEmailRequest,+ validateGoogleChatConfig,+ testChannel,notifications,],);@@ -562,9 +604,6 @@ function CreateAlertChannels({initialValue: {type,...selectedConfig,- ...PagerInitialConfig,- ...OpsgenieInitialConfig,- ...EmailInitialConfig,},}}/>diff --git a/frontend/src/container/CreateAlertChannels/utils.ts b/frontend/src/container/CreateAlertChannels/utils.tsindex ce7520a9f1..55ee6b5f35 100644--- a/frontend/src/container/CreateAlertChannels/utils.ts+++ b/frontend/src/container/CreateAlertChannels/utils.ts@@ -1,4 +1,39 @@-import { ChannelType } from './config';+import {+ AlertmanagertypesPostableChannelDTO,+ ConfigSecretURLDTO,+} from 'api/generated/services/sigNoz.schemas';++import { ChannelType, GoogleChatChannel } from './config';export const isChannelType = (type: string): type is ChannelType =>Object.values(ChannelType).includes(type as ChannelType);++const GOOGLE_CHAT_WEBHOOK_HOST = 'chat.googleapis.com';++// the backend enforces the same two rules, this is only for a nicer error experience+export const isValidGoogleChatWebhookURL = (url: string): boolean => {+ try {+ const { protocol, hostname } = new URL(url);+ return (+ protocol === 'https:' && hostname.toLowerCase() === GOOGLE_CHAT_WEBHOOK_HOST+ );+ } catch {+ return false;+ }+};++// create, update and test all send the same body shape+export const prepareGoogleChatRequest = (+ config: Partial<GoogleChatChannel>,+): AlertmanagertypesPostableChannelDTO => ({+ name: config.name || '',+ googlechat_configs: [+ {+ // the generated type models go's config.SecretURL as an object, the api takes a string+ webhook_url: (config.webhook_url || '') as unknown as ConfigSecretURLDTO,+ title: config.title || '',+ text: config.text || '',+ send_resolved: config.send_resolved || false,+ },+ ],+});diff --git a/frontend/src/container/EditAlertChannels/index.tsx b/frontend/src/container/EditAlertChannels/index.tsxindex af986afe06..c7d7da009e 100644--- a/frontend/src/container/EditAlertChannels/index.tsx+++ b/frontend/src/container/EditAlertChannels/index.tsx@@ -14,10 +14,17 @@ import testPagerApi from 'api/channels/testPager';import testSlackApi from 'api/channels/testSlack';import testWebhookApi from 'api/channels/testWebhook';import logEvent from 'api/common/logEvent';+import {+ useTestChannel,+ useUpdateChannelByID,+} from 'api/generated/services/channels';+import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';+import { ErrorType } from 'api/generatedAPIInstance';import ROUTES from 'constants/routes';import {ChannelType,EmailChannel,+ GoogleChatChannel,MsTeamsChannel,OpsgenieChannel,PagerChannel,@@ -25,10 +32,15 @@ import {ValidatePagerChannel,WebhookChannel,} from 'container/CreateAlertChannels/config';+import {+ isValidGoogleChatWebhookURL,+ prepareGoogleChatRequest,+} from 'container/CreateAlertChannels/utils';import FormAlertChannels from 'container/FormAlertChannels';import { useNotifications } from 'hooks/useNotifications';import history from 'lib/history';import APIError from 'types/api/error';+import { toAPIError } from 'utils/errorUtils';function EditAlertChannels({initialValue,@@ -45,7 +57,8 @@ function EditAlertChannels({PagerChannel &MsTeamsChannel &OpsgenieChannel &- EmailChannel+ EmailChannel &+ GoogleChatChannel>>({...initialValue,@@ -54,6 +67,26 @@ function EditAlertChannels({const [testingState, setTestingState] = useState<boolean>(false);const { notifications } = useNotifications();+ const { mutateAsync: updateChannel } = useUpdateChannelByID();+ const { mutateAsync: testChannel } = useTestChannel();++ const notifyError = useCallback(+ (error: unknown): APIError => {+ const apiError =+ error instanceof APIError+ ? error+ : toAPIError(error as ErrorType<RenderErrorResponseDTO>);++ notifications.error({+ message: apiError.getErrorCode(),+ description: apiError.getErrorMessage(),+ });++ return apiError;+ },+ [notifications],+ );+const [type, setType] = useState<ChannelType>(initialValue?.type ? (initialValue.type as ChannelType) : ChannelType.Slack,);@@ -364,6 +397,61 @@ function EditAlertChannels({}}, [prepareMsTeamsRequest, t, notifications, selectedConfig]);+ const validateGoogleChatConfig = useCallback((): string => {+ if (!selectedConfig?.webhook_url) {+ return t('webhook_url_required');+ }++ if (!isValidGoogleChatWebhookURL(selectedConfig.webhook_url)) {+ return t('google_chat_webhook_url_invalid');+ }++ return '';+ }, [selectedConfig, t]);++ const onGoogleChatEditHandler = useCallback(async () => {+ const validationError = validateGoogleChatConfig();++ if (validationError !== '') {+ notifications.error({+ message: 'Error',+ description: validationError,+ });+ return { status: 'failed', statusMessage: validationError };+ }++ setSavingState(true);++ try {+ await updateChannel({+ pathParams: { id },+ data: prepareGoogleChatRequest(selectedConfig),+ });+ notifications.success({+ message: 'Success',+ description: t('channel_edit_done'),+ });+ history.replace(ROUTES.ALL_CHANNELS);+ return { status: 'success', statusMessage: t('channel_edit_done') };+ } catch (error) {+ const apiError = notifyError(error);+ return {+ status: 'failed',+ statusMessage: apiError.getErrorMessage() || t('channel_edit_failed'),+ };+ } finally {+ setSavingState(false);+ }+ }, [+ validateGoogleChatConfig,+ updateChannel,+ id,+ selectedConfig,+ notifications,+ notifyError,+ t,+ ]);+const onSaveHandler = useCallback(async (value: ChannelType) => {let result;@@ -379,6 +467,8 @@ function EditAlertChannels({result = await onOpsgenieEditHandler();} else if (value === ChannelType.Email) {result = await onEmailEditHandler();+ } else if (value === ChannelType.GoogleChat) {+ result = await onGoogleChatEditHandler();}logEvent('Alert Channel: Save channel', {type: value,@@ -397,6 +487,7 @@ function EditAlertChannels({onMsTeamsEditHandler,onOpsgenieEditHandler,onEmailEditHandler,+ onGoogleChatEditHandler,],);@@ -438,6 +529,19 @@ function EditAlertChannels({await testEmail(request);}break;+ case ChannelType.GoogleChat: {+ const validationError = validateGoogleChatConfig();+ if (validationError !== '') {+ notifications.error({+ message: 'Error',+ description: validationError,+ });+ setTestingState(false);+ return;+ }+ await testChannel({ data: prepareGoogleChatRequest(selectedConfig) });+ break;+ }default:notifications.error({message: 'Error',@@ -459,10 +563,7 @@ function EditAlertChannels({status: 'Test success',});} catch (error) {- notifications.error({- message: (error as APIError).getErrorCode(),- description: (error as APIError).getErrorMessage(),- });+ notifyError(error);logEvent('Alert Channel: Test notification', {type: channelType,sendResolvedAlert: selectedConfig?.send_resolved,@@ -476,6 +577,9 @@ function EditAlertChannels({// eslint-disable-next-line react-hooks/exhaustive-deps[t,+ notifyError,+ validateGoogleChatConfig,+ testChannel,prepareWebhookRequest,preparePagerRequest,prepareSlackRequest,diff --git a/frontend/src/container/FormAlertChannels/Settings/GoogleChat.tsx b/frontend/src/container/FormAlertChannels/Settings/GoogleChat.tsxnew file mode 100644index 0000000000..a1f4dcc1ea--- /dev/null+++ b/frontend/src/container/FormAlertChannels/Settings/GoogleChat.tsx@@ -0,0 +1,82 @@+import { Dispatch, SetStateAction } from 'react';+import { useTranslation } from 'react-i18next';+import { Form, Input } from 'antd';+import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';++import { GoogleChatChannel } from '../../CreateAlertChannels/config';+import { isValidGoogleChatWebhookURL } from '../../CreateAlertChannels/utils';++function GoogleChat({ setSelectedConfig }: GoogleChatProps): JSX.Element {+ const { t } = useTranslation('channels');++ return (+ <>+ <Form.Item+ name="webhook_url"+ label={t('field_webhook_url')}+ required+ rules={[+ {+ validator: (_, value: string): Promise<void> =>+ !value || isValidGoogleChatWebhookURL(value)+ ? Promise.resolve()+ : Promise.reject(new Error(t('google_chat_webhook_url_invalid'))),+ },+ ]}+ tooltip={{+ title: (+ <MarkdownRenderer+ markdownContent={t('tooltip_google_chat_url')}+ variables={{}}+ />+ ),+ overlayInnerStyle: { maxWidth: 400 },+ placement: 'right',+ }}+ >+ <Input+ onChange={(event): void => {+ setSelectedConfig((value) => ({+ ...value,+ webhook_url: event.target.value,+ }));+ }}+ data-testid="webhook-url-textbox"+ />+ </Form.Item>++ <Form.Item name="title" label={t('field_slack_title')}>+ <Input.TextArea+ rows={4}+ onChange={(event): void =>+ setSelectedConfig((value) => ({+ ...value,+ title: event.target.value,+ }))+ }+ data-testid="title-textarea"+ />+ </Form.Item>++ <Form.Item name="text" label={t('field_slack_description')}>+ <Input.TextArea+ rows={4}+ onChange={(event): void =>+ setSelectedConfig((value) => ({+ ...value,+ text: event.target.value,+ }))+ }+ data-testid="description-textarea"+ placeholder={t('placeholder_slack_description')}+ />+ </Form.Item>+ </>+ );+}++interface GoogleChatProps {+ setSelectedConfig: Dispatch<SetStateAction<Partial<GoogleChatChannel>>>;+}++export default GoogleChat;diff --git a/frontend/src/container/FormAlertChannels/index.tsx b/frontend/src/container/FormAlertChannels/index.tsxindex 3057a25521..959cca08c2 100644--- a/frontend/src/container/FormAlertChannels/index.tsx+++ b/frontend/src/container/FormAlertChannels/index.tsx@@ -9,6 +9,7 @@ import ROUTES from 'constants/routes';import {ChannelType,EmailChannel,+ GoogleChatChannel,OpsgenieChannel,PagerChannel,SlackChannel,@@ -17,6 +18,7 @@ import {import history from 'lib/history';import EmailSettings from './Settings/Email';+import GoogleChatSettings from './Settings/GoogleChat';import MsTeamsSettings from './Settings/MsTeams';import OpsgenieSettings from './Settings/Opsgenie';import PagerSettings from './Settings/Pager';@@ -49,6 +51,8 @@ function FormAlertChannels({return <PagerSettings setSelectedConfig={setSelectedConfig} />;case ChannelType.MsTeams:return <MsTeamsSettings setSelectedConfig={setSelectedConfig} />;+ case ChannelType.GoogleChat:+ return <GoogleChatSettings setSelectedConfig={setSelectedConfig} />;case ChannelType.Opsgenie:return <OpsgenieSettings setSelectedConfig={setSelectedConfig} />;case ChannelType.Email:@@ -129,6 +133,14 @@ function FormAlertChannels({<Select.Option value="msteams" key="msteams" data-testid="select-option">Microsoft Teams</Select.Option>++ <Select.Option+ value="googlechat"+ key="googlechat"+ data-testid="select-option"+ >+ Google Chat+ </Select.Option></Select></Form.Item>@@ -176,7 +188,8 @@ interface FormAlertChannelsProps {WebhookChannel &PagerChannel &OpsgenieChannel &- EmailChannel+ EmailChannel &+ GoogleChatChannel>>>;diff --git a/frontend/src/mocks-server/__mockdata__/alerts.ts b/frontend/src/mocks-server/__mockdata__/alerts.tsindex e7af99c7fd..10e17250bc 100644--- a/frontend/src/mocks-server/__mockdata__/alerts.ts+++ b/frontend/src/mocks-server/__mockdata__/alerts.ts@@ -27,9 +27,13 @@ export const slackTitleDefaultValue = `[{{ .Status | toUpper }}{{ if eq .Statusexport const slackDescriptionDefaultValue = `{{ range .Alerts -}} *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }} *Summary:* {{ .Annotations.summary }} *Description:* {{ .Annotations.description }} *RelatedLogs:* {{ if gt (len .Annotations.related_logs) 0 -}} View in <{{ .Annotations.related_logs }}|logs explorer> {{- end}} *RelatedTraces:* {{ if gt (len .Annotations.related_traces) 0 -}} View in <{{ .Annotations.related_traces }}|traces explorer> {{- end}} *Details:* {{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }} {{ end }} {{ end }}`;+export const googleChatTitleDefaultValue = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`;++export const googleChatDescriptionDefaultValue = `{{ 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 }} {{ end }}`;+export const editSlackDescriptionDefaultValue = `{{ range .Alerts -}} *Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }} dummy_summary *Summary:* {{ .Annotations.summary }} *Description:* {{ .Annotations.description }} *Details:* {{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }} {{ end }} {{ end }}`;-export const pagerDutyDescriptionDefaultVaule = `{{ if gt (len .Alerts.Firing) 0 -}} Alerts Firing: {{ range .Alerts.Firing }} - Message: {{ .Annotations.description }} Labels: {{ range .Labels.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Annotations: {{ range .Annotations.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Source: {{ .GeneratorURL }} {{ end }} {{- end }} {{ if gt (len .Alerts.Resolved) 0 -}} Alerts Resolved: {{ range .Alerts.Resolved }} - Message: {{ .Annotations.description }} Labels: {{ range .Labels.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Annotations: {{ range .Annotations.SortedPairs }} - {{ .Name }} = {{ .Value }} {{ end }} Source: {{ .GeneratorURL }} {{ end }} {{- end }}`;+export const pagerDutyDescriptionDefaultValue = `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }} {{- if gt (len .CommonLabels) (len .GroupLabels) -}} {{" "}}( {{- with .CommonLabels.Remove .GroupLabels.Names }} {{- range $index, $label := .SortedPairs -}} {{ if $index }}, {{ end }} {{- $label.Name }}="{{ $label.Value -}}" {{- end }} {{- end -}} ) {{- end }}`;export const pagerDutyAdditionalDetailsDefaultValue = JSON.stringify({firing: `{{ .Alerts.Firing | toJson }}`,diff --git a/frontend/src/pages/ChannelsEdit/index.tsx b/frontend/src/pages/ChannelsEdit/index.tsxindex 9a89122a0f..1b7cd021ff 100644--- a/frontend/src/pages/ChannelsEdit/index.tsx+++ b/frontend/src/pages/ChannelsEdit/index.tsx@@ -10,6 +10,7 @@ import Spinner from 'components/Spinner';import ROUTES from 'constants/routes';import {ChannelType,+ GoogleChatChannel,MsTeamsChannel,PagerChannel,SlackChannel,@@ -59,11 +60,20 @@ function ChannelsEdit(): JSX.Element {const prepChannelConfig = (): {type: string;- channel: SlackChannel & WebhookChannel & PagerChannel & MsTeamsChannel;+ channel: SlackChannel &+ WebhookChannel &+ PagerChannel &+ MsTeamsChannel &+ GoogleChatChannel;} => {- let channel: SlackChannel & WebhookChannel & PagerChannel & MsTeamsChannel = {+ let channel: SlackChannel &+ WebhookChannel &+ PagerChannel &+ MsTeamsChannel &+ GoogleChatChannel = {name: '',};+if (value && 'slack_configs' in value) {const slackConfig = value.slack_configs[0];channel = slackConfig;@@ -81,6 +91,16 @@ function ChannelsEdit(): JSX.Element {channel,};}++ if (value && 'googlechat_configs' in value) {+ const [googleChatConfig] = value.googlechat_configs;+ channel = googleChatConfig;+ return {+ type: ChannelType.GoogleChat,+ channel,+ };+ }+if (value && 'pagerduty_configs' in value) {const pagerConfig = value.pagerduty_configs[0];channel = pagerConfig;