Compare commits

...

25 Commits

Author SHA1 Message Date
nikhilmantri0902
c78b9f63b3 Merge branch 'infraM/google_chat_integration_backend' into feat/alert-channels-google-chat-full-stack 2026-07-30 16:28:10 +05:30
nikhilmantri0902
d95a2164d9 test(googlechat): cover default-body grouped alerts (single combined section) 2026-07-30 16:15:47 +05:30
nikhilmantri0902
de48f99455 docs(googlechat): clarify content.bodies default-vs-custom alignment 2026-07-30 16:05:05 +05:30
nikhilmantri0902
f9a770c50b feat(googlechat): render grouped alerts as per-alert card sections
Render each alert in its own card section with its own View Related
Logs/Traces buttons, and move Open in SigNoz to a shared footer button
(it's per-rule). Matches the slack/msteams per-alert layout; the default
template still produces one combined section.

Cap sections at 30 with a "+N more alerts" note: Google Chat allows 100
widgets per card and silently drops the section that crosses that count
and every section after it, so capping keeps the footer and trailing
alerts from vanishing. Cap is applied before the size guard so the trim
loop only touches rendered bodies.

Generalize the 32 KB size guard to trim the longest body, then the title.
2026-07-30 15:36:58 +05:30
nikhilmantri0902
6136eb3258 fix(googlechat): guard nil HTTPConfig in New with a clean error 2026-07-30 13:47:26 +05:30
nikhilmantri0902
c639cbf8c7 Merge branch 'infraM/google_chat_integration_backend' into feat/alert-channels-google-chat-full-stack 2026-07-30 12:57:47 +05:30
nikhilmantri0902
a86e9f958d Merge branch 'infraM/google_chat_integration_backend' into feat/alert-channels-google-chat-full-stack 2026-07-30 12:54:44 +05:30
Nikhil Mantri
e865648db2 Merge branch 'main' into feat/alert-channels-google-chat 2026-07-30 12:52:01 +05:30
Nikhil Mantri
dd64bdb5cc Merge branch 'main' into infraM/google_chat_integration_backend 2026-07-30 12:04:57 +05:30
nikhilmantri0902
9c82342cbf fix(googlechat): use standard markdown in default templates for cardsV2 2026-07-29 21:38:13 +05:30
nikhilmantri0902
589e33eb39 chore: truncation logic optimized for both body and title 2026-07-29 19:39:19 +05:30
nikhilmantri0902
91064d0b63 chore: cardsv2 scaffolding 2026-07-29 19:26:57 +05:30
Ashwin Bhatkal
23a9497cce test(alert-channels): cover the google chat channel form 2026-07-29 18:22:24 +05:30
Ashwin Bhatkal
b48542d2c7 feat(alert-channels): wire google chat create, edit and test calls 2026-07-29 18:22:24 +05:30
Ashwin Bhatkal
ab0d13814a feat(alert-channels): add google chat option and form fields 2026-07-29 18:22:24 +05:30
Ashwin Bhatkal
ac5a3bbd57 feat(alert-channels): add google chat channel type, defaults and url validation
Prefills the title and description templates verbatim from the backend's
DefaultGoogleChatReceiverConfig, and extracts the slack templates into
SlackInitialConfig so the form can restore them when the type changes.
2026-07-29 18:22:24 +05:30
Nikhil Mantri
0500d14054 Merge branch 'main' into infraM/google_chat_integration_backend 2026-07-29 15:38:09 +05:30
nikhilmantri0902
a9051c4e9e chore: error on empty title body with non-retryable error and give 429 retryable error due to limit 2026-07-29 01:34:03 +05:30
nikhilmantri0902
17f4b4af91 chore: added one more test 2026-07-28 18:02:14 +05:30
nikhilmantri0902
759d2f6db5 chore: comment correction 2026-07-28 17:38:22 +05:30
nikhilmantri0902
b9156ac4b0 chore: added utf 8 sanitization and capping the limit 2026-07-28 17:35:32 +05:30
nikhilmantri0902
1300dbc1c2 chore: adding processing logic for makrdown to google chat format 2026-07-28 17:09:17 +05:30
nikhilmantri0902
0f657b946e chore: added tests 2026-07-28 16:49:24 +05:30
nikhilmantri0902
376c1d9fcc chore: added content extraction and formatting for google chat content 2026-07-28 16:02:32 +05:30
nikhilmantri0902
e90783d3ed chore: added googlechat notify function 2026-07-28 15:14:27 +05:30
19 changed files with 1558 additions and 42 deletions

View File

@@ -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",

View File

@@ -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",

View File

@@ -1,6 +1,9 @@
import CreateAlertChannels from 'container/CreateAlertChannels';
import { ChannelType } from 'container/CreateAlertChannels/config';
import { GoogleChatInitialConfig } from 'container/CreateAlertChannels/defaults';
import {
googleChatDescriptionDefaultValue,
googleChatTitleDefaultValue,
opsGenieDescriptionDefaultValue,
opsGenieMessageDefaultValue,
opsGeniePriorityDefaultValue,
@@ -419,5 +422,99 @@ 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 () => {
fireEvent.change(screen.getByTestId('channel-name-textbox'), {
target: { value: 'gchat-channel' },
});
fireEvent.change(screen.getByTestId('webhook-url-textbox'), {
target: { value: 'https://example.com/webhook' },
});
fireEvent.click(
screen.getByRole('button', { name: 'button_save_channel' }),
);
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' }),
);
}),
);
fireEvent.change(screen.getByTestId('channel-name-textbox'), {
target: { value: 'gchat-channel' },
});
fireEvent.change(screen.getByTestId('webhook-url-textbox'), {
target: { value: validWebhookUrl },
});
fireEvent.click(
screen.getByRole('button', { name: 'button_save_channel' }),
);
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,
},
],
});
});
});
});
});

View File

@@ -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;
}

View File

@@ -1,4 +1,48 @@
import { EmailChannel, OpsgenieChannel, PagerChannel } from './config';
import {
EmailChannel,
GoogleChatChannel,
OpsgenieChannel,
PagerChannel,
SlackChannel,
} 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 }}

View File

@@ -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,
@@ -33,10 +41,16 @@ import {
} from './config';
import {
EmailInitialConfig,
GoogleChatInitialConfig,
OpsgenieInitialConfig,
PagerInitialConfig,
SlackInitialConfig,
} from './defaults';
import { isChannelType } from './utils';
import {
isChannelType,
isValidGoogleChatWebhookURL,
prepareGoogleChatRequest,
} from './utils';
import './CreateAlertChannels.styles.scss';
@@ -60,38 +74,22 @@ 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 }}`,
});
...(preType === ChannelType.GoogleChat
? GoogleChatInitialConfig
: SlackInitialConfig),
}));
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) => {
@@ -121,8 +119,26 @@ function CreateAlertChannels({
...EmailInitialConfig,
}));
}
// google chat prefills its own title / description templates, so switching
// in or out of it has to swap the templates the form is showing
if (
currentType !== value &&
(value === ChannelType.GoogleChat || currentType === ChannelType.GoogleChat)
) {
const templates =
value === ChannelType.GoogleChat
? GoogleChatInitialConfig
: SlackInitialConfig;
setSelectedConfig((selectedConfig) => ({
...selectedConfig,
...templates,
}));
formInstance.setFieldsValue(templates);
}
},
[type, selectedConfig],
[type, selectedConfig, formInstance],
);
const prepareSlackRequest = useCallback(
@@ -407,6 +423,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 +490,7 @@ function CreateAlertChannels({
[ChannelType.Opsgenie]: onOpsgenieHandler,
[ChannelType.MsTeams]: onMsTeamsHandler,
[ChannelType.Email]: onEmailHandler,
[ChannelType.GoogleChat]: onGoogleChatHandler,
};
if (isChannelType(value)) {
@@ -455,6 +522,7 @@ function CreateAlertChannels({
onOpsgenieHandler,
onMsTeamsHandler,
onEmailHandler,
onGoogleChatHandler,
notifications,
t,
],
@@ -492,6 +560,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 +588,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 +614,8 @@ function CreateAlertChannels({
prepareSlackRequest,
prepareMsTeamsRequest,
prepareEmailRequest,
validateGoogleChatConfig,
testChannel,
notifications,
],
);

View File

@@ -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,
},
],
});

View File

@@ -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,

View File

@@ -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;

View File

@@ -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
>
>
>;

View File

@@ -27,6 +27,10 @@ export const slackTitleDefaultValue = `[{{ .Status | toUpper }}{{ if eq .Status
export 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 }}`;

View File

@@ -10,6 +10,7 @@ import Spinner from 'components/Spinner';
import ROUTES from 'constants/routes';
import {
ChannelType,
GoogleChatChannel,
MsTeamsChannel,
PagerChannel,
SlackChannel,
@@ -59,9 +60,17 @@ 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) {
@@ -81,6 +90,15 @@ 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;

View File

@@ -0,0 +1,298 @@
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"
)
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: &notify.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...)
buf, err := encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining))
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 {
break
}
if buf, err = encodeMessage(buildMessage(title, status, capAlerts, bodies, remaining)); 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.
func buildMessage(title, statusHTML string, alerts []*types.Alert, bodies []string, remaining int) 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 len(alerts) > 0 && alerts[0] != nil {
if btn := sigNozButton(alerts[0]); 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
}

View File

@@ -0,0 +1,551 @@
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/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)
require.False(t, retry)
require.Contains(t, got.Text, "FIRING")
require.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)
require.False(t, retry)
// Title is the plain summary + card header; body lives in a card widget.
require.Equal(t, "TITLE", got.Text)
require.Equal(t, "TITLE", got.CardsV2[0].Card.Header.Title)
require.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)
require.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)
require.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)
require.LessOrEqual(t, len(got), c.wantLen)
if c.wantHas != "" {
require.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)
require.False(t, retry)
require.True(t, valid, "posted body must be valid JSON")
require.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)
require.Equal(t, "REPLY_MESSAGE_FALLBACK_TO_NEW_THREAD", query.Get("messageReplyOption"))
threadKey := query.Get("threadKey")
require.Equal(t, notify.Key(c.groupKey).Hash(), threadKey, "threadKey must be the group key hash")
seen[c.name] = threadKey
})
}
require.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)
require.Contains(t, body, "<strong>bold</strong>", "** should convert to HTML bold")
require.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)
require.True(t, valid, "posted body must be valid JSON")
require.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)
require.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)
require.Len(t, buttons, len(c.wantButtons))
for _, b := range buttons {
require.Equal(t, c.wantButtons[b.Text], b.OnClick.OpenLink.URL, "button %q", b.Text)
}
})
}
}
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.
require.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
}
}
require.Equal(t, 1, sigNoz, "SigNoz button must appear once (shared, per-rule)")
require.True(t, logsURLs["https://signoz.example/logs?pod=pod-1"], "pod-1's logs button")
require.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.
require.Equal(t, 3, cardSectionCount(t, got))
body := cardBody(t, got)
require.Contains(t, body, "pod-1")
require.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++
}
}
require.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.
require.Equal(t, 1+maxAlertSections+1+1, cardSectionCount(t, got))
body := cardBody(t, got)
require.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++
}
}
require.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)
require.Contains(t, cardBody(t, got), c.want)
})
}
}

View File

@@ -0,0 +1,95 @@
package googlechat
import (
"log/slog"
"net/http"
"github.com/SigNoz/signoz/pkg/types/alertmanagertypes"
"github.com/prometheus/alertmanager/notify"
"github.com/prometheus/alertmanager/template"
)
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
}

View File

@@ -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.Temp
return 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, &errs

View File

@@ -1,6 +1,10 @@
package alertmanagertypes
import (
"net/url"
"strings"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/prometheus/alertmanager/config"
commoncfg "github.com/prometheus/common/config"
)
@@ -21,9 +25,9 @@ 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 }}`,
}
@@ -32,3 +36,18 @@ func (c *GoogleChatReceiverConfig) UnmarshalYAML(unmarshal func(any) error) erro
type plain GoogleChatReceiverConfig
return unmarshal((*plain)(c))
}
// ValidateGoogleChatWebhookURL validates the Google Chat webhook URL format.
func ValidateGoogleChatWebhookURL(rawURL string) error {
u, err := url.Parse(rawURL)
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
}

View File

@@ -0,0 +1,44 @@
package alertmanagertypes
import (
"testing"
"github.com/stretchr/testify/require"
)
func TestValidateGoogleChatWebhookURL(t *testing.T) {
cases := []struct {
name string
url string
wantErr bool
}{
{"valid", "https://chat.googleapis.com/v1/spaces/AAA/messages?key=k&token=t", false},
{"http scheme rejected", "http://chat.googleapis.com/v1/spaces/AAA/messages", true},
{"wrong host rejected", "https://example.com/v1/spaces/AAA/messages", true},
{"empty rejected", "", true},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
err := ValidateGoogleChatWebhookURL(c.url)
if c.wantErr {
require.Error(t, err)
} else {
require.NoError(t, err)
}
})
}
}
func TestNewReceiverGoogleChatRejectsBadURL(t *testing.T) {
// http scheme
_, err := NewReceiver(`{"name":"gc","googlechat_configs":[{"webhook_url":"http://chat.googleapis.com/v1/spaces/x/messages"}]}`)
require.Error(t, err)
// wrong host
_, err = NewReceiver(`{"name":"gc","googlechat_configs":[{"webhook_url":"https://example.com/x"}]}`)
require.Error(t, err)
// missing webhook_url
_, err = NewReceiver(`{"name":"gc","googlechat_configs":[{"title":"x"}]}`)
require.Error(t, err)
}

View File

@@ -45,12 +45,23 @@ func NewReceiver(input string) (*Receiver, error) {
if err != nil {
return nil, err
}
if err := validateGoogleChatConfig(defaulted); err != nil {
return nil, err
}
receiver.GoogleChatConfigs[i] = defaulted
}
return receiver, nil
}
// validateGoogleChatConfig validates a Google Chat receiver configuration.
func validateGoogleChatConfig(cfg *GoogleChatReceiverConfig) error {
if cfg.WebhookURL == nil {
return errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "google chat webhook_url is required")
}
return ValidateGoogleChatWebhookURL(cfg.WebhookURL.String())
}
func defaultedBaseReceiver(base *config.Receiver) (*config.Receiver, error) {
bytes, err := yaml.Marshal(base)
if err != nil {