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(gateway): add first-class ingestion limit APIs (#12625)
Vikrant Guptab3b547f34a77
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex cf3029e4f2..ed8301f9ff 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -4090,6 +4090,18 @@ components:nullable: truetype: objecttype: object+ GatewaytypesDeprecatedPostableIngestionKeyLimit:+ properties:+ config:+ $ref: '#/components/schemas/GatewaytypesLimitConfig'+ signal:+ type: string+ tags:+ items:+ type: string+ nullable: true+ type: array+ type: objectGatewaytypesGettableCreatedIngestionKey:properties:id:@@ -4233,6 +4245,8 @@ components:properties:config:$ref: '#/components/schemas/GatewaytypesLimitConfig'+ keyId:+ type: stringsignal:type: stringtags:@@ -4240,6 +4254,8 @@ components:type: stringnullable: truetype: array+ required:+ - keyIdtype: objectGatewaytypesUpdatableIngestionKeyLimit:properties:@@ -16161,6 +16177,63 @@ paths:summary: Delete ingestion key for workspacetags:- gateway+ get:+ deprecated: false+ description: This endpoint returns an ingestion key for the workspace+ operationId: GetIngestionKey+ parameters:+ - in: path+ name: keyId+ required: true+ schema:+ type: string+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/GatewaytypesIngestionKey'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "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:+ - EDITOR+ - tokenizer:+ - EDITOR+ summary: Get ingestion key for workspace+ tags:+ - gatewaypatch:deprecated: falsedescription: This endpoint updates an ingestion key for the workspace@@ -16206,8 +16279,68 @@ paths:tags:- gateway/api/v2/gateway/ingestion_keys/{keyId}/limits:- post:+ get:deprecated: false+ description: This endpoint returns the ingestion limits for an ingestion key+ operationId: GetIngestionKeyLimits+ parameters:+ - in: path+ name: keyId+ required: true+ schema:+ type: string+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ items:+ $ref: '#/components/schemas/GatewaytypesLimit'+ nullable: true+ type: array+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "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:+ - EDITOR+ - tokenizer:+ - EDITOR+ summary: Get limits for the ingestion key+ tags:+ - gateway+ post:+ deprecated: truedescription: This endpoint creates an ingestion key limitoperationId: CreateIngestionKeyLimitparameters:@@ -16220,7 +16353,7 @@ paths:content:application/json:schema:- $ref: '#/components/schemas/GatewaytypesPostableIngestionKeyLimit'+ $ref: '#/components/schemas/GatewaytypesDeprecatedPostableIngestionKeyLimit'responses:"201":content:@@ -16264,7 +16397,7 @@ paths:- gateway/api/v2/gateway/ingestion_keys/limits/{limitId}:delete:- deprecated: false+ deprecated: truedescription: This endpoint deletes an ingestion key limitoperationId: DeleteIngestionKeyLimitparameters:@@ -16303,7 +16436,7 @@ paths:tags:- gatewaypatch:- deprecated: false+ deprecated: truedescription: This endpoint updates an ingestion key limitoperationId: UpdateIngestionKeyLimitparameters:@@ -16406,6 +16539,205 @@ paths:summary: Search ingestion keys for workspacetags:- gateway+ /api/v2/gateway/ingestion_limits:+ post:+ deprecated: false+ description: This endpoint creates an ingestion limit for the ingestion key+ referenced by keyId+ operationId: CreateIngestionLimit+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/GatewaytypesPostableIngestionKeyLimit'+ responses:+ "201":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/TypesIdentifiable'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: Created+ "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:+ - EDITOR+ - tokenizer:+ - EDITOR+ summary: Create ingestion limit+ tags:+ - gateway+ /api/v2/gateway/ingestion_limits/{limitId}:+ delete:+ deprecated: false+ description: This endpoint deletes an ingestion limit+ operationId: DeleteIngestionLimit+ parameters:+ - in: path+ name: limitId+ required: true+ schema:+ type: string+ responses:+ "204":+ description: No Content+ "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:+ - EDITOR+ - tokenizer:+ - EDITOR+ summary: Delete ingestion limit+ tags:+ - gateway+ get:+ deprecated: false+ description: This endpoint returns an ingestion limit+ operationId: GetIngestionLimit+ parameters:+ - in: path+ name: limitId+ required: true+ schema:+ type: string+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/GatewaytypesLimit'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "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:+ - EDITOR+ - tokenizer:+ - EDITOR+ summary: Get ingestion limit+ tags:+ - gateway+ patch:+ deprecated: false+ description: This endpoint updates an ingestion limit+ operationId: UpdateIngestionLimit+ parameters:+ - in: path+ name: limitId+ required: true+ schema:+ type: string+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/GatewaytypesUpdatableIngestionKeyLimit'+ responses:+ "204":+ description: No Content+ "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:+ - EDITOR+ - tokenizer:+ - EDITOR+ summary: Update ingestion limit+ tags:+ - gateway/api/v2/healthz:get:operationId: Healthzdiff --git a/ee/gateway/httpgateway/provider.go b/ee/gateway/httpgateway/provider.goindex 944db4046e..5b72598d19 100644--- a/ee/gateway/httpgateway/provider.go+++ b/ee/gateway/httpgateway/provider.go@@ -108,6 +108,20 @@ func (provider *Provider) SearchIngestionKeysByName(ctx context.Context, orgID v}, nil}+func (provider *Provider) GetIngestionKey(ctx context.Context, orgID valuer.UUID, keyID string) (*gatewaytypes.IngestionKey, error) {+ responseBody, err := provider.do(ctx, orgID, http.MethodGet, "/v1/workspaces/me/keys/"+keyID, nil, nil)+ if err != nil {+ return nil, err+ }++ var ingestionKey gatewaytypes.IngestionKey+ if err := json.Unmarshal([]byte(gjson.GetBytes(responseBody, "data").String()), &ingestionKey); err != nil {+ return nil, err+ }++ return &ingestionKey, nil+}+func (provider *Provider) CreateIngestionKey(ctx context.Context, orgID valuer.UUID, name string, tags []string, expiresAt time.Time) (*gatewaytypes.GettableCreatedIngestionKey, error) {requestBody := gatewaytypes.PostableIngestionKey{Name: name,@@ -161,7 +175,7 @@ func (provider *Provider) DeleteIngestionKey(ctx context.Context, orgID valuer.U}func (provider *Provider) CreateIngestionKeyLimit(ctx context.Context, orgID valuer.UUID, keyID string, signal string, limitConfig gatewaytypes.LimitConfig, tags []string) (*gatewaytypes.GettableCreatedIngestionKeyLimit, error) {- requestBody := gatewaytypes.PostableIngestionKeyLimit{+ requestBody := gatewaytypes.DeprecatedPostableIngestionKeyLimit{Signal: signal,Config: limitConfig,Tags: tags,@@ -184,6 +198,34 @@ func (provider *Provider) CreateIngestionKeyLimit(ctx context.Context, orgID valreturn &createdIngestionKeyLimitResponse, nil}+func (provider *Provider) GetIngestionKeyLimit(ctx context.Context, orgID valuer.UUID, limitID string) (*gatewaytypes.Limit, error) {+ responseBody, err := provider.do(ctx, orgID, http.MethodGet, "/v1/workspaces/me/limits/"+limitID, nil, nil)+ if err != nil {+ return nil, err+ }++ var limit gatewaytypes.Limit+ if err := json.Unmarshal([]byte(gjson.GetBytes(responseBody, "data").String()), &limit); err != nil {+ return nil, err+ }++ return &limit, nil+}++func (provider *Provider) GetIngestionKeyLimits(ctx context.Context, orgID valuer.UUID, keyID string) ([]gatewaytypes.Limit, error) {+ responseBody, err := provider.do(ctx, orgID, http.MethodGet, "/v1/workspaces/me/keys/"+keyID+"/limits", nil, nil)+ if err != nil {+ return nil, err+ }++ var limits []gatewaytypes.Limit+ if err := json.Unmarshal([]byte(gjson.GetBytes(responseBody, "data").String()), &limits); err != nil {+ return nil, err+ }++ return limits, nil+}+func (provider *Provider) UpdateIngestionKeyLimit(ctx context.Context, orgID valuer.UUID, limitID string, limitConfig gatewaytypes.LimitConfig, tags []string) error {requestBody := gatewaytypes.UpdatableIngestionKeyLimit{Config: limitConfig,diff --git a/frontend/src/api/generated/services/gateway/index.ts b/frontend/src/api/generated/services/gateway/index.tsindex fdcb3c472e..f377455982 100644--- a/frontend/src/api/generated/services/gateway/index.ts+++ b/frontend/src/api/generated/services/gateway/index.ts@@ -21,18 +21,28 @@ import type {CreateIngestionKey201,CreateIngestionKeyLimit201,CreateIngestionKeyLimitPathParameters,+ CreateIngestionLimit201,DeleteIngestionKeyLimitPathParameters,DeleteIngestionKeyPathParameters,+ DeleteIngestionLimitPathParameters,+ GatewaytypesDeprecatedPostableIngestionKeyLimitDTO,GatewaytypesPostableIngestionKeyDTO,GatewaytypesPostableIngestionKeyLimitDTO,GatewaytypesUpdatableIngestionKeyLimitDTO,+ GetIngestionKey200,+ GetIngestionKeyLimits200,+ GetIngestionKeyLimitsPathParameters,+ GetIngestionKeyPathParameters,GetIngestionKeys200,GetIngestionKeysParams,+ GetIngestionLimit200,+ GetIngestionLimitPathParameters,RenderErrorResponseDTO,SearchIngestionKeys200,SearchIngestionKeysParams,UpdateIngestionKeyLimitPathParameters,UpdateIngestionKeyPathParameters,+ UpdateIngestionLimitPathParameters,} from '../sigNoz.schemas';import { GeneratedAPIInstance } from '../../../generatedAPIInstance';@@ -300,6 +310,108 @@ export const useDeleteIngestionKey = <> => {return useMutation(getDeleteIngestionKeyMutationOptions(options));};+/**+ * This endpoint returns an ingestion key for the workspace+ * @summary Get ingestion key for workspace+ */+export const getIngestionKey = (+ { keyId }: GetIngestionKeyPathParameters,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<GetIngestionKey200>({+ url: `/api/v2/gateway/ingestion_keys/${keyId}`,+ method: 'GET',+ signal,+ });+};++export const getGetIngestionKeyQueryKey = ({+ keyId,+}: GetIngestionKeyPathParameters) => {+ return [`/api/v2/gateway/ingestion_keys/${keyId}`] as const;+};++export const getGetIngestionKeyQueryOptions = <+ TData = Awaited<ReturnType<typeof getIngestionKey>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { keyId }: GetIngestionKeyPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionKey>>,+ TError,+ TData+ >;+ },+) => {+ const { query: queryOptions } = options ?? {};++ const queryKey =+ queryOptions?.queryKey ?? getGetIngestionKeyQueryKey({ keyId });++ const queryFn: QueryFunction<Awaited<ReturnType<typeof getIngestionKey>>> = ({+ signal,+ }) => getIngestionKey({ keyId }, signal);++ return {+ queryKey,+ queryFn,+ enabled: !!keyId,+ ...queryOptions,+ } as UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionKey>>,+ TError,+ TData+ > & { queryKey: QueryKey };+};++export type GetIngestionKeyQueryResult = NonNullable<+ Awaited<ReturnType<typeof getIngestionKey>>+>;+export type GetIngestionKeyQueryError = ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Get ingestion key for workspace+ */++export function useGetIngestionKey<+ TData = Awaited<ReturnType<typeof getIngestionKey>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { keyId }: GetIngestionKeyPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionKey>>,+ TError,+ TData+ >;+ },+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {+ const queryOptions = getGetIngestionKeyQueryOptions({ keyId }, options);++ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {+ queryKey: QueryKey;+ };++ return { ...query, queryKey: queryOptions.queryKey };+}++/**+ * @summary Get ingestion key for workspace+ */+export const invalidateGetIngestionKey = async (+ queryClient: QueryClient,+ { keyId }: GetIngestionKeyPathParameters,+ options?: InvalidateOptions,+): Promise<QueryClient> => {+ await queryClient.invalidateQueries(+ { queryKey: getGetIngestionKeyQueryKey({ keyId }) },+ options,+ );++ return queryClient;+};+/*** This endpoint updates an ingestion key for the workspace* @summary Update ingestion key for workspace@@ -399,20 +511,123 @@ export const useUpdateIngestionKey = <> => {return useMutation(getUpdateIngestionKeyMutationOptions(options));};+/**+ * This endpoint returns the ingestion limits for an ingestion key+ * @summary Get limits for the ingestion key+ */+export const getIngestionKeyLimits = (+ { keyId }: GetIngestionKeyLimitsPathParameters,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<GetIngestionKeyLimits200>({+ url: `/api/v2/gateway/ingestion_keys/${keyId}/limits`,+ method: 'GET',+ signal,+ });+};++export const getGetIngestionKeyLimitsQueryKey = ({+ keyId,+}: GetIngestionKeyLimitsPathParameters) => {+ return [`/api/v2/gateway/ingestion_keys/${keyId}/limits`] as const;+};++export const getGetIngestionKeyLimitsQueryOptions = <+ TData = Awaited<ReturnType<typeof getIngestionKeyLimits>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { keyId }: GetIngestionKeyLimitsPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionKeyLimits>>,+ TError,+ TData+ >;+ },+) => {+ const { query: queryOptions } = options ?? {};++ const queryKey =+ queryOptions?.queryKey ?? getGetIngestionKeyLimitsQueryKey({ keyId });++ const queryFn: QueryFunction<+ Awaited<ReturnType<typeof getIngestionKeyLimits>>+ > = ({ signal }) => getIngestionKeyLimits({ keyId }, signal);++ return {+ queryKey,+ queryFn,+ enabled: !!keyId,+ ...queryOptions,+ } as UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionKeyLimits>>,+ TError,+ TData+ > & { queryKey: QueryKey };+};++export type GetIngestionKeyLimitsQueryResult = NonNullable<+ Awaited<ReturnType<typeof getIngestionKeyLimits>>+>;+export type GetIngestionKeyLimitsQueryError = ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Get limits for the ingestion key+ */++export function useGetIngestionKeyLimits<+ TData = Awaited<ReturnType<typeof getIngestionKeyLimits>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { keyId }: GetIngestionKeyLimitsPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionKeyLimits>>,+ TError,+ TData+ >;+ },+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {+ const queryOptions = getGetIngestionKeyLimitsQueryOptions({ keyId }, options);++ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {+ queryKey: QueryKey;+ };++ return { ...query, queryKey: queryOptions.queryKey };+}++/**+ * @summary Get limits for the ingestion key+ */+export const invalidateGetIngestionKeyLimits = async (+ queryClient: QueryClient,+ { keyId }: GetIngestionKeyLimitsPathParameters,+ options?: InvalidateOptions,+): Promise<QueryClient> => {+ await queryClient.invalidateQueries(+ { queryKey: getGetIngestionKeyLimitsQueryKey({ keyId }) },+ options,+ );++ return queryClient;+};+/*** This endpoint creates an ingestion key limit+ * @deprecated* @summary Create limit for the ingestion key*/export const createIngestionKeyLimit = ({ keyId }: CreateIngestionKeyLimitPathParameters,- gatewaytypesPostableIngestionKeyLimitDTO?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>,+ gatewaytypesDeprecatedPostableIngestionKeyLimitDTO?: BodyType<GatewaytypesDeprecatedPostableIngestionKeyLimitDTO>,signal?: AbortSignal,) => {return GeneratedAPIInstance<CreateIngestionKeyLimit201>({url: `/api/v2/gateway/ingestion_keys/${keyId}/limits`,method: 'POST',headers: { 'Content-Type': 'application/json' },- data: gatewaytypesPostableIngestionKeyLimitDTO,+ data: gatewaytypesDeprecatedPostableIngestionKeyLimitDTO,signal,});};@@ -426,7 +641,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <TError,{pathParams: CreateIngestionKeyLimitPathParameters;- data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;+ data?: BodyType<GatewaytypesDeprecatedPostableIngestionKeyLimitDTO>;},TContext>;@@ -435,7 +650,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <TError,{pathParams: CreateIngestionKeyLimitPathParameters;- data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;+ data?: BodyType<GatewaytypesDeprecatedPostableIngestionKeyLimitDTO>;},TContext> => {@@ -452,7 +667,7 @@ export const getCreateIngestionKeyLimitMutationOptions = <Awaited<ReturnType<typeof createIngestionKeyLimit>>,{pathParams: CreateIngestionKeyLimitPathParameters;- data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;+ data?: BodyType<GatewaytypesDeprecatedPostableIngestionKeyLimitDTO>;}> = (props) => {const { pathParams, data } = props ?? {};@@ -467,12 +682,13 @@ export type CreateIngestionKeyLimitMutationResult = NonNullable<Awaited<ReturnType<typeof createIngestionKeyLimit>>>;export type CreateIngestionKeyLimitMutationBody =- | BodyType<GatewaytypesPostableIngestionKeyLimitDTO>+ | BodyType<GatewaytypesDeprecatedPostableIngestionKeyLimitDTO>| undefined;export type CreateIngestionKeyLimitMutationError =ErrorType<RenderErrorResponseDTO>;/**+ * @deprecated* @summary Create limit for the ingestion key*/export const useCreateIngestionKeyLimit = <@@ -484,7 +700,7 @@ export const useCreateIngestionKeyLimit = <TError,{pathParams: CreateIngestionKeyLimitPathParameters;- data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;+ data?: BodyType<GatewaytypesDeprecatedPostableIngestionKeyLimitDTO>;},TContext>;@@ -493,7 +709,7 @@ export const useCreateIngestionKeyLimit = <TError,{pathParams: CreateIngestionKeyLimitPathParameters;- data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>;+ data?: BodyType<GatewaytypesDeprecatedPostableIngestionKeyLimitDTO>;},TContext> => {@@ -501,6 +717,7 @@ export const useCreateIngestionKeyLimit = <};/*** This endpoint deletes an ingestion key limit+ * @deprecated* @summary Delete limit for the ingestion key*/export const deleteIngestionKeyLimit = (@@ -559,6 +776,7 @@ export type DeleteIngestionKeyLimitMutationError =ErrorType<RenderErrorResponseDTO>;/**+ * @deprecated* @summary Delete limit for the ingestion key*/export const useDeleteIngestionKeyLimit = <@@ -581,6 +799,7 @@ export const useDeleteIngestionKeyLimit = <};/*** This endpoint updates an ingestion key limit+ * @deprecated* @summary Update limit for the ingestion key*/export const updateIngestionKeyLimit = (@@ -653,6 +872,7 @@ export type UpdateIngestionKeyLimitMutationError =ErrorType<RenderErrorResponseDTO>;/**+ * @deprecated* @summary Update limit for the ingestion key*/export const useUpdateIngestionKeyLimit = <@@ -779,3 +999,370 @@ export const invalidateSearchIngestionKeys = async (return queryClient;};++/**+ * This endpoint creates an ingestion limit for the ingestion key referenced by keyId+ * @summary Create ingestion limit+ */+export const createIngestionLimit = (+ gatewaytypesPostableIngestionKeyLimitDTO?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO>,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<CreateIngestionLimit201>({+ url: `/api/v2/gateway/ingestion_limits`,+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ data: gatewaytypesPostableIngestionKeyLimitDTO,+ signal,+ });+};++export const getCreateIngestionLimitMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof createIngestionLimit>>,+ TError,+ { data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO> },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof createIngestionLimit>>,+ TError,+ { data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO> },+ TContext+> => {+ const mutationKey = ['createIngestionLimit'];+ 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 createIngestionLimit>>,+ { data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO> }+ > = (props) => {+ const { data } = props ?? {};++ return createIngestionLimit(data);+ };++ return { mutationFn, ...mutationOptions };+};++export type CreateIngestionLimitMutationResult = NonNullable<+ Awaited<ReturnType<typeof createIngestionLimit>>+>;+export type CreateIngestionLimitMutationBody =+ | BodyType<GatewaytypesPostableIngestionKeyLimitDTO>+ | undefined;+export type CreateIngestionLimitMutationError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Create ingestion limit+ */+export const useCreateIngestionLimit = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof createIngestionLimit>>,+ TError,+ { data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO> },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof createIngestionLimit>>,+ TError,+ { data?: BodyType<GatewaytypesPostableIngestionKeyLimitDTO> },+ TContext+> => {+ return useMutation(getCreateIngestionLimitMutationOptions(options));+};+/**+ * This endpoint deletes an ingestion limit+ * @summary Delete ingestion limit+ */+export const deleteIngestionLimit = (+ { limitId }: DeleteIngestionLimitPathParameters,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<void>({+ url: `/api/v2/gateway/ingestion_limits/${limitId}`,+ method: 'DELETE',+ signal,+ });+};++export const getDeleteIngestionLimitMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof deleteIngestionLimit>>,+ TError,+ { pathParams: DeleteIngestionLimitPathParameters },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof deleteIngestionLimit>>,+ TError,+ { pathParams: DeleteIngestionLimitPathParameters },+ TContext+> => {+ const mutationKey = ['deleteIngestionLimit'];+ 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 deleteIngestionLimit>>,+ { pathParams: DeleteIngestionLimitPathParameters }+ > = (props) => {+ const { pathParams } = props ?? {};++ return deleteIngestionLimit(pathParams);+ };++ return { mutationFn, ...mutationOptions };+};++export type DeleteIngestionLimitMutationResult = NonNullable<+ Awaited<ReturnType<typeof deleteIngestionLimit>>+>;++export type DeleteIngestionLimitMutationError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Delete ingestion limit+ */+export const useDeleteIngestionLimit = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof deleteIngestionLimit>>,+ TError,+ { pathParams: DeleteIngestionLimitPathParameters },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof deleteIngestionLimit>>,+ TError,+ { pathParams: DeleteIngestionLimitPathParameters },+ TContext+> => {+ return useMutation(getDeleteIngestionLimitMutationOptions(options));+};+/**+ * This endpoint returns an ingestion limit+ * @summary Get ingestion limit+ */+export const getIngestionLimit = (+ { limitId }: GetIngestionLimitPathParameters,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<GetIngestionLimit200>({+ url: `/api/v2/gateway/ingestion_limits/${limitId}`,+ method: 'GET',+ signal,+ });+};++export const getGetIngestionLimitQueryKey = ({+ limitId,+}: GetIngestionLimitPathParameters) => {+ return [`/api/v2/gateway/ingestion_limits/${limitId}`] as const;+};++export const getGetIngestionLimitQueryOptions = <+ TData = Awaited<ReturnType<typeof getIngestionLimit>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { limitId }: GetIngestionLimitPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionLimit>>,+ TError,+ TData+ >;+ },+) => {+ const { query: queryOptions } = options ?? {};++ const queryKey =+ queryOptions?.queryKey ?? getGetIngestionLimitQueryKey({ limitId });++ const queryFn: QueryFunction<+ Awaited<ReturnType<typeof getIngestionLimit>>+ > = ({ signal }) => getIngestionLimit({ limitId }, signal);++ return {+ queryKey,+ queryFn,+ enabled: !!limitId,+ ...queryOptions,+ } as UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionLimit>>,+ TError,+ TData+ > & { queryKey: QueryKey };+};++export type GetIngestionLimitQueryResult = NonNullable<+ Awaited<ReturnType<typeof getIngestionLimit>>+>;+export type GetIngestionLimitQueryError = ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Get ingestion limit+ */++export function useGetIngestionLimit<+ TData = Awaited<ReturnType<typeof getIngestionLimit>>,+ TError = ErrorType<RenderErrorResponseDTO>,+>(+ { limitId }: GetIngestionLimitPathParameters,+ options?: {+ query?: UseQueryOptions<+ Awaited<ReturnType<typeof getIngestionLimit>>,+ TError,+ TData+ >;+ },+): UseQueryResult<TData, TError> & { queryKey: QueryKey } {+ const queryOptions = getGetIngestionLimitQueryOptions({ limitId }, options);++ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {+ queryKey: QueryKey;+ };++ return { ...query, queryKey: queryOptions.queryKey };+}++/**+ * @summary Get ingestion limit+ */+export const invalidateGetIngestionLimit = async (+ queryClient: QueryClient,+ { limitId }: GetIngestionLimitPathParameters,+ options?: InvalidateOptions,+): Promise<QueryClient> => {+ await queryClient.invalidateQueries(+ { queryKey: getGetIngestionLimitQueryKey({ limitId }) },+ options,+ );++ return queryClient;+};++/**+ * This endpoint updates an ingestion limit+ * @summary Update ingestion limit+ */+export const updateIngestionLimit = (+ { limitId }: UpdateIngestionLimitPathParameters,+ gatewaytypesUpdatableIngestionKeyLimitDTO?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<void>({+ url: `/api/v2/gateway/ingestion_limits/${limitId}`,+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ data: gatewaytypesUpdatableIngestionKeyLimitDTO,+ signal,+ });+};++export const getUpdateIngestionLimitMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof updateIngestionLimit>>,+ TError,+ {+ pathParams: UpdateIngestionLimitPathParameters;+ data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;+ },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof updateIngestionLimit>>,+ TError,+ {+ pathParams: UpdateIngestionLimitPathParameters;+ data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;+ },+ TContext+> => {+ const mutationKey = ['updateIngestionLimit'];+ 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 updateIngestionLimit>>,+ {+ pathParams: UpdateIngestionLimitPathParameters;+ data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;+ }+ > = (props) => {+ const { pathParams, data } = props ?? {};++ return updateIngestionLimit(pathParams, data);+ };++ return { mutationFn, ...mutationOptions };+};++export type UpdateIngestionLimitMutationResult = NonNullable<+ Awaited<ReturnType<typeof updateIngestionLimit>>+>;+export type UpdateIngestionLimitMutationBody =+ | BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>+ | undefined;+export type UpdateIngestionLimitMutationError =+ ErrorType<RenderErrorResponseDTO>;++/**+ * @summary Update ingestion limit+ */+export const useUpdateIngestionLimit = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof updateIngestionLimit>>,+ TError,+ {+ pathParams: UpdateIngestionLimitPathParameters;+ data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;+ },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof updateIngestionLimit>>,+ TError,+ {+ pathParams: UpdateIngestionLimitPathParameters;+ data?: BodyType<GatewaytypesUpdatableIngestionKeyLimitDTO>;+ },+ TContext+> => {+ return useMutation(getUpdateIngestionLimitMutationOptions(options));+};diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex 1a4f8cc295..3ad36b9c2e 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -5493,6 +5493,34 @@ export interface FeaturetypesGettableFeatureDTO {variants?: FeaturetypesGettableFeatureDTOVariants;}+export interface GatewaytypesLimitValueDTO {+ /**+ * @type integer,null+ */+ count?: number | null;+ /**+ * @type integer,null+ */+ size?: number | null;+}++export interface GatewaytypesLimitConfigDTO {+ day?: GatewaytypesLimitValueDTO;+ second?: GatewaytypesLimitValueDTO;+}++export interface GatewaytypesDeprecatedPostableIngestionKeyLimitDTO {+ config?: GatewaytypesLimitConfigDTO;+ /**+ * @type string+ */+ signal?: string;+ /**+ * @type array,null+ */+ tags?: string[] | null;+}+export interface GatewaytypesGettableCreatedIngestionKeyDTO {/*** @type string@@ -5530,22 +5558,6 @@ export interface GatewaytypesPaginationDTO {total?: number;}-export interface GatewaytypesLimitValueDTO {- /**- * @type integer,null- */- count?: number | null;- /**- * @type integer,null- */- size?: number | null;-}--export interface GatewaytypesLimitConfigDTO {- day?: GatewaytypesLimitValueDTO;- second?: GatewaytypesLimitValueDTO;-}-export interface GatewaytypesLimitMetricValueDTO {/*** @type integer@@ -5663,6 +5675,10 @@ export interface GatewaytypesPostableIngestionKeyDTO {export interface GatewaytypesPostableIngestionKeyLimitDTO {config?: GatewaytypesLimitConfigDTO;+ /**+ * @type string+ */+ keyId: string;/*** @type string*/@@ -11940,9 +11956,34 @@ export type CreateIngestionKey201 = {export type DeleteIngestionKeyPathParameters = {keyId: string;};+export type GetIngestionKeyPathParameters = {+ keyId: string;+};+export type GetIngestionKey200 = {+ data: GatewaytypesIngestionKeyDTO;+ /**+ * @type string+ */+ status: string;+};+export type UpdateIngestionKeyPathParameters = {keyId: string;};+export type GetIngestionKeyLimitsPathParameters = {+ keyId: string;+};+export type GetIngestionKeyLimits200 = {+ /**+ * @type array,null+ */+ data: GatewaytypesLimitDTO[] | null;+ /**+ * @type string+ */+ status: string;+};+export type CreateIngestionKeyLimitPathParameters = {keyId: string;};@@ -11986,6 +12027,31 @@ export type SearchIngestionKeys200 = {status: string;};+export type CreateIngestionLimit201 = {+ data: TypesIdentifiableDTO;+ /**+ * @type string+ */+ status: string;+};++export type DeleteIngestionLimitPathParameters = {+ limitId: string;+};+export type GetIngestionLimitPathParameters = {+ limitId: string;+};+export type GetIngestionLimit200 = {+ data: GatewaytypesLimitDTO;+ /**+ * @type string+ */+ status: string;+};++export type UpdateIngestionLimitPathParameters = {+ limitId: string;+};export type Healthz200 = {data: FactoryResponseDTO;/**diff --git a/pkg/apiserver/signozapiserver/gateway.go b/pkg/apiserver/signozapiserver/gateway.goindex d4104df46d..27cf75abe3 100644--- a/pkg/apiserver/signozapiserver/gateway.go+++ b/pkg/apiserver/signozapiserver/gateway.go@@ -97,23 +97,57 @@ func (provider *provider) addGatewayRoutes(router *mux.Router) error {return err}- if err := router.Handle("/api/v2/gateway/ingestion_keys/{keyId}/limits", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.CreateIngestionKeyLimit), handler.OpenAPIDef{+ if err := router.Handle("/api/v2/gateway/ingestion_keys/{keyId}", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.GetIngestionKey), handler.OpenAPIDef{+ ID: "GetIngestionKey",+ Tags: []string{"gateway"},+ Summary: "Get ingestion key for workspace",+ Description: "This endpoint returns an ingestion key for the workspace",+ Request: nil,+ RequestContentType: "",+ Response: new(gatewaytypes.IngestionKey),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),+ })).Methods(http.MethodGet).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/gateway/ingestion_keys/{keyId}/limits", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.DeprecatedCreateIngestionKeyLimit), handler.OpenAPIDef{ID: "CreateIngestionKeyLimit",Tags: []string{"gateway"},Summary: "Create limit for the ingestion key",Description: "This endpoint creates an ingestion key limit",- Request: new(gatewaytypes.PostableIngestionKeyLimit),+ Request: new(gatewaytypes.DeprecatedPostableIngestionKeyLimit),RequestContentType: "application/json",Response: new(gatewaytypes.GettableCreatedIngestionKeyLimit),ResponseContentType: "application/json",SuccessStatusCode: http.StatusCreated,ErrorStatusCodes: []int{},- Deprecated: false,+ Deprecated: true,SecuritySchemes: newSecuritySchemes(types.RoleEditor),})).Methods(http.MethodPost).GetError(); err != nil {return err}+ if err := router.Handle("/api/v2/gateway/ingestion_keys/{keyId}/limits", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.GetIngestionKeyLimits), handler.OpenAPIDef{+ ID: "GetIngestionKeyLimits",+ Tags: []string{"gateway"},+ Summary: "Get limits for the ingestion key",+ Description: "This endpoint returns the ingestion limits for an ingestion key",+ Request: nil,+ RequestContentType: "",+ Response: new([]gatewaytypes.Limit),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),+ })).Methods(http.MethodGet).GetError(); err != nil {+ return err+ }+if err := router.Handle("/api/v2/gateway/ingestion_keys/limits/{limitId}", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.UpdateIngestionKeyLimit), handler.OpenAPIDef{ID: "UpdateIngestionKeyLimit",Tags: []string{"gateway"},@@ -125,7 +159,7 @@ func (provider *provider) addGatewayRoutes(router *mux.Router) error {ResponseContentType: "",SuccessStatusCode: http.StatusNoContent,ErrorStatusCodes: []int{},- Deprecated: false,+ Deprecated: true,SecuritySchemes: newSecuritySchemes(types.RoleEditor),})).Methods(http.MethodPatch).GetError(); err != nil {return err@@ -142,6 +176,74 @@ func (provider *provider) addGatewayRoutes(router *mux.Router) error {ResponseContentType: "",SuccessStatusCode: http.StatusNoContent,ErrorStatusCodes: []int{},+ Deprecated: true,+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),+ })).Methods(http.MethodDelete).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/gateway/ingestion_limits", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.CreateIngestionKeyLimit), handler.OpenAPIDef{+ ID: "CreateIngestionLimit",+ Tags: []string{"gateway"},+ Summary: "Create ingestion limit",+ Description: "This endpoint creates an ingestion limit for the ingestion key referenced by keyId",+ Request: new(gatewaytypes.PostableIngestionKeyLimit),+ RequestContentType: "application/json",+ Response: new(types.Identifiable),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusCreated,+ ErrorStatusCodes: []int{http.StatusBadRequest},+ Deprecated: false,+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),+ })).Methods(http.MethodPost).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/gateway/ingestion_limits/{limitId}", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.GetIngestionKeyLimit), handler.OpenAPIDef{+ ID: "GetIngestionLimit",+ Tags: []string{"gateway"},+ Summary: "Get ingestion limit",+ Description: "This endpoint returns an ingestion limit",+ Request: nil,+ RequestContentType: "",+ Response: new(gatewaytypes.Limit),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusNotFound},+ Deprecated: false,+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),+ })).Methods(http.MethodGet).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/gateway/ingestion_limits/{limitId}", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.UpdateIngestionKeyLimit), handler.OpenAPIDef{+ ID: "UpdateIngestionLimit",+ Tags: []string{"gateway"},+ Summary: "Update ingestion limit",+ Description: "This endpoint updates an ingestion limit",+ Request: new(gatewaytypes.UpdatableIngestionKeyLimit),+ RequestContentType: "application/json",+ Response: nil,+ ResponseContentType: "",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{},+ Deprecated: false,+ SecuritySchemes: newSecuritySchemes(types.RoleEditor),+ })).Methods(http.MethodPatch).GetError(); err != nil {+ return err+ }++ if err := router.Handle("/api/v2/gateway/ingestion_limits/{limitId}", handler.New(provider.authzMiddleware.EditAccess(provider.gatewayHandler.DeleteIngestionKeyLimit), handler.OpenAPIDef{+ ID: "DeleteIngestionLimit",+ Tags: []string{"gateway"},+ Summary: "Delete ingestion limit",+ Description: "This endpoint deletes an ingestion limit",+ Request: nil,+ RequestContentType: "",+ Response: nil,+ ResponseContentType: "",+ SuccessStatusCode: http.StatusNoContent,+ ErrorStatusCodes: []int{},Deprecated: false,SecuritySchemes: newSecuritySchemes(types.RoleEditor),})).Methods(http.MethodDelete).GetError(); err != nil {diff --git a/pkg/gateway/gateway.go b/pkg/gateway/gateway.goindex 3ea7fba855..14758c1575 100644--- a/pkg/gateway/gateway.go+++ b/pkg/gateway/gateway.go@@ -22,6 +22,9 @@ type Gateway interface {// Search Ingestion Keys by Name (this is supposed to be for the current user but for now in gateway code this is ignoring the consumer user)SearchIngestionKeysByName(ctx context.Context, orgID valuer.UUID, name string, page, perPage int) (*gatewaytypes.GettableIngestionKeys, error)+ // Get Ingestion Key+ GetIngestionKey(ctx context.Context, orgID valuer.UUID, keyID string) (*gatewaytypes.IngestionKey, error)+// Create Ingestion KeyCreateIngestionKey(ctx context.Context, orgID valuer.UUID, name string, tags []string, expiresAt time.Time) (*gatewaytypes.GettableCreatedIngestionKey, error)@@ -34,6 +37,12 @@ type Gateway interface {// Create Ingestion Key LimitCreateIngestionKeyLimit(ctx context.Context, orgID valuer.UUID, keyID string, signal string, limitConfig gatewaytypes.LimitConfig, tags []string) (*gatewaytypes.GettableCreatedIngestionKeyLimit, error)+ // Get Ingestion Key Limit+ GetIngestionKeyLimit(ctx context.Context, orgID valuer.UUID, limitID string) (*gatewaytypes.Limit, error)++ // Get Ingestion Key Limits+ GetIngestionKeyLimits(ctx context.Context, orgID valuer.UUID, keyID string) ([]gatewaytypes.Limit, error)+// Update Ingestion Key LimitUpdateIngestionKeyLimit(ctx context.Context, orgID valuer.UUID, limitID string, limitConfig gatewaytypes.LimitConfig, tags []string) error@@ -46,6 +55,8 @@ type Handler interface {SearchIngestionKeys(http.ResponseWriter, *http.Request)+ GetIngestionKey(http.ResponseWriter, *http.Request)+CreateIngestionKey(http.ResponseWriter, *http.Request)UpdateIngestionKey(http.ResponseWriter, *http.Request)@@ -54,7 +65,13 @@ type Handler interface {CreateIngestionKeyLimit(http.ResponseWriter, *http.Request)+ GetIngestionKeyLimit(http.ResponseWriter, *http.Request)++ GetIngestionKeyLimits(http.ResponseWriter, *http.Request)+UpdateIngestionKeyLimit(http.ResponseWriter, *http.Request)DeleteIngestionKeyLimit(http.ResponseWriter, *http.Request)++ DeprecatedCreateIngestionKeyLimit(http.ResponseWriter, *http.Request)}diff --git a/pkg/gateway/handler.go b/pkg/gateway/handler.goindex ab61caf4dd..c6190cf1ea 100644--- a/pkg/gateway/handler.go+++ b/pkg/gateway/handler.go@@ -1,11 +1,11 @@package gatewayimport (- "encoding/json""net/http""strconv""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/authtypes""github.com/SigNoz/signoz/pkg/types/gatewaytypes"@@ -111,8 +111,8 @@ func (handler *handler) CreateIngestionKey(rw http.ResponseWriter, r *http.RequeorgID := valuer.MustNewUUID(claims.OrgID)var req gatewaytypes.PostableIngestionKey- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid request body"))+ if err := binding.JSON.BindBody(r.Body, &req); err != nil {+ render.Error(rw, err)return}@@ -143,8 +143,8 @@ func (handler *handler) UpdateIngestionKey(rw http.ResponseWriter, r *http.Reque}var req gatewaytypes.PostableIngestionKey- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid request body"))+ if err := binding.JSON.BindBody(r.Body, &req); err != nil {+ render.Error(rw, err)return}@@ -183,7 +183,7 @@ func (handler *handler) DeleteIngestionKey(rw http.ResponseWriter, r *http.Requerender.Success(rw, http.StatusNoContent, nil)}-func (handler *handler) CreateIngestionKeyLimit(rw http.ResponseWriter, r *http.Request) {+func (handler *handler) DeprecatedCreateIngestionKeyLimit(rw http.ResponseWriter, r *http.Request) {ctx := r.Context()claims, err := authtypes.ClaimsFromContext(ctx)@@ -200,9 +200,9 @@ func (handler *handler) CreateIngestionKeyLimit(rw http.ResponseWriter, r *http.return}- var req gatewaytypes.PostableIngestionKeyLimit- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid request body"))+ var req gatewaytypes.DeprecatedPostableIngestionKeyLimit+ if err := binding.JSON.BindBody(r.Body, &req); err != nil {+ render.Error(rw, err)return}@@ -233,8 +233,8 @@ func (handler *handler) UpdateIngestionKeyLimit(rw http.ResponseWriter, r *http.}var req gatewaytypes.UpdatableIngestionKeyLimit- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {- render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "invalid request body"))+ if err := binding.JSON.BindBody(r.Body, &req); err != nil {+ render.Error(rw, err)return}@@ -273,6 +273,115 @@ func (handler *handler) DeleteIngestionKeyLimit(rw http.ResponseWriter, r *http.render.Success(rw, http.StatusNoContent, nil)}+func (handler *handler) CreateIngestionKeyLimit(rw http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ orgID := valuer.MustNewUUID(claims.OrgID)++ var req gatewaytypes.PostableIngestionKeyLimit+ if err := binding.JSON.BindBody(r.Body, &req); err != nil {+ render.Error(rw, err)+ return+ }++ if req.KeyID == "" {+ render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "keyId is required"))+ return+ }++ response, err := handler.gateway.CreateIngestionKeyLimit(ctx, orgID, req.KeyID, req.Signal, req.Config, req.Tags)+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusCreated, response)+}++func (handler *handler) GetIngestionKeyLimit(rw http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ orgID := valuer.MustNewUUID(claims.OrgID)++ limitID := mux.Vars(r)["limitId"]+ if limitID == "" {+ render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "limitId is required"))+ return+ }++ response, err := handler.gateway.GetIngestionKeyLimit(ctx, orgID, limitID)+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, response)+}++func (handler *handler) GetIngestionKey(rw http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ orgID := valuer.MustNewUUID(claims.OrgID)++ keyID := mux.Vars(r)["keyId"]+ if keyID == "" {+ render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "keyId is required"))+ return+ }++ response, err := handler.gateway.GetIngestionKey(ctx, orgID, keyID)+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, response)+}++func (handler *handler) GetIngestionKeyLimits(rw http.ResponseWriter, r *http.Request) {+ ctx := r.Context()++ claims, err := authtypes.ClaimsFromContext(ctx)+ if err != nil {+ render.Error(rw, err)+ return+ }++ orgID := valuer.MustNewUUID(claims.OrgID)++ keyID := mux.Vars(r)["keyId"]+ if keyID == "" {+ render.Error(rw, errors.New(errors.TypeInvalidInput, errors.CodeInvalidInput, "keyId is required"))+ return+ }++ response, err := handler.gateway.GetIngestionKeyLimits(ctx, orgID, keyID)+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, response)+}+func parseIntWithDefaultValue(value string, defaultValue int) (int, error) {if value == "" {return defaultValue, nildiff --git a/pkg/gateway/noopgateway/provider.go b/pkg/gateway/noopgateway/provider.goindex 4609fed65d..760c2a1190 100644--- a/pkg/gateway/noopgateway/provider.go+++ b/pkg/gateway/noopgateway/provider.go@@ -31,6 +31,10 @@ func (p *provider) SearchIngestionKeysByName(_ context.Context, _ valuer.UUID, _return nil, errors.New(errors.TypeUnsupported, gateway.ErrCodeGatewayUnsupported, "unsupported call")}+func (p *provider) GetIngestionKey(_ context.Context, _ valuer.UUID, _ string) (*gatewaytypes.IngestionKey, error) {+ return nil, errors.New(errors.TypeUnsupported, gateway.ErrCodeGatewayUnsupported, "unsupported call")+}+func (p *provider) CreateIngestionKey(_ context.Context, _ valuer.UUID, _ string, _ []string, _ time.Time) (*gatewaytypes.GettableCreatedIngestionKey, error) {return nil, errors.New(errors.TypeUnsupported, gateway.ErrCodeGatewayUnsupported, "unsupported call")}@@ -47,6 +51,14 @@ func (p *provider) CreateIngestionKeyLimit(_ context.Context, _ valuer.UUID, _ sreturn nil, errors.New(errors.TypeUnsupported, gateway.ErrCodeGatewayUnsupported, "unsupported call")}+func (p *provider) GetIngestionKeyLimit(_ context.Context, _ valuer.UUID, _ string) (*gatewaytypes.Limit, error) {+ return nil, errors.New(errors.TypeUnsupported, gateway.ErrCodeGatewayUnsupported, "unsupported call")+}++func (p *provider) GetIngestionKeyLimits(_ context.Context, _ valuer.UUID, _ string) ([]gatewaytypes.Limit, error) {+ return nil, errors.New(errors.TypeUnsupported, gateway.ErrCodeGatewayUnsupported, "unsupported call")+}+func (p *provider) UpdateIngestionKeyLimit(_ context.Context, _ valuer.UUID, _ string, _ gatewaytypes.LimitConfig, _ []string) error {return errors.New(errors.TypeUnsupported, gateway.ErrCodeGatewayUnsupported, "unsupported call")}diff --git a/pkg/types/gatewaytypes/ingestionkey.go b/pkg/types/gatewaytypes/ingestionkey.goindex a8e9c4b752..96ea5787c1 100644--- a/pkg/types/gatewaytypes/ingestionkey.go+++ b/pkg/types/gatewaytypes/ingestionkey.go@@ -81,7 +81,7 @@ type GettableCreatedIngestionKey struct {Value string `json:"value" required:"true"`}-type PostableIngestionKeyLimit struct {+type DeprecatedPostableIngestionKeyLimit struct {Signal string `json:"signal"`Config LimitConfig `json:"config"`Tags []string `json:"tags"`@@ -91,6 +91,13 @@ type GettableCreatedIngestionKeyLimit struct {ID string `json:"id" required:"true"`}+type PostableIngestionKeyLimit struct {+ KeyID string `json:"keyId" required:"true"`+ Signal string `json:"signal"`+ Config LimitConfig `json:"config"`+ Tags []string `json:"tags"`+}+type UpdatableIngestionKeyLimit struct {Config LimitConfig `json:"config" required:"true"`Tags []string `json:"tags"`diff --git a/tests/integration/tests/ingestionkeys/01_ingestion_keys.py b/tests/integration/tests/ingestionkeys/01_ingestion_keys.pyindex 7e8a59fcdd..a6c07a8dbc 100644--- a/tests/integration/tests/ingestionkeys/01_ingestion_keys.py+++ b/tests/integration/tests/ingestionkeys/01_ingestion_keys.py@@ -177,6 +177,61 @@ def test_get_ingestion_keys(assert data["_pagination"]["total"] == 1+def test_get_ingestion_key_by_id(+ signoz: types.SigNoz,+ create_user_admin: types.Operation, # pylint: disable=unused-argument+ make_http_mocks: Callable[[types.TestContainerDocker, list], None],+ get_token: Callable[[str, str], str],+) -> None:+ editor_token = get_token(GATEWAY_APIS_EDITOR_EMAIL, GATEWAY_APIS_EDITOR_PASSWORD)++ gateway_url = f"/v1/workspaces/me/keys/{TEST_KEY_ID}"++ make_http_mocks(+ signoz.gateway,+ [+ Mapping(+ request=MappingRequest(+ method=HttpMethods.GET,+ url=gateway_url,+ headers=common_gateway_headers(),+ ),+ response=MappingResponse(+ status=200,+ json_body={+ "status": "success",+ "data": {+ "id": TEST_KEY_ID,+ "name": "my-test-key",+ "value": "secret",+ "expires_at": "2030-01-01T00:00:00Z",+ "tags": ["env:test"],+ "created_at": "2024-01-01T00:00:00Z",+ "updated_at": "2024-01-01T00:00:00Z",+ "workspace_id": "ws-1",+ },+ },+ ),+ persistent=False,+ ),+ ],+ )++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v2/gateway/ingestion_keys/{TEST_KEY_ID}"),+ headers={"Authorization": f"Bearer {editor_token}"},+ timeout=10,+ )++ assert response.status_code == HTTPStatus.OK, f"Expected 200, got {response.status_code}: {response.text}"++ data = response.json()["data"]+ assert data["id"] == TEST_KEY_ID+ assert data["name"] == "my-test-key"+ assert data["workspace_id"] == "ws-1"+ assert data["tags"] == ["env:test"]++def test_get_ingestion_keys_custom_pagination(signoz: types.SigNoz,create_user_admin: types.Operation, # pylint: disable=unused-argumentdiff --git a/tests/integration/tests/ingestionkeys/02_ingestion_keys_limits.py b/tests/integration/tests/ingestionkeys/02_ingestion_keys_limits.pyindex 488b0eb360..f64e868c69 100644--- a/tests/integration/tests/ingestionkeys/02_ingestion_keys_limits.py+++ b/tests/integration/tests/ingestionkeys/02_ingestion_keys_limits.py@@ -65,7 +65,7 @@ def test_create_ingestion_key_limit_only_size(status=201,json_body={"status": "success",- "data": {"id": "limit-created-1"},+ "data": {"id": "2c5b7d3e-4f6a-4b8c-a09d-3f4a5b6c7d8e"},},),persistent=False,@@ -86,7 +86,7 @@ def test_create_ingestion_key_limit_only_size(assert response.status_code == HTTPStatus.CREATED, f"Expected 201, got {response.status_code}: {response.text}"- assert response.json()["data"]["id"] == "limit-created-1"+ assert response.json()["data"]["id"] == "2c5b7d3e-4f6a-4b8c-a09d-3f4a5b6c7d8e"body = get_latest_gateway_request_body(signoz, "POST", gateway_url)assert body is not None, "Expected a POST request to reach the gateway"@@ -121,7 +121,7 @@ def test_create_ingestion_key_limit_only_count(status=201,json_body={"status": "success",- "data": {"id": "limit-created-2"},+ "data": {"id": "3d6c8e4f-5a7b-4c9d-b1ae-4a5b6c7d8e9f"},},),persistent=False,@@ -174,7 +174,7 @@ def test_create_ingestion_key_limit_both_size_and_count(status=201,json_body={"status": "success",- "data": {"id": "limit-created-3"},+ "data": {"id": "4e7d9f5a-6b8c-4dae-c2bf-5b6c7d8e9fa0"},},),persistent=False,@@ -391,3 +391,265 @@ def test_delete_ingestion_key_limit(# Verify at least one DELETE reached the gatewaymatched = get_gateway_requests(signoz, "DELETE", gateway_url)assert len(matched) >= 1, "Expected a DELETE request to reach the gateway"+++def test_create_ingestion_limit(+ signoz: types.SigNoz,+ create_user_admin: types.Operation, # pylint: disable=unused-argument+ make_http_mocks: Callable[[types.TestContainerDocker, list], None],+ get_token: Callable[[str, str], str],+) -> None:+ editor_token = get_token(GATEWAY_APIS_EDITOR_EMAIL, GATEWAY_APIS_EDITOR_PASSWORD)++ gateway_url = f"/v1/workspaces/me/keys/{TEST_KEY_ID}/limits"++ make_http_mocks(+ signoz.gateway,+ [+ Mapping(+ request=MappingRequest(+ method=HttpMethods.POST,+ url=gateway_url,+ headers=common_gateway_headers(),+ ),+ response=MappingResponse(+ status=201,+ json_body={+ "status": "success",+ "data": {"id": "5f8ea06b-7c9d-4ebf-a3c0-6c7d8e9fa0b1"},+ },+ ),+ persistent=False,+ ),+ ],+ )++ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v2/gateway/ingestion_limits"),+ json={+ "keyId": TEST_KEY_ID,+ "signal": "logs",+ "config": {"day": {"size": 3000}},+ "tags": ["test"],+ },+ headers={"Authorization": f"Bearer {editor_token}"},+ timeout=10,+ )++ assert response.status_code == HTTPStatus.CREATED, f"Expected 201, got {response.status_code}: {response.text}"++ assert response.json()["data"]["id"] == "5f8ea06b-7c9d-4ebf-a3c0-6c7d8e9fa0b1"++ body = get_latest_gateway_request_body(signoz, "POST", gateway_url)+ assert body is not None, "Expected a POST request to reach the gateway"+ assert body["signal"] == "logs"+ assert body["config"]["day"]["size"] == 3000+ assert body["tags"] == ["test"]+++def test_create_ingestion_limit_without_key_id(+ signoz: types.SigNoz,+ create_user_admin: types.Operation, # pylint: disable=unused-argument+ get_token: Callable[[str, str], str],+) -> None:+ editor_token = get_token(GATEWAY_APIS_EDITOR_EMAIL, GATEWAY_APIS_EDITOR_PASSWORD)++ response = requests.post(+ signoz.self.host_configs["8080"].get("/api/v2/gateway/ingestion_limits"),+ json={+ "signal": "logs",+ "config": {"day": {"size": 3000}},+ },+ headers={"Authorization": f"Bearer {editor_token}"},+ timeout=10,+ )++ assert response.status_code == HTTPStatus.BAD_REQUEST, f"Expected 400, got {response.status_code}: {response.text}"+++def test_get_ingestion_limit(+ signoz: types.SigNoz,+ create_user_admin: types.Operation, # pylint: disable=unused-argument+ make_http_mocks: Callable[[types.TestContainerDocker, list], None],+ get_token: Callable[[str, str], str],+) -> None:+ editor_token = get_token(GATEWAY_APIS_EDITOR_EMAIL, GATEWAY_APIS_EDITOR_PASSWORD)++ gateway_url = f"/v1/workspaces/me/limits/{TEST_LIMIT_ID}"++ make_http_mocks(+ signoz.gateway,+ [+ Mapping(+ request=MappingRequest(+ method=HttpMethods.GET,+ url=gateway_url,+ headers=common_gateway_headers(),+ ),+ response=MappingResponse(+ status=200,+ json_body={+ "status": "success",+ "data": {+ "id": TEST_LIMIT_ID,+ "key_id": TEST_KEY_ID,+ "signal": "logs",+ "config": {"day": {"size": 1000}},+ "tags": ["test"],+ },+ },+ ),+ persistent=False,+ ),+ ],+ )++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v2/gateway/ingestion_limits/{TEST_LIMIT_ID}"),+ headers={"Authorization": f"Bearer {editor_token}"},+ timeout=10,+ )++ assert response.status_code == HTTPStatus.OK, f"Expected 200, got {response.status_code}: {response.text}"++ data = response.json()["data"]+ assert data["id"] == TEST_LIMIT_ID+ assert data["key_id"] == TEST_KEY_ID+ assert data["signal"] == "logs"+ assert data["config"]["day"]["size"] == 1000+++def test_get_ingestion_key_limits(+ signoz: types.SigNoz,+ create_user_admin: types.Operation, # pylint: disable=unused-argument+ make_http_mocks: Callable[[types.TestContainerDocker, list], None],+ get_token: Callable[[str, str], str],+) -> None:+ editor_token = get_token(GATEWAY_APIS_EDITOR_EMAIL, GATEWAY_APIS_EDITOR_PASSWORD)++ gateway_url = f"/v1/workspaces/me/keys/{TEST_KEY_ID}/limits"++ make_http_mocks(+ signoz.gateway,+ [+ Mapping(+ request=MappingRequest(+ method=HttpMethods.GET,+ url=gateway_url,+ headers=common_gateway_headers(),+ ),+ response=MappingResponse(+ status=200,+ json_body={+ "status": "success",+ "data": [+ {+ "id": TEST_LIMIT_ID,+ "key_id": TEST_KEY_ID,+ "signal": "logs",+ "config": {"day": {"size": 1000}},+ "tags": ["test"],+ }+ ],+ },+ ),+ persistent=False,+ ),+ ],+ )++ response = requests.get(+ signoz.self.host_configs["8080"].get(f"/api/v2/gateway/ingestion_keys/{TEST_KEY_ID}/limits"),+ headers={"Authorization": f"Bearer {editor_token}"},+ timeout=10,+ )++ assert response.status_code == HTTPStatus.OK, f"Expected 200, got {response.status_code}: {response.text}"++ data = response.json()["data"]+ assert len(data) == 1+ assert data[0]["id"] == TEST_LIMIT_ID+ assert data[0]["key_id"] == TEST_KEY_ID+ assert data[0]["signal"] == "logs"+ assert data[0]["config"]["day"]["size"] == 1000+++def test_update_ingestion_limit(+ signoz: types.SigNoz,+ create_user_admin: types.Operation, # pylint: disable=unused-argument+ make_http_mocks: Callable[[types.TestContainerDocker, list], None],+ get_token: Callable[[str, str], str],+) -> None:+ editor_token = get_token(GATEWAY_APIS_EDITOR_EMAIL, GATEWAY_APIS_EDITOR_PASSWORD)++ gateway_url = f"/v1/workspaces/me/limits/{TEST_LIMIT_ID}"++ make_http_mocks(+ signoz.gateway,+ [+ Mapping(+ request=MappingRequest(+ method=HttpMethods.PATCH,+ url=gateway_url,+ headers=common_gateway_headers(),+ ),+ response=MappingResponse(status=204),+ persistent=False,+ ),+ ],+ )++ response = requests.patch(+ signoz.self.host_configs["8080"].get(f"/api/v2/gateway/ingestion_limits/{TEST_LIMIT_ID}"),+ json={+ "config": {"day": {"size": 4000, "count": 250}},+ "tags": ["test"],+ },+ headers={"Authorization": f"Bearer {editor_token}"},+ timeout=10,+ )++ assert response.status_code == HTTPStatus.NO_CONTENT, f"Expected 204, got {response.status_code}: {response.text}"++ body = get_latest_gateway_request_body(signoz, "PATCH", gateway_url)+ assert body is not None, "Expected a PATCH request to reach the gateway"+ assert body["config"]["day"]["size"] == 4000+ assert body["config"]["day"]["count"] == 250+ assert body["tags"] == ["test"]+++def test_delete_ingestion_limit(+ signoz: types.SigNoz,+ create_user_admin: types.Operation, # pylint: disable=unused-argument+ make_http_mocks: Callable[[types.TestContainerDocker, list], None],+ get_token: Callable[[str, str], str],+) -> None:+ editor_token = get_token(GATEWAY_APIS_EDITOR_EMAIL, GATEWAY_APIS_EDITOR_PASSWORD)++ gateway_url = f"/v1/workspaces/me/limits/{TEST_LIMIT_ID}"++ make_http_mocks(+ signoz.gateway,+ [+ Mapping(+ request=MappingRequest(+ method=HttpMethods.DELETE,+ url=gateway_url,+ headers=common_gateway_headers(),+ ),+ response=MappingResponse(status=204),+ persistent=False,+ ),+ ],+ )++ response = requests.delete(+ signoz.self.host_configs["8080"].get(f"/api/v2/gateway/ingestion_limits/{TEST_LIMIT_ID}"),+ headers={"Authorization": f"Bearer {editor_token}"},+ timeout=10,+ )++ assert response.status_code == HTTPStatus.NO_CONTENT, f"Expected 204, got {response.status_code}: {response.text}"++ matched = get_gateway_requests(signoz, "DELETE", gateway_url)+ assert len(matched) >= 1, "Expected a DELETE request to reach the gateway"