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: add remaining v2 notification channel apis (#12786)
Naman Verma4175f84815dd
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex 31836fa239..b8f548977e 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -296,6 +296,17 @@ components:- jsmops- incidentiotype: string+ AlertmanagertypesChannelListOrder:+ enum:+ - asc+ - desc+ type: string+ AlertmanagertypesChannelListSort:+ enum:+ - updated_at+ - created_at+ - name+ type: stringAlertmanagertypesChannelMSTeamsConfig:properties:sendResolved:@@ -576,6 +587,43 @@ components:wont_fix_resolution:type: stringtype: object+ AlertmanagertypesListableNotificationChannel:+ properties:+ channels:+ items:+ $ref: '#/components/schemas/AlertmanagertypesListedNotificationChannel'+ type: array+ total:+ format: int64+ type: integer+ required:+ - channels+ - total+ type: object+ AlertmanagertypesListedNotificationChannel:+ properties:+ createdAt:+ format: date-time+ type: string+ displayName:+ type: string+ id:+ type: string+ kind:+ $ref: '#/components/schemas/AlertmanagertypesChannelKind'+ name:+ type: string+ updatedAt:+ format: date-time+ type: string+ required:+ - id+ - name+ - displayName+ - kind+ - createdAt+ - updatedAt+ type: objectAlertmanagertypesMaintenanceKind:enum:- fixed@@ -942,6 +990,20 @@ components:- timezone- startTimetype: object+ AlertmanagertypesTestableNotificationChannel:+ properties:+ config:+ $ref: '#/components/schemas/AlertmanagertypesChannelConfig'+ required:+ - config+ type: object+ AlertmanagertypesUpdatableNotificationChannel:+ properties:+ config:+ $ref: '#/components/schemas/AlertmanagertypesChannelConfig'+ required:+ - config+ type: objectAuthtypesAttributeMapping:properties:email:@@ -19784,6 +19846,86 @@ paths:tags:- metrics/api/v2/notification_channels:+ get:+ deprecated: false+ description: Returns a page of notification channels for the org. Each entry+ carries the channel's identity and kind but not its configuration; fetch a+ channel by ID for that. Supports a case-insensitive display name search (`query`),+ a kind filter (`kind`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`),+ and offset-based pagination (`limit`/`offset`).+ operationId: ListNotificationChannels+ parameters:+ - in: query+ name: query+ schema:+ type: string+ - in: query+ name: kind+ schema:+ $ref: '#/components/schemas/AlertmanagertypesChannelKind'+ - in: query+ name: sort+ schema:+ $ref: '#/components/schemas/AlertmanagertypesChannelListSort'+ - in: query+ name: order+ schema:+ $ref: '#/components/schemas/AlertmanagertypesChannelListOrder'+ - in: query+ name: limit+ schema:+ type: integer+ - in: query+ name: offset+ schema:+ type: integer+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/AlertmanagertypesListableNotificationChannel'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - notification-channel:list+ - tokenizer:+ - notification-channel:list+ summary: List notification channels+ tags:+ - channelspost:deprecated: falsedescription: This endpoint creates a notification channel@@ -19846,6 +19988,239 @@ paths:summary: Create notification channeltags:- channels+ /api/v2/notification_channels/{id}:+ delete:+ deprecated: false+ description: This endpoint deletes a notification channel by ID+ operationId: DeleteNotificationChannel+ parameters:+ - in: path+ name: id+ required: true+ schema:+ type: string+ responses:+ "204":+ description: No Content+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "404":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Not Found+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - notification-channel:delete+ - tokenizer:+ - notification-channel:delete+ summary: Delete notification channel+ tags:+ - channels+ get:+ deprecated: false+ description: This endpoint returns a notification channel by ID. A channel written+ by the v1 API can carry a configuration this API does not model.+ operationId: GetNotificationChannel+ parameters:+ - in: path+ name: id+ required: true+ schema:+ type: string+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/AlertmanagertypesGettableNotificationChannel'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "404":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Not Found+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - notification-channel:read+ - tokenizer:+ - notification-channel:read+ summary: Get notification channel by ID+ tags:+ - channels+ put:+ deprecated: false+ description: 'This endpoint replaces a notification channel''s configuration+ in full. Neither name is part of the request body: both are immutable. The+ kind may change, which replaces the channel''s notifier configuration.'+ operationId: UpdateNotificationChannel+ parameters:+ - in: path+ name: id+ required: true+ schema:+ type: string+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AlertmanagertypesUpdatableNotificationChannel'+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/AlertmanagertypesGettableNotificationChannel'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "404":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Not Found+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - notification-channel:update+ - tokenizer:+ - notification-channel:update+ summary: Update notification channel+ tags:+ - channels+ /api/v2/notification_channels/test:+ post:+ deprecated: false+ description: This endpoint sends a test notification for the configuration in+ the request body. The channel need not exist and nothing is persisted, so+ the body carries a configuration only.+ operationId: TestNotificationChannel+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/AlertmanagertypesTestableNotificationChannel'+ responses:+ "204":+ description: No Content+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - notification-channel:create+ - tokenizer:+ - notification-channel:create+ summary: Test notification channel+ tags:+ - channels/api/v2/orgs/me:get:deprecated: falsediff --git a/frontend/src/api/generated/services/channels/index.ts b/frontend/src/api/generated/services/channels/index.tsindex 8a2ef4fb43..579a764c94 100644--- a/frontend/src/api/generated/services/channels/index.ts+++ b/frontend/src/api/generated/services/channels/index.ts@@ -21,14 +21,23 @@ import type {AlertmanagertypesPostableChannelDTO,AlertmanagertypesPostableNotificationChannelDTO,AlertmanagertypesReceiverDTO,+ AlertmanagertypesTestableNotificationChannelDTO,+ AlertmanagertypesUpdatableNotificationChannelDTO,CreateChannel201,CreateNotificationChannel201,DeleteChannelByIDPathParameters,+ DeleteNotificationChannelPathParameters,GetChannelByID200,GetChannelByIDPathParameters,+ GetNotificationChannel200,+ GetNotificationChannelPathParameters,ListChannels200,+ ListNotificationChannels200,+ ListNotificationChannelsParams,RenderErrorResponseDTO,UpdateChannelByIDPathParameters,+ UpdateNotificationChannel200,+ UpdateNotificationChannelPathParameters,} from '../sigNoz.schemas';import { GeneratedAPIInstance } from '../../../generatedAPIInstance';@@ -649,6 +658,105 @@ export const useTestChannelDeprecated = <> => {return useMutation(getTestChannelDeprecatedMutationOptions(options));};+/**+ * Returns a page of notification channels for the org. Each entry carries the channel's identity and kind but not its configuration; fetch a channel by ID for that. Supports a case-insensitive display name search (`query`), a kind filter (`kind`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`).+ * @summary List notification channels+ */+export const listNotificationChannels = (+ params?: ListNotificationChannelsParams,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<ListNotificationChannels200>({+ url: `/api/v2/notification_channels`,+ method: 'GET',+ params,+ signal,+ });+};++export const getListNotificationChannelsQueryKey = (+ params?: ListNotificationChannelsParams,+) => {+ return [`/api/v2/notification_channels`, ...(params ? [params] : [])] as const;+};++export const getListNotificationChannelsQueryOptions = <+ TData = Awaited<ReturnType<typeof listNotificationChannels>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ params?: ListNotificationChannelsParams,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof listNotificationChannels>>,+ TError,+ TData+ >;+ },+) => {+ const { query: queryOptions } = options ?? {};++ const queryKey =+ queryOptions?.queryKey ?? getListNotificationChannelsQueryKey(params);++ const queryFn: QueryFunction<+ Awaited<ReturnType<typeof listNotificationChannels>>+ > = ({ signal }) => listNotificationChannels(params, signal);++ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<+ Awaited<ReturnType<typeof listNotificationChannels>>,+ TError,+ TData+ > & { queryKey: QueryKey };+};++export type ListNotificationChannelsQueryResult = NonNullable<+ Awaited<ReturnType<typeof listNotificationChannels>>+>;+export type ListNotificationChannelsQueryError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary List notification channels+ */++export function useListNotificationChannels<+ TData = Awaited<ReturnType<typeof listNotificationChannels>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ params?: ListNotificationChannelsParams,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof listNotificationChannels>>,+ TError,+ TData+ >;+ },+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {+ const queryOptions = getListNotificationChannelsQueryOptions(params, options);++ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {+ queryKey: QueryKey;+ };++ return { ...query, queryKey: queryOptions.queryKey };+}++/**+ * @summary List notification channels+ */+export const invalidateListNotificationChannels = async (+ queryClient: QueryClient,+ params?: ListNotificationChannelsParams,+ options?: InvalidateOptions,+): Promise<QueryClient> => {+ await queryClient.invalidateQueries(+ { queryKey: getListNotificationChannelsQueryKey(params) },+ options,+ );++ return queryClient;+};+/*** This endpoint creates a notification channel* @summary Create notification channel@@ -733,3 +841,370 @@ export const useCreateNotificationChannel = <> => {return useMutation(getCreateNotificationChannelMutationOptions(options));};+/**+ * This endpoint deletes a notification channel by ID+ * @summary Delete notification channel+ */+export const deleteNotificationChannel = (+ { id }: DeleteNotificationChannelPathParameters,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<void>({+ url: `/api/v2/notification_channels/${id}`,+ method: 'DELETE',+ signal,+ });+};++export const getDeleteNotificationChannelMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof deleteNotificationChannel>>,+ TError,+ { pathParams: DeleteNotificationChannelPathParameters },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof deleteNotificationChannel>>,+ TError,+ { pathParams: DeleteNotificationChannelPathParameters },+ TContext+> => {+ const mutationKey = ['deleteNotificationChannel'];+ const { mutation: mutationOptions } = options+ ? options.mutation &&+ 'mutationKey' in options.mutation &&+ options.mutation.mutationKey+ ? options+ : { ...options, mutation: { ...options.mutation, mutationKey } }+ : { mutation: { mutationKey } };++ const mutationFn: MutationFunction<+ Awaited<ReturnType<typeof deleteNotificationChannel>>,+ { pathParams: DeleteNotificationChannelPathParameters }+ > = (props) => {+ const { pathParams } = props ?? {};++ return deleteNotificationChannel(pathParams);+ };++ return { mutationFn, ...mutationOptions };+};++export type DeleteNotificationChannelMutationResult = NonNullable<+ Awaited<ReturnType<typeof deleteNotificationChannel>>+>;++export type DeleteNotificationChannelMutationError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Delete notification channel+ */+export const useDeleteNotificationChannel = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof deleteNotificationChannel>>,+ TError,+ { pathParams: DeleteNotificationChannelPathParameters },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof deleteNotificationChannel>>,+ TError,+ { pathParams: DeleteNotificationChannelPathParameters },+ TContext+> => {+ return useMutation(getDeleteNotificationChannelMutationOptions(options));+};+/**+ * This endpoint returns a notification channel by ID. A channel written by the v1 API can carry a configuration this API does not model.+ * @summary Get notification channel by ID+ */+export const getNotificationChannel = (+ { id }: GetNotificationChannelPathParameters,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<GetNotificationChannel200>({+ url: `/api/v2/notification_channels/${id}`,+ method: 'GET',+ signal,+ });+};++export const getGetNotificationChannelQueryKey = ({+ id,+}: GetNotificationChannelPathParameters) => {+ return [`/api/v2/notification_channels/${id}`] as const;+};++export const getGetNotificationChannelQueryOptions = <+ TData = Awaited<ReturnType<typeof getNotificationChannel>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { id }: GetNotificationChannelPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getNotificationChannel>>,+ TError,+ TData+ >;+ },+) => {+ const { query: queryOptions } = options ?? {};++ const queryKey =+ queryOptions?.queryKey ?? getGetNotificationChannelQueryKey({ id });++ const queryFn: QueryFunction<+ Awaited<ReturnType<typeof getNotificationChannel>>+ > = ({ signal }) => getNotificationChannel({ id }, signal);++ return {+ queryKey,+ queryFn,+ enabled: !!id,+ ...queryOptions,+ } as UseQueryOptions<+ Awaited<ReturnType<typeof getNotificationChannel>>,+ TError,+ TData+ > & { queryKey: QueryKey };+};++export type GetNotificationChannelQueryResult = NonNullable<+ Awaited<ReturnType<typeof getNotificationChannel>>+>;+export type GetNotificationChannelQueryError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Get notification channel by ID+ */++export function useGetNotificationChannel<+ TData = Awaited<ReturnType<typeof getNotificationChannel>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { id }: GetNotificationChannelPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getNotificationChannel>>,+ TError,+ TData+ >;+ },+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {+ const queryOptions = getGetNotificationChannelQueryOptions({ id }, options);++ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {+ queryKey: QueryKey;+ };++ return { ...query, queryKey: queryOptions.queryKey };+}++/**+ * @summary Get notification channel by ID+ */+export const invalidateGetNotificationChannel = async (+ queryClient: QueryClient,+ { id }: GetNotificationChannelPathParameters,+ options?: InvalidateOptions,+): Promise<QueryClient> => {+ await queryClient.invalidateQueries(+ { queryKey: getGetNotificationChannelQueryKey({ id }) },+ options,+ );++ return queryClient;+};++/**+ * This endpoint replaces a notification channel's configuration in full. Neither name is part of the request body: both are immutable. The kind may change, which replaces the channel's notifier configuration.+ * @summary Update notification channel+ */+export const updateNotificationChannel = (+ { id }: UpdateNotificationChannelPathParameters,+ alertmanagertypesUpdatableNotificationChannelDTO?: BodyType<AlertmanagertypesUpdatableNotificationChannelDTO>,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<UpdateNotificationChannel200>({+ url: `/api/v2/notification_channels/${id}`,+ method: 'PUT',+ headers: { 'Content-Type': 'application/json' },+ data: alertmanagertypesUpdatableNotificationChannelDTO,+ signal,+ });+};++export const getUpdateNotificationChannelMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof updateNotificationChannel>>,+ TError,+ {+ pathParams: UpdateNotificationChannelPathParameters;+ data?: BodyType<AlertmanagertypesUpdatableNotificationChannelDTO>;+ },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof updateNotificationChannel>>,+ TError,+ {+ pathParams: UpdateNotificationChannelPathParameters;+ data?: BodyType<AlertmanagertypesUpdatableNotificationChannelDTO>;+ },+ TContext+> => {+ const mutationKey = ['updateNotificationChannel'];+ const { mutation: mutationOptions } = options+ ? options.mutation &&+ 'mutationKey' in options.mutation &&+ options.mutation.mutationKey+ ? options+ : { ...options, mutation: { ...options.mutation, mutationKey } }+ : { mutation: { mutationKey } };++ const mutationFn: MutationFunction<+ Awaited<ReturnType<typeof updateNotificationChannel>>,+ {+ pathParams: UpdateNotificationChannelPathParameters;+ data?: BodyType<AlertmanagertypesUpdatableNotificationChannelDTO>;+ }+ > = (props) => {+ const { pathParams, data } = props ?? {};++ return updateNotificationChannel(pathParams, data);+ };++ return { mutationFn, ...mutationOptions };+};++export type UpdateNotificationChannelMutationResult = NonNullable<+ Awaited<ReturnType<typeof updateNotificationChannel>>+>;+export type UpdateNotificationChannelMutationBody =+ | BodyType<AlertmanagertypesUpdatableNotificationChannelDTO>+ | undefined;+export type UpdateNotificationChannelMutationError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Update notification channel+ */+export const useUpdateNotificationChannel = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof updateNotificationChannel>>,+ TError,+ {+ pathParams: UpdateNotificationChannelPathParameters;+ data?: BodyType<AlertmanagertypesUpdatableNotificationChannelDTO>;+ },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof updateNotificationChannel>>,+ TError,+ {+ pathParams: UpdateNotificationChannelPathParameters;+ data?: BodyType<AlertmanagertypesUpdatableNotificationChannelDTO>;+ },+ TContext+> => {+ return useMutation(getUpdateNotificationChannelMutationOptions(options));+};+/**+ * This endpoint sends a test notification for the configuration in the request body. The channel need not exist and nothing is persisted, so the body carries a configuration only.+ * @summary Test notification channel+ */+export const testNotificationChannel = (+ alertmanagertypesTestableNotificationChannelDTO?: BodyType<AlertmanagertypesTestableNotificationChannelDTO>,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<void>({+ url: `/api/v2/notification_channels/test`,+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ data: alertmanagertypesTestableNotificationChannelDTO,+ signal,+ });+};++export const getTestNotificationChannelMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof testNotificationChannel>>,+ TError,+ { data?: BodyType<AlertmanagertypesTestableNotificationChannelDTO> },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof testNotificationChannel>>,+ TError,+ { data?: BodyType<AlertmanagertypesTestableNotificationChannelDTO> },+ TContext+> => {+ const mutationKey = ['testNotificationChannel'];+ const { mutation: mutationOptions } = options+ ? options.mutation &&+ 'mutationKey' in options.mutation &&+ options.mutation.mutationKey+ ? options+ : { ...options, mutation: { ...options.mutation, mutationKey } }+ : { mutation: { mutationKey } };++ const mutationFn: MutationFunction<+ Awaited<ReturnType<typeof testNotificationChannel>>,+ { data?: BodyType<AlertmanagertypesTestableNotificationChannelDTO> }+ > = (props) => {+ const { data } = props ?? {};++ return testNotificationChannel(data);+ };++ return { mutationFn, ...mutationOptions };+};++export type TestNotificationChannelMutationResult = NonNullable<+ Awaited<ReturnType<typeof testNotificationChannel>>+>;+export type TestNotificationChannelMutationBody =+ | BodyType<AlertmanagertypesTestableNotificationChannelDTO>+ | undefined;+export type TestNotificationChannelMutationError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Test notification channel+ */+export const useTestNotificationChannel = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof testNotificationChannel>>,+ TError,+ { data?: BodyType<AlertmanagertypesTestableNotificationChannelDTO> },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof testNotificationChannel>>,+ TError,+ { data?: BodyType<AlertmanagertypesTestableNotificationChannelDTO> },+ TContext+> => {+ return useMutation(getTestNotificationChannelMutationOptions(options));+};diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex 4c51318791..3c23a19604 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -507,6 +507,15 @@ export enum AlertmanagertypesChannelKindDTO {jsmops = 'jsmops',incidentio = 'incidentio',}+export enum AlertmanagertypesChannelListOrderDTO {+ asc = 'asc',+ desc = 'desc',+}+export enum AlertmanagertypesChannelListSortDTO {+ updated_at = 'updated_at',+ created_at = 'created_at',+ name = 'name',+}export interface ModelLabelSetDTO {[key: string]: string;}@@ -1000,6 +1009,44 @@ export interface AlertmanagertypesJiraReceiverConfigDTO {wont_fix_resolution?: string;}+export interface AlertmanagertypesListedNotificationChannelDTO {+ /**+ * @type string+ * @format date-time+ */+ createdAt: string;+ /**+ * @type string+ */+ displayName: string;+ /**+ * @type string+ */+ id: string;+ kind: AlertmanagertypesChannelKindDTO;+ /**+ * @type string+ */+ name: string;+ /**+ * @type string+ * @format date-time+ */+ updatedAt: string;+}++export interface AlertmanagertypesListableNotificationChannelDTO {+ /**+ * @type array+ */+ channels: AlertmanagertypesListedNotificationChannelDTO[];+ /**+ * @type integer+ * @format int64+ */+ total: number;+}+export enum AlertmanagertypesMaintenanceKindDTO {fixed = 'fixed',recurring = 'recurring',@@ -2391,6 +2438,14 @@ export interface AlertmanagertypesReceiverDTO {wechat_configs?: ConfigWechatConfigDTO[];}+export interface AlertmanagertypesTestableNotificationChannelDTO {+ config: AlertmanagertypesChannelConfigDTO;+}++export interface AlertmanagertypesUpdatableNotificationChannelDTO {+ config: AlertmanagertypesChannelConfigDTO;+}+export interface AuthtypesAttributeMappingDTO {/*** @type string@@ -13219,6 +13274,44 @@ export type GetMetricsTreemap200 = {status: string;};+export type ListNotificationChannelsParams = {+ /**+ * @type string+ * @description undefined+ */+ query?: string;+ /**+ * @description undefined+ */+ kind?: AlertmanagertypesChannelKindDTO;+ /**+ * @description undefined+ */+ sort?: AlertmanagertypesChannelListSortDTO;+ /**+ * @description undefined+ */+ order?: AlertmanagertypesChannelListOrderDTO;+ /**+ * @type integer+ * @description undefined+ */+ limit?: number;+ /**+ * @type integer+ * @description undefined+ */+ offset?: number;+};++export type ListNotificationChannels200 = {+ data: AlertmanagertypesListableNotificationChannelDTO;+ /**+ * @type string+ */+ status: string;+};+export type CreateNotificationChannel201 = {data: AlertmanagertypesGettableNotificationChannelDTO;/**@@ -13227,6 +13320,31 @@ export type CreateNotificationChannel201 = {status: string;};+export type DeleteNotificationChannelPathParameters = {+ id: string;+};+export type GetNotificationChannelPathParameters = {+ id: string;+};+export type GetNotificationChannel200 = {+ data: AlertmanagertypesGettableNotificationChannelDTO;+ /**+ * @type string+ */+ status: string;+};++export type UpdateNotificationChannelPathParameters = {+ id: string;+};+export type UpdateNotificationChannel200 = {+ data: AlertmanagertypesGettableNotificationChannelDTO;+ /**+ * @type string+ */+ status: string;+};+export type GetMyOrganization200 = {data: TypesOrganizationDTO;/**diff --git a/pkg/alertmanager/alertmanager.go b/pkg/alertmanager/alertmanager.goindex 85057646fd..2e71836855 100644--- a/pkg/alertmanager/alertmanager.go+++ b/pkg/alertmanager/alertmanager.go@@ -37,6 +37,9 @@ type Alertmanager interface {// ListAllChannels lists all channels for all organizations. It is used by the legacy alertmanager only.ListAllChannels(context.Context) ([]*alertmanagertypes.Channel, error)+ // Nil params lists every channel, unordered and unpaged.+ ListNotificationChannels(context.Context, string, *alertmanagertypes.ListChannelsParams) (*alertmanagertypes.ListableNotificationChannel, error)+// GetChannelByID gets a channel for the organization.GetChannelByID(context.Context, string, valuer.UUID) (*alertmanagertypes.Channel, error)@@ -48,7 +51,12 @@ type Alertmanager interface {// CreateNotificationChannel takes the postable rather than a receiver, because// a receiver carries only the display name.- CreateNotificationChannel(context.Context, string, *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)+ CreateNotificationChannel(context.Context, string, alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)++ UpdateNotificationChannel(context.Context, string, valuer.UUID, alertmanagertypes.UpdatableNotificationChannel) (*alertmanagertypes.Channel, error)++ // TestNotificationChannel sends a test notification for a channel that need not exist.+ TestNotificationChannel(context.Context, string, alertmanagertypes.TestableNotificationChannel) error// DeleteChannelByID deletes a channel for the organization.DeleteChannelByID(context.Context, string, valuer.UUID) errordiff --git a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.go b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.goindex 6d929307fb..dcdea607c1 100644--- a/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.go+++ b/pkg/alertmanager/alertmanagerstore/sqlalertmanagerstore/config.go@@ -3,6 +3,7 @@ package sqlalertmanagerstoreimport ("context""database/sql"+ "strings""github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/sqlstore"@@ -138,21 +139,88 @@ func (store *config) DeleteChannelByID(ctx context.Context, orgID string, id val}, opts...)}-func (store *config) ListChannels(ctx context.Context, orgID string) ([]*alertmanagertypes.Channel, error) {- var channels []*alertmanagertypes.Channel+func (store *config) ListChannels(ctx context.Context, orgID string, params *alertmanagertypes.ListChannelsParams) ([]*alertmanagertypes.Channel, int64, error) {+ // Nil params means no pagination, so every match is on the only page.+ if params == nil {+ var channels []*alertmanagertypes.Channel- err := store.+ if err := store.+ sqlstore.+ BunDB().+ NewSelect().+ Model(&channels).+ Where("org_id = ?", orgID).+ Scan(ctx); err != nil {+ return nil, 0, err+ }++ return channels, int64(len(channels)), nil+ }++ type listedChannel struct {+ *alertmanagertypes.Channel `bun:",extend"`++ Total int64 `bun:"total"`+ }++ rows := make([]*listedChannel, 0)++ q := store.sqlstore.BunDB().NewSelect().- Model(&channels).- Where("org_id = ?", orgID).- Scan(ctx)- if err != nil {- return nil, err+ Model(&rows).+ ColumnExpr("*").+ ColumnExpr("COUNT(*) OVER () AS total").+ Where("org_id = ?", orgID)++ formatter := store.sqlstore.Formatter()++ if params.Query != "" {+ // LOWER(col) LIKE LOWER(?) behaves the same on SQLite (no ILIKE) and+ // Postgres. The value's % and _ are escaped to match literally, with+ // ESCAPE pinning backslash as the escape character.+ q = q.Where(+ string(formatter.LowerExpression("display_name"))+" LIKE LOWER(?) ESCAPE '\\'",+ "%"+formatter.EscapeLikePattern(params.Query)+"%",+ )}- return channels, nil+ if !params.Kind.IsZero() {+ q = q.Where("type = ?", params.Kind.ToStoredType())+ }++ q = q.+ OrderExpr(params.Sort.ToColumn() + " " + strings.ToUpper(params.Order.StringValue())).+ Limit(params.Limit).+ Offset(params.Offset)++ if err := q.Scan(ctx); err != nil {+ return nil, 0, err+ }++ // COUNT(*) OVER () is computed pre-LIMIT, so any returned row carries the full+ // filter total.+ var total int64+ if len(rows) > 0 {+ total = rows[0].Total+ } else if params.Offset > 0 {+ // An empty page carries no total. At offset zero that means nothing+ // matched, but past the last match it hides the rows the offset skipped.+ matches, err := q.Count(ctx)+ if err != nil {+ return nil, 0, err+ }++ total = int64(matches)+ }++ channels := make([]*alertmanagertypes.Channel, len(rows))+ for index, row := range rows {+ channels[index] = row.Channel+ }++ return channels, total, nil}func (store *config) ListAllChannels(ctx context.Context) ([]*alertmanagertypes.Channel, error) {diff --git a/pkg/alertmanager/alertmanagertest/alertmanager.go b/pkg/alertmanager/alertmanagertest/alertmanager.goindex d28d2f6391..c570da535a 100644--- a/pkg/alertmanager/alertmanagertest/alertmanager.go+++ b/pkg/alertmanager/alertmanagertest/alertmanager.go@@ -292,7 +292,7 @@ func (_c *MockAlertmanager_CreateInhibitRules_Call) RunAndReturn(run func(ctx co}// CreateNotificationChannel provides a mock function for the type MockAlertmanager-func (_mock *MockAlertmanager) CreateNotificationChannel(context1 context.Context, s string, postableNotificationChannel *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error) {+func (_mock *MockAlertmanager) CreateNotificationChannel(context1 context.Context, s string, postableNotificationChannel alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error) {ret := _mock.Called(context1, s, postableNotificationChannel)if len(ret) == 0 {@@ -301,17 +301,17 @@ func (_mock *MockAlertmanager) CreateNotificationChannel(context1 context.Contexvar r0 *alertmanagertypes.Channelvar r1 error- if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)); ok {+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)); ok {return returnFunc(context1, s, postableNotificationChannel)}- if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.PostableNotificationChannel) *alertmanagertypes.Channel); ok {+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, alertmanagertypes.PostableNotificationChannel) *alertmanagertypes.Channel); ok {r0 = returnFunc(context1, s, postableNotificationChannel)} else {if ret.Get(0) != nil {r0 = ret.Get(0).(*alertmanagertypes.Channel)}}- if returnFunc, ok := ret.Get(1).(func(context.Context, string, *alertmanagertypes.PostableNotificationChannel) error); ok {+ if returnFunc, ok := ret.Get(1).(func(context.Context, string, alertmanagertypes.PostableNotificationChannel) error); ok {r1 = returnFunc(context1, s, postableNotificationChannel)} else {r1 = ret.Error(1)@@ -327,12 +327,12 @@ type MockAlertmanager_CreateNotificationChannel_Call struct {// CreateNotificationChannel is a helper method to define mock.On call// - context1 context.Context// - s string-// - postableNotificationChannel *alertmanagertypes.PostableNotificationChannel+// - postableNotificationChannel alertmanagertypes.PostableNotificationChannelfunc (_e *MockAlertmanager_Expecter) CreateNotificationChannel(context1 interface{}, s interface{}, postableNotificationChannel interface{}) *MockAlertmanager_CreateNotificationChannel_Call {return &MockAlertmanager_CreateNotificationChannel_Call{Call: _e.mock.On("CreateNotificationChannel", context1, s, postableNotificationChannel)}}-func (_c *MockAlertmanager_CreateNotificationChannel_Call) Run(run func(context1 context.Context, s string, postableNotificationChannel *alertmanagertypes.PostableNotificationChannel)) *MockAlertmanager_CreateNotificationChannel_Call {+func (_c *MockAlertmanager_CreateNotificationChannel_Call) Run(run func(context1 context.Context, s string, postableNotificationChannel alertmanagertypes.PostableNotificationChannel)) *MockAlertmanager_CreateNotificationChannel_Call {_c.Call.Run(func(args mock.Arguments) {var arg0 context.Contextif args[0] != nil {@@ -342,9 +342,9 @@ func (_c *MockAlertmanager_CreateNotificationChannel_Call) Run(run func(context1if args[1] != nil {arg1 = args[1].(string)}- var arg2 *alertmanagertypes.PostableNotificationChannel+ var arg2 alertmanagertypes.PostableNotificationChannelif args[2] != nil {- arg2 = args[2].(*alertmanagertypes.PostableNotificationChannel)+ arg2 = args[2].(alertmanagertypes.PostableNotificationChannel)}run(arg0,@@ -360,7 +360,7 @@ func (_c *MockAlertmanager_CreateNotificationChannel_Call) Return(channel *alertreturn _c}-func (_c *MockAlertmanager_CreateNotificationChannel_Call) RunAndReturn(run func(context1 context.Context, s string, postableNotificationChannel *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)) *MockAlertmanager_CreateNotificationChannel_Call {+func (_c *MockAlertmanager_CreateNotificationChannel_Call) RunAndReturn(run func(context1 context.Context, s string, postableNotificationChannel alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error)) *MockAlertmanager_CreateNotificationChannel_Call {_c.Call.Return(run)return _c}@@ -1280,6 +1280,80 @@ func (_c *MockAlertmanager_ListChannels_Call) RunAndReturn(run func(context1 conreturn _c}+// ListNotificationChannels provides a mock function for the type MockAlertmanager+func (_mock *MockAlertmanager) ListNotificationChannels(context1 context.Context, s string, listChannelsParams *alertmanagertypes.ListChannelsParams) (*alertmanagertypes.ListableNotificationChannel, error) {+ ret := _mock.Called(context1, s, listChannelsParams)++ if len(ret) == 0 {+ panic("no return value specified for ListNotificationChannels")+ }++ var r0 *alertmanagertypes.ListableNotificationChannel+ var r1 error+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.ListChannelsParams) (*alertmanagertypes.ListableNotificationChannel, error)); ok {+ return returnFunc(context1, s, listChannelsParams)+ }+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, *alertmanagertypes.ListChannelsParams) *alertmanagertypes.ListableNotificationChannel); ok {+ r0 = returnFunc(context1, s, listChannelsParams)+ } else {+ if ret.Get(0) != nil {+ r0 = ret.Get(0).(*alertmanagertypes.ListableNotificationChannel)+ }+ }+ if returnFunc, ok := ret.Get(1).(func(context.Context, string, *alertmanagertypes.ListChannelsParams) error); ok {+ r1 = returnFunc(context1, s, listChannelsParams)+ } else {+ r1 = ret.Error(1)+ }+ return r0, r1+}++// MockAlertmanager_ListNotificationChannels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListNotificationChannels'+type MockAlertmanager_ListNotificationChannels_Call struct {+ *mock.Call+}++// ListNotificationChannels is a helper method to define mock.On call+// - context1 context.Context+// - s string+// - listChannelsParams *alertmanagertypes.ListChannelsParams+func (_e *MockAlertmanager_Expecter) ListNotificationChannels(context1 interface{}, s interface{}, listChannelsParams interface{}) *MockAlertmanager_ListNotificationChannels_Call {+ return &MockAlertmanager_ListNotificationChannels_Call{Call: _e.mock.On("ListNotificationChannels", context1, s, listChannelsParams)}+}++func (_c *MockAlertmanager_ListNotificationChannels_Call) Run(run func(context1 context.Context, s string, listChannelsParams *alertmanagertypes.ListChannelsParams)) *MockAlertmanager_ListNotificationChannels_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 context.Context+ if args[0] != nil {+ arg0 = args[0].(context.Context)+ }+ var arg1 string+ if args[1] != nil {+ arg1 = args[1].(string)+ }+ var arg2 *alertmanagertypes.ListChannelsParams+ if args[2] != nil {+ arg2 = args[2].(*alertmanagertypes.ListChannelsParams)+ }+ run(+ arg0,+ arg1,+ arg2,+ )+ })+ return _c+}++func (_c *MockAlertmanager_ListNotificationChannels_Call) Return(listableNotificationChannel *alertmanagertypes.ListableNotificationChannel, err error) *MockAlertmanager_ListNotificationChannels_Call {+ _c.Call.Return(listableNotificationChannel, err)+ return _c+}++func (_c *MockAlertmanager_ListNotificationChannels_Call) RunAndReturn(run func(context1 context.Context, s string, listChannelsParams *alertmanagertypes.ListChannelsParams) (*alertmanagertypes.ListableNotificationChannel, error)) *MockAlertmanager_ListNotificationChannels_Call {+ _c.Call.Return(run)+ return _c+}+// PutAlerts provides a mock function for the type MockAlertmanagerfunc (_mock *MockAlertmanager) PutAlerts(context1 context.Context, s string, v alertmanagertypes.PostableAlerts) error {ret := _mock.Called(context1, s, v)@@ -1697,6 +1771,69 @@ func (_c *MockAlertmanager_TestAlert_Call) RunAndReturn(run func(ctx context.Conreturn _c}+// TestNotificationChannel provides a mock function for the type MockAlertmanager+func (_mock *MockAlertmanager) TestNotificationChannel(context1 context.Context, s string, testableNotificationChannel alertmanagertypes.TestableNotificationChannel) error {+ ret := _mock.Called(context1, s, testableNotificationChannel)++ if len(ret) == 0 {+ panic("no return value specified for TestNotificationChannel")+ }++ var r0 error+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, alertmanagertypes.TestableNotificationChannel) error); ok {+ r0 = returnFunc(context1, s, testableNotificationChannel)+ } else {+ r0 = ret.Error(0)+ }+ return r0+}++// MockAlertmanager_TestNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TestNotificationChannel'+type MockAlertmanager_TestNotificationChannel_Call struct {+ *mock.Call+}++// TestNotificationChannel is a helper method to define mock.On call+// - context1 context.Context+// - s string+// - testableNotificationChannel alertmanagertypes.TestableNotificationChannel+func (_e *MockAlertmanager_Expecter) TestNotificationChannel(context1 interface{}, s interface{}, testableNotificationChannel interface{}) *MockAlertmanager_TestNotificationChannel_Call {+ return &MockAlertmanager_TestNotificationChannel_Call{Call: _e.mock.On("TestNotificationChannel", context1, s, testableNotificationChannel)}+}++func (_c *MockAlertmanager_TestNotificationChannel_Call) Run(run func(context1 context.Context, s string, testableNotificationChannel alertmanagertypes.TestableNotificationChannel)) *MockAlertmanager_TestNotificationChannel_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 context.Context+ if args[0] != nil {+ arg0 = args[0].(context.Context)+ }+ var arg1 string+ if args[1] != nil {+ arg1 = args[1].(string)+ }+ var arg2 alertmanagertypes.TestableNotificationChannel+ if args[2] != nil {+ arg2 = args[2].(alertmanagertypes.TestableNotificationChannel)+ }+ run(+ arg0,+ arg1,+ arg2,+ )+ })+ return _c+}++func (_c *MockAlertmanager_TestNotificationChannel_Call) Return(err error) *MockAlertmanager_TestNotificationChannel_Call {+ _c.Call.Return(err)+ return _c+}++func (_c *MockAlertmanager_TestNotificationChannel_Call) RunAndReturn(run func(context1 context.Context, s string, testableNotificationChannel alertmanagertypes.TestableNotificationChannel) error) *MockAlertmanager_TestNotificationChannel_Call {+ _c.Call.Return(run)+ return _c+}+// TestReceiver provides a mock function for the type MockAlertmanagerfunc (_mock *MockAlertmanager) TestReceiver(context1 context.Context, s string, receiver *alertmanagertypes.Receiver) error {ret := _mock.Called(context1, s, receiver)@@ -1892,6 +2029,86 @@ func (_c *MockAlertmanager_UpdateChannelByReceiverAndID_Call) RunAndReturn(run freturn _c}+// UpdateNotificationChannel provides a mock function for the type MockAlertmanager+func (_mock *MockAlertmanager) UpdateNotificationChannel(context1 context.Context, s string, uUID valuer.UUID, updatableNotificationChannel alertmanagertypes.UpdatableNotificationChannel) (*alertmanagertypes.Channel, error) {+ ret := _mock.Called(context1, s, uUID, updatableNotificationChannel)++ if len(ret) == 0 {+ panic("no return value specified for UpdateNotificationChannel")+ }++ var r0 *alertmanagertypes.Channel+ var r1 error+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, valuer.UUID, alertmanagertypes.UpdatableNotificationChannel) (*alertmanagertypes.Channel, error)); ok {+ return returnFunc(context1, s, uUID, updatableNotificationChannel)+ }+ if returnFunc, ok := ret.Get(0).(func(context.Context, string, valuer.UUID, alertmanagertypes.UpdatableNotificationChannel) *alertmanagertypes.Channel); ok {+ r0 = returnFunc(context1, s, uUID, updatableNotificationChannel)+ } else {+ if ret.Get(0) != nil {+ r0 = ret.Get(0).(*alertmanagertypes.Channel)+ }+ }+ if returnFunc, ok := ret.Get(1).(func(context.Context, string, valuer.UUID, alertmanagertypes.UpdatableNotificationChannel) error); ok {+ r1 = returnFunc(context1, s, uUID, updatableNotificationChannel)+ } else {+ r1 = ret.Error(1)+ }+ return r0, r1+}++// MockAlertmanager_UpdateNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateNotificationChannel'+type MockAlertmanager_UpdateNotificationChannel_Call struct {+ *mock.Call+}++// UpdateNotificationChannel is a helper method to define mock.On call+// - context1 context.Context+// - s string+// - uUID valuer.UUID+// - updatableNotificationChannel alertmanagertypes.UpdatableNotificationChannel+func (_e *MockAlertmanager_Expecter) UpdateNotificationChannel(context1 interface{}, s interface{}, uUID interface{}, updatableNotificationChannel interface{}) *MockAlertmanager_UpdateNotificationChannel_Call {+ return &MockAlertmanager_UpdateNotificationChannel_Call{Call: _e.mock.On("UpdateNotificationChannel", context1, s, uUID, updatableNotificationChannel)}+}++func (_c *MockAlertmanager_UpdateNotificationChannel_Call) Run(run func(context1 context.Context, s string, uUID valuer.UUID, updatableNotificationChannel alertmanagertypes.UpdatableNotificationChannel)) *MockAlertmanager_UpdateNotificationChannel_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 context.Context+ if args[0] != nil {+ arg0 = args[0].(context.Context)+ }+ var arg1 string+ if args[1] != nil {+ arg1 = args[1].(string)+ }+ var arg2 valuer.UUID+ if args[2] != nil {+ arg2 = args[2].(valuer.UUID)+ }+ var arg3 alertmanagertypes.UpdatableNotificationChannel+ if args[3] != nil {+ arg3 = args[3].(alertmanagertypes.UpdatableNotificationChannel)+ }+ run(+ arg0,+ arg1,+ arg2,+ arg3,+ )+ })+ return _c+}++func (_c *MockAlertmanager_UpdateNotificationChannel_Call) Return(channel *alertmanagertypes.Channel, err error) *MockAlertmanager_UpdateNotificationChannel_Call {+ _c.Call.Return(channel, err)+ return _c+}++func (_c *MockAlertmanager_UpdateNotificationChannel_Call) RunAndReturn(run func(context1 context.Context, s string, uUID valuer.UUID, updatableNotificationChannel alertmanagertypes.UpdatableNotificationChannel) (*alertmanagertypes.Channel, error)) *MockAlertmanager_UpdateNotificationChannel_Call {+ _c.Call.Return(run)+ return _c+}+// UpdateRoutePolicyByID provides a mock function for the type MockAlertmanagerfunc (_mock *MockAlertmanager) UpdateRoutePolicyByID(ctx context.Context, routeID string, route *alertmanagertypes.PostableRoutePolicy) (*alertmanagertypes.GettableRoutePolicy, error) {ret := _mock.Called(ctx, routeID, route)@@ -2177,6 +2394,52 @@ func (_c *MockHandler_DeleteChannelByID_Call) RunAndReturn(run func(responseWritreturn _c}+// DeleteNotificationChannel provides a mock function for the type MockHandler+func (_mock *MockHandler) DeleteNotificationChannel(responseWriter http.ResponseWriter, request *http.Request) {+ _mock.Called(responseWriter, request)+ return+}++// MockHandler_DeleteNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeleteNotificationChannel'+type MockHandler_DeleteNotificationChannel_Call struct {+ *mock.Call+}++// DeleteNotificationChannel is a helper method to define mock.On call+// - responseWriter http.ResponseWriter+// - request *http.Request+func (_e *MockHandler_Expecter) DeleteNotificationChannel(responseWriter interface{}, request interface{}) *MockHandler_DeleteNotificationChannel_Call {+ return &MockHandler_DeleteNotificationChannel_Call{Call: _e.mock.On("DeleteNotificationChannel", responseWriter, request)}+}++func (_c *MockHandler_DeleteNotificationChannel_Call) Run(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_DeleteNotificationChannel_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 http.ResponseWriter+ if args[0] != nil {+ arg0 = args[0].(http.ResponseWriter)+ }+ var arg1 *http.Request+ if args[1] != nil {+ arg1 = args[1].(*http.Request)+ }+ run(+ arg0,+ arg1,+ )+ })+ return _c+}++func (_c *MockHandler_DeleteNotificationChannel_Call) Return() *MockHandler_DeleteNotificationChannel_Call {+ _c.Call.Return()+ return _c+}++func (_c *MockHandler_DeleteNotificationChannel_Call) RunAndReturn(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_DeleteNotificationChannel_Call {+ _c.Run(run)+ return _c+}+// DeleteRoutePolicyByID provides a mock function for the type MockHandlerfunc (_mock *MockHandler) DeleteRoutePolicyByID(responseWriter http.ResponseWriter, request *http.Request) {_mock.Called(responseWriter, request)@@ -2361,6 +2624,52 @@ func (_c *MockHandler_GetChannelByID_Call) RunAndReturn(run func(responseWriterreturn _c}+// GetNotificationChannel provides a mock function for the type MockHandler+func (_mock *MockHandler) GetNotificationChannel(responseWriter http.ResponseWriter, request *http.Request) {+ _mock.Called(responseWriter, request)+ return+}++// MockHandler_GetNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetNotificationChannel'+type MockHandler_GetNotificationChannel_Call struct {+ *mock.Call+}++// GetNotificationChannel is a helper method to define mock.On call+// - responseWriter http.ResponseWriter+// - request *http.Request+func (_e *MockHandler_Expecter) GetNotificationChannel(responseWriter interface{}, request interface{}) *MockHandler_GetNotificationChannel_Call {+ return &MockHandler_GetNotificationChannel_Call{Call: _e.mock.On("GetNotificationChannel", responseWriter, request)}+}++func (_c *MockHandler_GetNotificationChannel_Call) Run(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_GetNotificationChannel_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 http.ResponseWriter+ if args[0] != nil {+ arg0 = args[0].(http.ResponseWriter)+ }+ var arg1 *http.Request+ if args[1] != nil {+ arg1 = args[1].(*http.Request)+ }+ run(+ arg0,+ arg1,+ )+ })+ return _c+}++func (_c *MockHandler_GetNotificationChannel_Call) Return() *MockHandler_GetNotificationChannel_Call {+ _c.Call.Return()+ return _c+}++func (_c *MockHandler_GetNotificationChannel_Call) RunAndReturn(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_GetNotificationChannel_Call {+ _c.Run(run)+ return _c+}+// GetRoutePolicyByID provides a mock function for the type MockHandlerfunc (_mock *MockHandler) GetRoutePolicyByID(responseWriter http.ResponseWriter, request *http.Request) {_mock.Called(responseWriter, request)@@ -2499,6 +2808,98 @@ func (_c *MockHandler_ListChannels_Call) RunAndReturn(run func(responseWriter htreturn _c}+// ListNotificationChannels provides a mock function for the type MockHandler+func (_mock *MockHandler) ListNotificationChannels(responseWriter http.ResponseWriter, request *http.Request) {+ _mock.Called(responseWriter, request)+ return+}++// MockHandler_ListNotificationChannels_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListNotificationChannels'+type MockHandler_ListNotificationChannels_Call struct {+ *mock.Call+}++// ListNotificationChannels is a helper method to define mock.On call+// - responseWriter http.ResponseWriter+// - request *http.Request+func (_e *MockHandler_Expecter) ListNotificationChannels(responseWriter interface{}, request interface{}) *MockHandler_ListNotificationChannels_Call {+ return &MockHandler_ListNotificationChannels_Call{Call: _e.mock.On("ListNotificationChannels", responseWriter, request)}+}++func (_c *MockHandler_ListNotificationChannels_Call) Run(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_ListNotificationChannels_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 http.ResponseWriter+ if args[0] != nil {+ arg0 = args[0].(http.ResponseWriter)+ }+ var arg1 *http.Request+ if args[1] != nil {+ arg1 = args[1].(*http.Request)+ }+ run(+ arg0,+ arg1,+ )+ })+ return _c+}++func (_c *MockHandler_ListNotificationChannels_Call) Return() *MockHandler_ListNotificationChannels_Call {+ _c.Call.Return()+ return _c+}++func (_c *MockHandler_ListNotificationChannels_Call) RunAndReturn(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_ListNotificationChannels_Call {+ _c.Run(run)+ return _c+}++// TestNotificationChannel provides a mock function for the type MockHandler+func (_mock *MockHandler) TestNotificationChannel(responseWriter http.ResponseWriter, request *http.Request) {+ _mock.Called(responseWriter, request)+ return+}++// MockHandler_TestNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'TestNotificationChannel'+type MockHandler_TestNotificationChannel_Call struct {+ *mock.Call+}++// TestNotificationChannel is a helper method to define mock.On call+// - responseWriter http.ResponseWriter+// - request *http.Request+func (_e *MockHandler_Expecter) TestNotificationChannel(responseWriter interface{}, request interface{}) *MockHandler_TestNotificationChannel_Call {+ return &MockHandler_TestNotificationChannel_Call{Call: _e.mock.On("TestNotificationChannel", responseWriter, request)}+}++func (_c *MockHandler_TestNotificationChannel_Call) Run(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_TestNotificationChannel_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 http.ResponseWriter+ if args[0] != nil {+ arg0 = args[0].(http.ResponseWriter)+ }+ var arg1 *http.Request+ if args[1] != nil {+ arg1 = args[1].(*http.Request)+ }+ run(+ arg0,+ arg1,+ )+ })+ return _c+}++func (_c *MockHandler_TestNotificationChannel_Call) Return() *MockHandler_TestNotificationChannel_Call {+ _c.Call.Return()+ return _c+}++func (_c *MockHandler_TestNotificationChannel_Call) RunAndReturn(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_TestNotificationChannel_Call {+ _c.Run(run)+ return _c+}+// TestReceiver provides a mock function for the type MockHandlerfunc (_mock *MockHandler) TestReceiver(responseWriter http.ResponseWriter, request *http.Request) {_mock.Called(responseWriter, request)@@ -2591,6 +2992,52 @@ func (_c *MockHandler_UpdateChannelByID_Call) RunAndReturn(run func(responseWritreturn _c}+// UpdateNotificationChannel provides a mock function for the type MockHandler+func (_mock *MockHandler) UpdateNotificationChannel(responseWriter http.ResponseWriter, request *http.Request) {+ _mock.Called(responseWriter, request)+ return+}++// MockHandler_UpdateNotificationChannel_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateNotificationChannel'+type MockHandler_UpdateNotificationChannel_Call struct {+ *mock.Call+}++// UpdateNotificationChannel is a helper method to define mock.On call+// - responseWriter http.ResponseWriter+// - request *http.Request+func (_e *MockHandler_Expecter) UpdateNotificationChannel(responseWriter interface{}, request interface{}) *MockHandler_UpdateNotificationChannel_Call {+ return &MockHandler_UpdateNotificationChannel_Call{Call: _e.mock.On("UpdateNotificationChannel", responseWriter, request)}+}++func (_c *MockHandler_UpdateNotificationChannel_Call) Run(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_UpdateNotificationChannel_Call {+ _c.Call.Run(func(args mock.Arguments) {+ var arg0 http.ResponseWriter+ if args[0] != nil {+ arg0 = args[0].(http.ResponseWriter)+ }+ var arg1 *http.Request+ if args[1] != nil {+ arg1 = args[1].(*http.Request)+ }+ run(+ arg0,+ arg1,+ )+ })+ return _c+}++func (_c *MockHandler_UpdateNotificationChannel_Call) Return() *MockHandler_UpdateNotificationChannel_Call {+ _c.Call.Return()+ return _c+}++func (_c *MockHandler_UpdateNotificationChannel_Call) RunAndReturn(run func(responseWriter http.ResponseWriter, request *http.Request)) *MockHandler_UpdateNotificationChannel_Call {+ _c.Run(run)+ return _c+}+// UpdateRoutePolicy provides a mock function for the type MockHandlerfunc (_mock *MockHandler) UpdateRoutePolicy(responseWriter http.ResponseWriter, request *http.Request) {_mock.Called(responseWriter, request)diff --git a/pkg/alertmanager/handler.go b/pkg/alertmanager/handler.goindex afc94de0ef..617796e7f7 100644--- a/pkg/alertmanager/handler.go+++ b/pkg/alertmanager/handler.go@@ -19,8 +19,18 @@ type Handler interface {DeleteChannelByID(http.ResponseWriter, *http.Request)+ ListNotificationChannels(http.ResponseWriter, *http.Request)++ GetNotificationChannel(http.ResponseWriter, *http.Request)+CreateNotificationChannel(http.ResponseWriter, *http.Request)+ UpdateNotificationChannel(http.ResponseWriter, *http.Request)++ DeleteNotificationChannel(http.ResponseWriter, *http.Request)++ TestNotificationChannel(http.ResponseWriter, *http.Request)+GetAllRoutePolicies(http.ResponseWriter, *http.Request)GetRoutePolicyByID(http.ResponseWriter, *http.Request)diff --git a/pkg/alertmanager/service.go b/pkg/alertmanager/service.goindex 955205b48c..05e86e5fed 100644--- a/pkg/alertmanager/service.go+++ b/pkg/alertmanager/service.go@@ -240,7 +240,7 @@ func (service *Service) getConfig(ctx context.Context, orgID string) (*alertmana}func (service *Service) compareAndSelectConfig(ctx context.Context, incomingConfig *alertmanagertypes.Config) (*alertmanagertypes.Config, error) {- channels, err := service.configStore.ListChannels(ctx, incomingConfig.StoreableConfig().OrgID)+ channels, _, err := service.configStore.ListChannels(ctx, incomingConfig.StoreableConfig().OrgID, nil)if err != nil {return nil, err}diff --git a/pkg/alertmanager/signozalertmanager/handler_channel.go b/pkg/alertmanager/signozalertmanager/handler_channel.goindex dd514ea10a..131fae05da 100644--- a/pkg/alertmanager/signozalertmanager/handler_channel.go+++ b/pkg/alertmanager/signozalertmanager/handler_channel.go@@ -5,10 +5,13 @@ import ("net/http""time"+ "github.com/SigNoz/signoz/pkg/errors""github.com/SigNoz/signoz/pkg/http/binding""github.com/SigNoz/signoz/pkg/http/render""github.com/SigNoz/signoz/pkg/types/alertmanagertypes""github.com/SigNoz/signoz/pkg/types/authtypes"+ "github.com/SigNoz/signoz/pkg/valuer"+ "github.com/gorilla/mux")func (handler *handler) CreateNotificationChannel(rw http.ResponseWriter, req *http.Request) {@@ -21,8 +24,8 @@ func (handler *handler) CreateNotificationChannel(rw http.ResponseWriter, req *hreturn}- postable := new(alertmanagertypes.PostableNotificationChannel)- if err := binding.JSON.BindBody(req.Body, postable); err != nil {+ postable := alertmanagertypes.PostableNotificationChannel{}+ if err := binding.JSON.BindBody(req.Body, &postable); err != nil {render.Error(rw, err)return}@@ -41,3 +44,150 @@ func (handler *handler) CreateNotificationChannel(rw http.ResponseWriter, req *hrender.Success(rw, http.StatusCreated, gettable)}++func (handler *handler) ListNotificationChannels(rw http.ResponseWriter, req *http.Request) {+ ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)+ defer cancel()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ params := new(alertmanagertypes.ListChannelsParams)+ if err := binding.Query.BindQuery(req.URL.Query(), params); err != nil {+ render.Error(rw, err)+ return+ }++ if err := params.Validate(); err != nil {+ render.Error(rw, err)+ return+ }++ // todo(@namanv3): use valuer.MustNewUUID(claims.OrgID) from here till the store method.+ listed, err := handler.alertmanager.ListNotificationChannels(ctx, claims.OrgID, params)+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, listed)+}++func (handler *handler) GetNotificationChannel(rw http.ResponseWriter, req *http.Request) {+ ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)+ defer cancel()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ id, err := valuer.NewUUID(mux.Vars(req)["id"])+ if err != nil {+ render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "id is not a valid uuid-v7"))+ return+ }++ channel, err := handler.alertmanager.GetChannelByID(ctx, claims.OrgID, id)+ if err != nil {+ render.Error(rw, err)+ return+ }++ gettable, err := channel.ToGettableNotificationChannel()+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, gettable)+}++func (handler *handler) UpdateNotificationChannel(rw http.ResponseWriter, req *http.Request) {+ ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)+ defer cancel()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ id, err := valuer.NewUUID(mux.Vars(req)["id"])+ if err != nil {+ render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "id is not a valid uuid-v7"))+ return+ }++ updatable := alertmanagertypes.UpdatableNotificationChannel{}+ if err := binding.JSON.BindBody(req.Body, &updatable); err != nil {+ render.Error(rw, err)+ return+ }++ channel, err := handler.alertmanager.UpdateNotificationChannel(ctx, claims.OrgID, id, updatable)+ if err != nil {+ render.Error(rw, err)+ return+ }++ gettable, err := channel.ToGettableNotificationChannel()+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, gettable)+}++func (handler *handler) DeleteNotificationChannel(rw http.ResponseWriter, req *http.Request) {+ ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)+ defer cancel()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ id, err := valuer.NewUUID(mux.Vars(req)["id"])+ if err != nil {+ render.Error(rw, errors.NewInvalidInputf(errors.CodeInvalidInput, "id is not a valid uuid-v7"))+ return+ }++ if err := handler.alertmanager.DeleteChannelByID(ctx, claims.OrgID, id); err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusNoContent, nil)+}++func (handler *handler) TestNotificationChannel(rw http.ResponseWriter, req *http.Request) {+ ctx, cancel := context.WithTimeout(req.Context(), 30*time.Second)+ defer cancel()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ testable := alertmanagertypes.TestableNotificationChannel{}+ if err := binding.JSON.BindBody(req.Body, &testable); err != nil {+ render.Error(rw, err)+ return+ }++ if err := handler.alertmanager.TestNotificationChannel(ctx, claims.OrgID, testable); err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusNoContent, nil)+}diff --git a/pkg/alertmanager/signozalertmanager/provider.go b/pkg/alertmanager/signozalertmanager/provider.goindex 4e7bf71fcb..4c2478d15b 100644--- a/pkg/alertmanager/signozalertmanager/provider.go+++ b/pkg/alertmanager/signozalertmanager/provider.go@@ -141,7 +141,23 @@ func (provider *provider) TestAlert(ctx context.Context, orgID string, ruleID st}func (provider *provider) ListChannels(ctx context.Context, orgID string) ([]*alertmanagertypes.Channel, error) {- return provider.configStore.ListChannels(ctx, orgID)+ channels, _, err := provider.configStore.ListChannels(ctx, orgID, nil)++ return channels, err+}++func (provider *provider) ListNotificationChannels(ctx context.Context, orgID string, params *alertmanagertypes.ListChannelsParams) (*alertmanagertypes.ListableNotificationChannel, error) {+ channels, total, err := provider.configStore.ListChannels(ctx, orgID, params)+ if err != nil {+ return nil, err+ }++ listed := make([]*alertmanagertypes.ListedNotificationChannel, 0, len(channels))+ for _, channel := range channels {+ listed = append(listed, channel.ToListedNotificationChannel())+ }++ return &alertmanagertypes.ListableNotificationChannel{Channels: listed, Total: total}, nil}func (provider *provider) ListAllChannels(ctx context.Context) ([]*alertmanagertypes.Channel, error) {@@ -244,7 +260,7 @@ func (provider *provider) CreateChannel(ctx context.Context, orgID string, receireturn channel, nil}-func (provider *provider) CreateNotificationChannel(ctx context.Context, orgID string, postable *alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error) {+func (provider *provider) CreateNotificationChannel(ctx context.Context, orgID string, postable alertmanagertypes.PostableNotificationChannel) (*alertmanagertypes.Channel, error) {receiver, err := postable.ToReceiver()if err != nil {return nil, err@@ -278,6 +294,55 @@ func (provider *provider) CreateNotificationChannel(ctx context.Context, orgID sreturn channel, nil}+// UpdateNotificationChannel replaces the channel's configuration. The display+// name is not in the updatable body because it cannot change, so it is read off+// the stored channel and fed back into the receiver.+func (provider *provider) UpdateNotificationChannel(ctx context.Context, orgID string, id valuer.UUID, updatable alertmanagertypes.UpdatableNotificationChannel) (*alertmanagertypes.Channel, error) {+ channel, err := provider.configStore.GetChannelByID(ctx, orgID, id)+ if err != nil {+ return nil, err+ }++ receiver, err := updatable.ToReceiver(channel.DisplayName)+ if err != nil {+ return nil, err+ }++ if err := channel.Update(receiver); err != nil {+ return nil, err+ }++ config, err := provider.configStore.Get(ctx, orgID)+ if err != nil {+ return nil, err+ }++ if err := config.SetGlobalConfig(provider.config.Signoz.Global); err != nil {+ return nil, err+ }++ if err := config.UpdateReceiver(receiver); err != nil {+ return nil, err+ }++ if err := provider.configStore.UpdateChannel(ctx, orgID, channel, alertmanagertypes.WithCb(func(ctx context.Context) error {+ return provider.configStore.Set(ctx, config)+ })); err != nil {+ return nil, err+ }++ return channel, nil+}++func (provider *provider) TestNotificationChannel(ctx context.Context, orgID string, testable alertmanagertypes.TestableNotificationChannel) error {+ receiver, err := testable.ToReceiver()+ if err != nil {+ return err+ }++ return provider.service.TestReceiver(ctx, orgID, receiver)+}+func (provider *provider) Config() alertmanagerserver.Config {return provider.config.Signoz.Config}@@ -300,7 +365,7 @@ func (provider *provider) SetDefaultConfig(ctx context.Context, orgID string) er}func (provider *provider) Collect(ctx context.Context, orgID valuer.UUID) (map[string]any, error) {- channels, err := provider.configStore.ListChannels(ctx, orgID.String())+ channels, _, err := provider.configStore.ListChannels(ctx, orgID.String(), nil)if err != nil {return nil, err}diff --git a/pkg/apiserver/signozapiserver/alertmanager.go b/pkg/apiserver/signozapiserver/alertmanager.goindex c584eff518..f2b4b283ed 100644--- a/pkg/apiserver/signozapiserver/alertmanager.go+++ b/pkg/apiserver/signozapiserver/alertmanager.go@@ -158,6 +158,140 @@ func (provider *provider) addAlertmanagerRoutes(router *mux.Router) error {return err}+ if err := router.Handle("/api/v2/notification_channels", handler.New(+ provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.ListNotificationChannels, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "ListNotificationChannels",+ Tags: []string{"channels"},+ Summary: "List notification channels",+ Description: "Returns a page of notification channels for the org. Each entry carries the channel's identity and kind but not its configuration; fetch a channel by ID for that. Supports a case-insensitive display name search (`query`), a kind filter (`kind`), sort (`updated_at`/`created_at`/`name`), order (`asc`/`desc`), and offset-based pagination (`limit`/`offset`).",+ Request: nil,+ RequestQuery: new(alertmanagertypes.ListChannelsParams),+ RequestContentType: "",+ Response: new(alertmanagertypes.ListableNotificationChannel),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbList)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceNotificationChannel,+ Verb: coretypes.VerbList,+ Category: coretypes.ActionCategoryDataAccess,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodGet).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/notification_channels/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.GetNotificationChannel, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName, authtypes.SigNozViewerRoleName),+ handler.OpenAPIDef{+ ID: "GetNotificationChannel",+ Tags: []string{"channels"},+ Summary: "Get notification channel by ID",+ Description: "This endpoint returns a notification channel by ID. A channel written by the v1 API can carry a configuration this API does not model.",+ Request: nil,+ RequestContentType: "",+ Response: new(alertmanagertypes.GettableNotificationChannel),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbRead)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceNotificationChannel,+ Verb: coretypes.VerbRead,+ Category: coretypes.ActionCategoryDataAccess,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodGet).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/notification_channels/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.UpdateNotificationChannel, authtypes.SigNozAdminRoleName),+ handler.OpenAPIDef{+ ID: "UpdateNotificationChannel",+ Tags: []string{"channels"},+ Summary: "Update notification channel",+ Description: "This endpoint replaces a notification channel's configuration in full. Neither name is part of the request body: both are immutable. The kind may change, which replaces the channel's notifier configuration.",+ Request: new(alertmanagertypes.UpdatableNotificationChannel),+ RequestContentType: "application/json",+ Response: new(alertmanagertypes.GettableNotificationChannel),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbUpdate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceNotificationChannel,+ Verb: coretypes.VerbUpdate,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodPut).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/notification_channels/{id}", handler.New(+ provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.DeleteNotificationChannel, authtypes.SigNozAdminRoleName),+ handler.OpenAPIDef{+ ID: "DeleteNotificationChannel",+ Tags: []string{"channels"},+ Summary: "Delete notification channel",+ Description: "This endpoint deletes a notification channel by ID",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbDelete)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceNotificationChannel,+ Verb: coretypes.VerbDelete,+ Category: coretypes.ActionCategoryConfigurationChange,+ ID: coretypes.PathParam("id"),+ Selector: coretypes.IDSelector,+ }),+ )).Methods(http.MethodDelete).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/notification_channels/test", handler.New(+ provider.authzMiddleware.CheckResources(provider.alertmanagerHandler.TestNotificationChannel, authtypes.SigNozAdminRoleName, authtypes.SigNozEditorRoleName),+ handler.OpenAPIDef{+ ID: "TestNotificationChannel",+ Tags: []string{"channels"},+ Summary: "Test notification channel",+ Description: "This endpoint sends a test notification for the configuration in the request body. The channel need not exist and nothing is persisted, so the body carries a configuration only.",+ Request: new(alertmanagertypes.TestableNotificationChannel),+ RequestContentType: "application/json",+ Response: nil,+ ResponseContentType: "",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceNotificationChannel.Scope(coretypes.VerbCreate)}),+ },+ handler.WithResourceDefs(handler.BasicResourceDef{+ Resource: coretypes.ResourceMetaResourceNotificationChannel,+ Verb: coretypes.VerbCreate,+ Category: coretypes.ActionCategoryConfigurationChange,+ Selector: coretypes.WildcardSelector,+ }),+ )).Methods(http.MethodPost).GetError(); err != nil {+ return err+ }+if err := router.Handle("/api/v1/route_policies", handler.New(provider.authzMiddleware.ViewAccess(provider.alertmanagerHandler.GetAllRoutePolicies), handler.OpenAPIDef{ID: "GetAllRoutePolicies",Tags: []string{"routepolicies"},diff --git a/pkg/types/alertmanagertypes/channelapi.go b/pkg/types/alertmanagertypes/channelapi.goindex 51bd23932f..2d75485c84 100644--- a/pkg/types/alertmanagertypes/channelapi.go+++ b/pkg/types/alertmanagertypes/channelapi.go@@ -25,16 +25,10 @@ type PostableNotificationChannel struct {}func (p *PostableNotificationChannel) UnmarshalJSON(data []byte) error {- dec := json.NewDecoder(bytes.NewReader(data))- dec.DisallowUnknownFields()-type alias PostableNotificationChannelvar tmp alias- if err := dec.Decode(&tmp); err != nil {- if errors.Ast(err, errors.TypeInvalidInput) {- return err- }- return errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "%s", err.Error())+ if err := decodeStrict(data, &tmp); err != nil {+ return err}*p = PostableNotificationChannel(tmp)@@ -92,6 +86,81 @@ func (p *PostableNotificationChannel) validateName() error {return nil}+// ════════════════════════════════════════════════════════════════════════+// Updatable+// ════════════════════════════════════════════════════════════════════════++// Name is immutable, and DisplayName cannot be edited until the routing+// policies and rules referencing it migrate onto Name.+type UpdatableNotificationChannel struct {+ Config ChannelConfig `json:"config" required:"true"`+}++func (u *UpdatableNotificationChannel) UnmarshalJSON(data []byte) error {+ if err := decodeChannelConfigBody(data, &u.Config); err != nil {+ return err+ }++ return u.Validate()+}++func (u *UpdatableNotificationChannel) Validate() error {+ return u.Config.Validate()+}++// ════════════════════════════════════════════════════════════════════════+// Testable+// ════════════════════════════════════════════════════════════════════════++// It carries no name because nothing is persisted: the receiver a test builds+// is thrown away once the notification is delivered.+type TestableNotificationChannel struct {+ Config ChannelConfig `json:"config" required:"true"`+}++func (t *TestableNotificationChannel) UnmarshalJSON(data []byte) error {+ if err := decodeChannelConfigBody(data, &t.Config); err != nil {+ return err+ }++ return t.Validate()+}++func (t *TestableNotificationChannel) Validate() error {+ return t.Config.Validate()+}++func decodeChannelConfigBody(data []byte, config *ChannelConfig) error {+ var body struct {+ Config ChannelConfig `json:"config"`+ }++ if err := decodeStrict(data, &body); err != nil {+ return err+ }++ *config = body.Config++ return nil+}++// decodeStrict rejects unknown fields. A nested UnmarshalJSON (ChannelConfig,+// then the spec) already reports which level failed, so its error is returned+// as it is rather than re-wrapped.+func decodeStrict(data []byte, target any) error {+ dec := json.NewDecoder(bytes.NewReader(data))+ dec.DisallowUnknownFields()++ if err := dec.Decode(target); err != nil {+ if errors.Ast(err, errors.TypeInvalidInput) {+ return err+ }+ return errors.WrapInvalidInputf(err, ErrCodeAlertmanagerChannelInvalid, "%s", err.Error())+ }++ return nil+}+// ════════════════════════════════════════════════════════════════════════// Gettable// ════════════════════════════════════════════════════════════════════════@@ -104,3 +173,25 @@ type GettableNotificationChannel struct {CreatedAt time.Time `json:"createdAt" required:"true"`UpdatedAt time.Time `json:"updatedAt" required:"true"`}++// ════════════════════════════════════════════════════════════════════════+// Listed+// ════════════════════════════════════════════════════════════════════════++// ListedNotificationChannel carries no configuration. The spec, credentials+// included, is only returned by a fetch by ID.+type ListedNotificationChannel struct {+ ID valuer.UUID `json:"id" required:"true"`+ Name string `json:"name" required:"true"`+ DisplayName string `json:"displayName" required:"true"`+ Kind ChannelKind `json:"kind" required:"true"`+ CreatedAt time.Time `json:"createdAt" required:"true"`+ UpdatedAt time.Time `json:"updatedAt" required:"true"`+}++// ListableNotificationChannel is one page of the channel list. Total counts every+// channel the filter matches, not just the ones on the page.+type ListableNotificationChannel struct {+ Channels []*ListedNotificationChannel `json:"channels" required:"true" nullable:"false"`+ Total int64 `json:"total" required:"true"`+}diff --git a/pkg/types/alertmanagertypes/channelconfig.go b/pkg/types/alertmanagertypes/channelconfig.goindex eed0ba00ea..07059efd6c 100644--- a/pkg/types/alertmanagertypes/channelconfig.go+++ b/pkg/types/alertmanagertypes/channelconfig.go@@ -57,6 +57,28 @@ func (t ChannelKind) IsValid() bool {return slices.ContainsFunc(t.Enum(), func(v any) bool { return v == t })}+// ToStoredType returns the Channel.Type a channel of this kind is stored under,+// which matches the kind for all but msteams.+func (t ChannelKind) ToStoredType() string {+ if t == ChannelKindMSTeams {+ return "msteamsv2"+ }++ return t.StringValue()+}++// parseStoredChannelType inverts ToStoredType. It reports false for the notifier+// kinds v1 accepted but v2 does not model.+func parseStoredChannelType(stored string) (ChannelKind, bool) {+ for _, channelKind := range channelKinds {+ if channelKind.kind.ToStoredType() == stored {+ return channelKind.kind, true+ }+ }++ return ChannelKind{}, false+}+func ErrUnsupportedChannelKind(s string) error {return errors.Newf(errors.TypeInvalidInput,@@ -1108,11 +1130,21 @@ func resolveSendResolved(sendResolved *bool, upstreamDefault bool) bool {}func allowedValuesForChannelKind() string {- values := make([]string, 0, len(channelKinds))- for _, channelKind := range channelKinds {- values = append(values, "`"+channelKind.kind.StringValue()+"`")+ return formatAllowedValues((ChannelKind{}).Enum())+}++func formatAllowedValues(enum []any) string {+ values := make([]string, 0, len(enum))+ for _, value := range enum {+ stringValuer, ok := value.(interface{ StringValue() string })+ if !ok {+ continue+ }++ values = append(values, "`"+stringValuer.StringValue()+"`")}slices.Sort(values)+return strings.Join(values, ", ")}diff --git a/pkg/types/alertmanagertypes/channelconvertors.go b/pkg/types/alertmanagertypes/channelconvertors.goindex 0498197065..3dbe6cef9c 100644--- a/pkg/types/alertmanagertypes/channelconvertors.go+++ b/pkg/types/alertmanagertypes/channelconvertors.go@@ -29,6 +29,22 @@ func (p *PostableNotificationChannel) ToReceiver() (*Receiver, error) {return newDefaultedReceiver(receiver)}+// ToReceiver builds the upstream receiver for an existing channel, whose display+// name the caller supplies because the update body cannot carry it.+func (u *UpdatableNotificationChannel) ToReceiver(displayName string) (*Receiver, error) {+ postable := PostableNotificationChannel{DisplayName: displayName, Config: u.Config}+ return postable.ToReceiver()+}++const testReceiverName = "test-receiver"++// ToReceiver builds a throwaway receiver for a test send. The name is never+// stored, so it only has to be something the notifier accepts.+func (t *TestableNotificationChannel) ToReceiver() (*Receiver, error) {+ postable := PostableNotificationChannel{DisplayName: testReceiverName, Config: t.Config}+ return postable.ToReceiver()+}+// ════════════════════════════════════════════════════════════════════════// Storage -> API// ════════════════════════════════════════════════════════════════════════@@ -44,10 +60,7 @@ func (c *Channel) toPostableNotificationChannel() (*PostableNotificationChannel,}if total := countNotifierConfigs(receiver); total > 1 {- return nil, errors.NewInvalidInputf(- ErrCodeAlertmanagerChannelInvalid,- "channel %q carries %d notifier configurations; only one per channel is supported", c.DisplayName, total,- )+ return nil, errors.NewInvalidInputf(ErrCodeAlertmanagerChannelInvalid, "channel %q carries %d notifier configurations; only one per channel is supported", c.DisplayName, total)}for _, channelKind := range channelKinds {@@ -67,10 +80,7 @@ func (c *Channel) toPostableNotificationChannel() (*PostableNotificationChannel,}, nil}- return nil, errors.NewNotFoundf(- ErrCodeChannelUnsupportedKind,- "channel %q carries no supported notifier configuration", c.DisplayName,- )+ return nil, errors.NewInvalidInputf(ErrCodeChannelUnsupportedKind, "channel %q carries no supported notifier configuration", c.DisplayName)}// countNotifierConfigs totals every *_configs entry on the receiver, including@@ -115,3 +125,19 @@ func (c *Channel) ToGettableNotificationChannel() (*GettableNotificationChannel,UpdatedAt: c.UpdatedAt,}, nil}++// ToListedNotificationChannel reports an empty Kind for a row whose stored type+// no ChannelKind models, which v1 allowed because it accepted every upstream+// notifier kind. One such row must not fail the whole page.+func (c *Channel) ToListedNotificationChannel() *ListedNotificationChannel {+ channelKind, _ := parseStoredChannelType(c.Type)++ return &ListedNotificationChannel{+ ID: c.ID,+ Name: c.Name,+ DisplayName: c.DisplayName,+ Kind: channelKind,+ CreatedAt: c.CreatedAt,+ UpdatedAt: c.UpdatedAt,+ }+}diff --git a/pkg/types/alertmanagertypes/channellist.go b/pkg/types/alertmanagertypes/channellist.gonew file mode 100644index 0000000000..0d4e30d822--- /dev/null+++ b/pkg/types/alertmanagertypes/channellist.go@@ -0,0 +1,110 @@+package alertmanagertypes++import (+ "slices"+ "unicode/utf8"++ "github.com/SigNoz/signoz/pkg/errors"+ "github.com/SigNoz/signoz/pkg/valuer"+)++const (+ DefaultChannelListLimit = 20+ MaxChannelListLimit = 200+ MaxChannelListQueryLen = 1024+)++var ErrCodeChannelListInvalid = errors.MustNewCode("alertmanager_channel_list_invalid")++// ChannelListSort is a closed enum so callers cannot order by arbitrary columns.+type ChannelListSort struct{ valuer.String }++var (+ ChannelListSortUpdatedAt = ChannelListSort{valuer.NewString("updated_at")}+ ChannelListSortCreatedAt = ChannelListSort{valuer.NewString("created_at")}+ ChannelListSortName = ChannelListSort{valuer.NewString("name")}+)++func (ChannelListSort) Enum() []any {+ return []any{ChannelListSortUpdatedAt, ChannelListSortCreatedAt, ChannelListSortName}+}++func (s ChannelListSort) IsValid() bool {+ return slices.ContainsFunc(s.Enum(), func(v any) bool { return v == s })+}++// ToColumn returns the column the sort orders by. Sorting by name orders by the+// display name, which is what a caller sees, rather than by the DNS1123 name.+func (s ChannelListSort) ToColumn() string {+ if s == ChannelListSortName {+ return "display_name"+ }++ return s.StringValue()+}++type ChannelListOrder struct{ valuer.String }++var (+ ChannelListOrderAsc = ChannelListOrder{valuer.NewString("asc")}+ ChannelListOrderDesc = ChannelListOrder{valuer.NewString("desc")}+)++func (ChannelListOrder) Enum() []any {+ return []any{ChannelListOrderAsc, ChannelListOrderDesc}+}++func (o ChannelListOrder) IsValid() bool {+ return slices.ContainsFunc(o.Enum(), func(v any) bool { return v == o })+}++// ListChannelsParams filters and orders the channel list. Query matches the+// display name case-insensitively.+type ListChannelsParams struct {+ Query string `query:"query" json:"query"`+ Kind ChannelKind `query:"kind" json:"kind"`+ Sort ChannelListSort `query:"sort" json:"sort"`+ Order ChannelListOrder `query:"order" json:"order"`+ Limit int `query:"limit" json:"limit"`+ Offset int `query:"offset" json:"offset"`+}++func (p *ListChannelsParams) Validate() error {+ if n := utf8.RuneCountInString(p.Query); n > MaxChannelListQueryLen {+ return errors.NewInvalidInputf(ErrCodeChannelListInvalid, "query cannot be longer than %d characters, got %d", MaxChannelListQueryLen, n)+ }++ if !p.Kind.IsZero() && !p.Kind.IsValid() {+ return ErrUnsupportedChannelKind(p.Kind.StringValue())+ }++ if !p.Sort.IsZero() && !p.Sort.IsValid() {+ return errors.NewInvalidInputf(ErrCodeChannelListInvalid, "invalid sort %q — expected one of: %s", p.Sort, formatAllowedValues(ChannelListSort{}.Enum()))+ }++ if !p.Order.IsZero() && !p.Order.IsValid() {+ return errors.NewInvalidInputf(ErrCodeChannelListInvalid, "invalid order %q — expected one of: %s", p.Order, formatAllowedValues(ChannelListOrder{}.Enum()))+ }++ if p.Sort.IsZero() {+ p.Sort = ChannelListSortUpdatedAt+ }++ if p.Order.IsZero() {+ p.Order = ChannelListOrderDesc+ }++ if p.Limit == 0 {+ p.Limit = DefaultChannelListLimit+ } else if p.Limit < 0 {+ return errors.NewInvalidInputf(ErrCodeChannelListInvalid, "invalid limit %d — must be a positive integer", p.Limit)+ } else if p.Limit > MaxChannelListLimit {+ p.Limit = MaxChannelListLimit+ }++ if p.Offset < 0 {+ return errors.NewInvalidInputf(ErrCodeChannelListInvalid, "invalid offset %d — must be a non-negative integer", p.Offset)+ }++ return nil+}diff --git a/pkg/types/alertmanagertypes/channellist_test.go b/pkg/types/alertmanagertypes/channellist_test.gonew file mode 100644index 0000000000..81d345fb43--- /dev/null+++ b/pkg/types/alertmanagertypes/channellist_test.go@@ -0,0 +1,75 @@+package alertmanagertypes++import (+ "strings"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestListChannelsParamsValidateBoundsTheLimit(t *testing.T) {+ omitted := &ListChannelsParams{}+ require.NoError(t, omitted.Validate())+ assert.Equal(t, DefaultChannelListLimit, omitted.Limit)++ beyondTheMaximum := &ListChannelsParams{Limit: MaxChannelListLimit + 1}+ require.NoError(t, beyondTheMaximum.Validate())+ assert.Equal(t, MaxChannelListLimit, beyondTheMaximum.Limit)+}++// Sorting by name orders by the display name, because the DNS1123 name is a slug+// a caller never sees.+func TestChannelListSortToColumn(t *testing.T) {+ assert.Equal(t, "display_name", ChannelListSortName.ToColumn())+ assert.Equal(t, "updated_at", ChannelListSortUpdatedAt.ToColumn())+ assert.Equal(t, "created_at", ChannelListSortCreatedAt.ToColumn())+}++func TestListChannelsParamsValidateKeepsAnExplicitSortAndOrder(t *testing.T) {+ params := &ListChannelsParams{Sort: ChannelListSortName, Order: ChannelListOrderAsc}+ require.NoError(t, params.Validate())++ assert.Equal(t, ChannelListSortName, params.Sort)+ assert.Equal(t, ChannelListOrderAsc, params.Order)+}++func TestListChannelsParamsValidateRejectsALongQuery(t *testing.T) {+ params := ListChannelsParams{Query: strings.Repeat("x", MaxChannelListQueryLen+1)}+ assert.Error(t, params.Validate())+}++// v1 accepted every upstream notifier kind, so rows this API does not model are+// possible until they are migrated. One of them must not fail the whole list.+func TestChannelToListedChannelLeavesUnmodelledKindsEmpty(t *testing.T) {+ channel := Channel{+ DisplayName: "tg",+ Name: "tg",+ Type: "telegram",+ Data: `{"name":"tg","telegram_configs":[{"chat_id":1}]}`,+ }++ listed := channel.ToListedNotificationChannel()+ assert.Equal(t, "tg", listed.Name)+ assert.True(t, listed.Kind.IsZero())+}++// msteams is the only kind whose stored Channel.Type differs from the api kind,+// so ToStoredType has to agree with the type the write path derives.+func TestChannelKindMSTeamsIsStoredAsMSTeamsV2(t *testing.T) {+ assert.Equal(t, "msteamsv2", ChannelKindMSTeams.ToStoredType())++ postable := PostableNotificationChannel{+ Name: "channel",+ DisplayName: "channel",+ Config: ChannelConfig{Kind: ChannelKindMSTeams, Spec: &ChannelMSTeamsConfig{WebhookURL: "https://a"}},+ }++ receiver, err := postable.ToReceiver()+ require.NoError(t, err)++ channel, err := NewChannelFromReceiverWithName(receiver, postable.Name, "org-1")+ require.NoError(t, err)++ assert.Equal(t, "msteamsv2", channel.Type)+}diff --git a/pkg/types/alertmanagertypes/config.go b/pkg/types/alertmanagertypes/config.goindex 8ee6c67312..2d2ed1f481 100644--- a/pkg/types/alertmanagertypes/config.go+++ b/pkg/types/alertmanagertypes/config.go@@ -604,8 +604,9 @@ type ConfigStore interface {// DeleteChannelByID deletes a channel.DeleteChannelByID(context.Context, string, valuer.UUID, ...StoreOption) error- // ListChannels returns the list of channels.- ListChannels(context.Context, string) ([]*Channel, error)+ // Nil params lists every one of them in no particular order, with the+ // total equal to the number returned.+ ListChannels(context.Context, string, *ListChannelsParams) ([]*Channel, int64, error)// ListAllChannels returns the list of channels for all organizations.ListAllChannels(context.Context) ([]*Channel, error)diff --git a/tests/integration/tests/alertmanager/04_notification_channels_v2.py b/tests/integration/tests/alertmanager/04_notification_channels_v2.pyindex 94e558389f..bb5fe11468 100644--- a/tests/integration/tests/alertmanager/04_notification_channels_v2.py+++ b/tests/integration/tests/alertmanager/04_notification_channels_v2.py@@ -10,7 +10,6 @@ from fixtures import typesfrom fixtures.auth import (USER_ADMIN_EMAIL,USER_ADMIN_PASSWORD,- create_active_user,)TIMEOUT = 10@@ -436,3 +435,328 @@ def test_create_echoes_an_empty_value_on_a_field_with_no_default(assert created["config"]["spec"]["severity"] == ""assert created["config"]["spec"]["class"] == ""+++def test_notification_channel_v2_lifecycle( # pylint: disable=too-many-statements+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ cleanup_notification_channels: list[str],+) -> None:+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ token_hex = uuid.uuid4().hex[:8]++ # ── stage 1: create one channel per kind, oldest first ───────────────────+ ids: dict[str, str] = {}+ for label, display_name, kind, spec in [+ ("alpha", f"Alpha Overview {token_hex}", "slack", {"apiUrl": "https://hooks.slack.test/services/T/B/SECRET", "channel": "#alerts"}),+ ("beta", f"Beta Escalation {token_hex}", "msteams", {"webhookUrl": "https://teams.test/webhook/abc"}),+ ("gamma", f"Gamma Overview {token_hex}", "webhook", {"url": "https://webhook.test/hook"}),+ ]:+ response = requests.post(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ json={"name": f"v2-list-{label}-{token_hex}", "displayName": display_name, "config": {"kind": kind, "spec": spec}},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text+ ids[label] = response.json()["data"]["id"]+ cleanup_notification_channels.append(ids[label])++ # ── stage 2: list ─────────────────────────────────────────────────────────+ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": token_hex},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ listed = response.json()["data"]+ assert listed["total"] == 3+ assert {channel["kind"] for channel in listed["channels"]} == {"slack", "msteams", "webhook"}+ assert all("config" not in channel for channel in listed["channels"])+ assert "SECRET" not in response.text+ assert [channel["displayName"] for channel in listed["channels"]] == [+ f"Gamma Overview {token_hex}",+ f"Beta Escalation {token_hex}",+ f"Alpha Overview {token_hex}",+ ]++ # ── stage 3: update ──────────────────────────────────────────────────────+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids['alpha']}"),+ json={"config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/Z", "channel": "#incidents"}}},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ updated = response.json()["data"]+ assert updated["name"] == f"v2-list-alpha-{token_hex}"+ assert updated["displayName"] == f"Alpha Overview {token_hex}"+ assert updated["config"]["spec"]["channel"] == "#incidents"++ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": token_hex},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ assert [channel["displayName"] for channel in response.json()["data"]["channels"]] == [+ f"Alpha Overview {token_hex}",+ f"Gamma Overview {token_hex}",+ f"Beta Escalation {token_hex}",+ ]++ # ── stage 4: search by display name ───────────────────────────────────────+ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": f"overview {token_hex}"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ listed = response.json()["data"]+ assert listed["total"] == 2+ assert {channel["displayName"] for channel in listed["channels"]} == {f"Alpha Overview {token_hex}", f"Gamma Overview {token_hex}"}++ # ── stage 5: filter by kind ───────────────────────────────────────────────+ # msteams is stored as msteamsv2, so the filter has to translate the api kind+ # rather than match Channel.Type directly.+ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": token_hex, "kind": "msteams"},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ listed = response.json()["data"]+ assert listed["total"] == 1+ assert listed["channels"][0]["kind"] == "msteams"++ # ── stage 6: page ─────────────────────────────────────────────────────────+ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": token_hex, "limit": 2},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ listed = response.json()["data"]+ assert listed["total"] == 3+ assert len(listed["channels"]) == 2++ # ── stage 7: page past the last match ─────────────────────────────────────+ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": token_hex, "offset": 10},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ listed = response.json()["data"]+ assert listed["channels"] == []+ assert listed["total"] == 3++ # ── stage 8: get by id ────────────────────────────────────────────────────+ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids['alpha']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ fetched = response.json()["data"]+ assert fetched["name"] == f"v2-list-alpha-{token_hex}"+ assert fetched["displayName"] == f"Alpha Overview {token_hex}"+ assert fetched["config"]["spec"]["apiUrl"] == "https://hooks.slack.test/services/T/B/Z"+ assert fetched["config"]["spec"]["channel"] == "#incidents"++ # ── stage 9: update the kind ──────────────────────────────────────────────+ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids['beta']}"),+ json={"config": {"kind": "webhook", "spec": {"url": "https://webhook.test/hook"}}},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ assert response.json()["data"]["config"]["kind"] == "webhook"++ # ── stage 10: delete ──────────────────────────────────────────────────────+ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids['gamma']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.NO_CONTENT, response.text+ cleanup_notification_channels.remove(ids["gamma"])++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{ids['gamma']}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.NOT_FOUND, response.text++ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": token_hex},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text+ assert response.json()["data"]["total"] == 2+++ "params",+ [+ pytest.param({"sort": "data"}, id="sort_outside_the_enum"),+ pytest.param({"order": "sideways"}, id="order_outside_the_enum"),+ pytest.param({"kind": "telegram"}, id="kind_outside_the_enum"),+ pytest.param({"limit": -1}, id="negative_limit"),+ pytest.param({"offset": -1}, id="negative_offset"),+ ],+)+def test_list_rejects_invalid_params(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ params: dict,+) -> None:+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params=params,+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text+++def test_get_unknown_id(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+) -> None:+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/0199a1b2-c3d4-7000-8000-000000000000"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.NOT_FOUND, response.text+++def test_list_and_get_a_v1_channel_of_an_unmodelled_kind(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ cleanup_notification_channels: list[str],+) -> None:+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ name = f"v1-telegram-{uuid.uuid4().hex[:8]}"++ # telegram is a kind v1 accepts and v2 does not model, so it can only be+ # written through v1.+ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v1/channels"),+ json={"name": name, "telegram_configs": [{"chat": 12345, "token": "telegram-bot-token"}]},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text+ channel_id = response.json()["data"]["id"]+ cleanup_notification_channels.append(channel_id)++ response = requests.get(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ params={"query": name},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.OK, response.text++ listed = response.json()["data"]+ assert listed["total"] == 1+ assert listed["channels"][0]["displayName"] == name+ assert listed["channels"][0]["kind"] == ""++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text+++ "body",+ [+ pytest.param({"name": "renamed", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}}, id="name_in_body"),+ pytest.param({"displayName": "Renamed", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}}, id="display_name_in_body"),+ pytest.param({"config": {"kind": "slack", "spec": {}}}, id="spec_missing_required_field"),+ pytest.param({}, id="no_config"),+ ],+)+def test_update_rejects_invalid_bodies( # pylint: disable=too-many-arguments,too-many-positional-arguments+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ cleanup_notification_channels: list[str],+ body: dict,+) -> None:+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)+ name = f"v2-badupdate-{uuid.uuid4().hex[:8]}"++ response = requests.post(+ signoz.self.host_configs["8080"].get(V2_BASE_URL),+ json={"name": name, "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}},+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.CREATED, response.text+ channel_id = response.json()["data"]["id"]+ cleanup_notification_channels.append(channel_id)++ response = requests.put(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/{channel_id}"),+ json=body,+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text+++ "body",+ [+ pytest.param({"name": "test-send", "config": {"kind": "slack", "spec": {"apiUrl": "https://hooks.slack.test/services/T/B/X"}}}, id="name_in_body"),+ pytest.param({"config": {"kind": "slack", "spec": {}}}, id="spec_missing_required_field"),+ pytest.param({"config": {"kind": "telegram", "spec": {"chatId": 1}}}, id="unmodelled_kind"),+ pytest.param({}, id="no_config"),+ ],+)+def test_test_rejects_invalid_bodies(+ signoz: types.SigNoz,+ create_user_admin: None, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+ body: dict,+) -> None:+ token = get_token(USER_ADMIN_EMAIL, USER_ADMIN_PASSWORD)++ response = requests.post(+ signoz.self.host_configs["8080"].get(f"{V2_BASE_URL}/test"),+ json=body,+ headers={"Authorization": f"Bearer {token}"},+ timeout=TIMEOUT,+ )+ assert response.status_code == HTTPStatus.BAD_REQUEST, response.text