Skip to content

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.

feat(subscription): add subscription endpoints with resource authz (#12767)

Vikrant Gupta0f36cb933404
diff --git a/cmd/community/server.go b/cmd/community/server.go
index 36a4b495bf..c187c466d9 100644
--- a/cmd/community/server.go
+++ b/cmd/community/server.go
@@ -44,6 +44,8 @@ import (
"github.com/SigNoz/signoz/pkg/ruler/signozruler"
"github.com/SigNoz/signoz/pkg/signoz"
"github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/subscription"
+ "github.com/SigNoz/signoz/pkg/subscription/noopsubscription"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
@@ -87,6 +89,9 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
func(_ sqlstore.SQLStore, _ zeus.Zeus, _ organization.Getter, _ analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return nooplicensing.NewFactory()
},
+ func(_ zeus.Zeus, _ licensing.Licensing) subscription.Subscription {
+ return noopsubscription.New()
+ },
signoz.NewEmailingProviderFactories(),
signoz.NewCacheProviderFactories(),
signoz.NewWebProviderFactories(config.Global),
diff --git a/cmd/enterprise/server.go b/cmd/enterprise/server.go
index db79628b56..c0ec9787e7 100644
--- a/cmd/enterprise/server.go
+++ b/cmd/enterprise/server.go
@@ -28,6 +28,7 @@ import (
eequerier "github.com/SigNoz/signoz/ee/querier"
enterpriseapp "github.com/SigNoz/signoz/ee/query-service/app"
eerules "github.com/SigNoz/signoz/ee/query-service/rules"
+ "github.com/SigNoz/signoz/ee/subscription/httpsubscription"
enterprisezeus "github.com/SigNoz/signoz/ee/zeus"
"github.com/SigNoz/signoz/ee/zeus/httpzeus"
"github.com/SigNoz/signoz/pkg/alertmanager"
@@ -60,6 +61,7 @@ import (
"github.com/SigNoz/signoz/pkg/ruler/signozruler"
"github.com/SigNoz/signoz/pkg/signoz"
"github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/subscription"
"github.com/SigNoz/signoz/pkg/telemetrystore"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/cloudintegrationtypes"
@@ -103,6 +105,9 @@ func runServer(ctx context.Context, config signoz.Config, logger *slog.Logger) e
func(sqlstore sqlstore.SQLStore, zeus zeus.Zeus, orgGetter organization.Getter, analytics analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config] {
return httplicensing.NewProviderFactory(sqlstore, zeus, orgGetter, analytics)
},
+ func(zeus zeus.Zeus, licensing licensing.Licensing) subscription.Subscription {
+ return httpsubscription.New(zeus, licensing)
+ },
signoz.NewEmailingProviderFactories(),
signoz.NewCacheProviderFactories(),
signoz.NewWebProviderFactories(config.Global),
diff --git a/docs/api/openapi.yml b/docs/api/openapi.yml
index 9c13b7e609..029d4db99a 100644
--- a/docs/api/openapi.yml
+++ b/docs/api/openapi.yml
@@ -9217,6 +9217,116 @@ components:
required:
- references
type: object
+ SubscriptiontypesGettableSubscription:
+ properties:
+ redirectURL:
+ type: string
+ required:
+ - redirectURL
+ type: object
+ SubscriptiontypesGettableSubscriptionUsage:
+ properties:
+ billingPeriodEnd:
+ format: int64
+ type: integer
+ billingPeriodStart:
+ format: int64
+ type: integer
+ details:
+ $ref: '#/components/schemas/SubscriptiontypesSubscriptionUsageDetails'
+ discount:
+ format: double
+ type: number
+ subscriptionStatus:
+ type: string
+ type: object
+ SubscriptiontypesPostableSubscription:
+ properties:
+ url:
+ type: string
+ required:
+ - url
+ type: object
+ SubscriptiontypesSubscriptionUsageBreakdown:
+ properties:
+ dayWiseBreakdown:
+ $ref: '#/components/schemas/SubscriptiontypesSubscriptionUsageDayWiseBreakdown'
+ tiers:
+ items:
+ $ref: '#/components/schemas/SubscriptiontypesSubscriptionUsageTier'
+ nullable: true
+ type: array
+ type:
+ type: string
+ unit:
+ type: string
+ type: object
+ SubscriptiontypesSubscriptionUsageDayWiseBreakdown:
+ properties:
+ breakdown:
+ items:
+ $ref: '#/components/schemas/SubscriptiontypesSubscriptionUsageDayWiseData'
+ nullable: true
+ type: array
+ type:
+ type: string
+ type: object
+ SubscriptiontypesSubscriptionUsageDayWiseData:
+ properties:
+ count:
+ format: double
+ type: number
+ quantity:
+ format: double
+ type: number
+ size:
+ format: double
+ type: number
+ timestamp:
+ format: int64
+ type: integer
+ total:
+ format: double
+ type: number
+ unitPrice:
+ format: double
+ type: number
+ type: object
+ SubscriptiontypesSubscriptionUsageDetails:
+ properties:
+ baseFee:
+ format: double
+ type: number
+ billTotal:
+ format: double
+ type: number
+ breakdown:
+ items:
+ $ref: '#/components/schemas/SubscriptiontypesSubscriptionUsageBreakdown'
+ nullable: true
+ type: array
+ total:
+ format: double
+ type: number
+ type: object
+ SubscriptiontypesSubscriptionUsageTier:
+ properties:
+ quantity:
+ format: double
+ type: number
+ tierCost:
+ format: double
+ type: number
+ tierEnd:
+ format: int64
+ type: integer
+ tierStart:
+ format: int64
+ type: integer
+ unitPrice:
+ format: double
+ type: number
+ type: object
TagtypesGettableTag:
properties:
key:
@@ -14441,6 +14551,197 @@ paths:
summary: Get stats
tags:
- stats
+ /api/v1/subscriptions:
+ get:
+ deprecated: false
+ description: This endpoint gets the organization's subscription along with its
+ usage and billing details.
+ operationId: GetSubscription
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/SubscriptiontypesGettableSubscriptionUsage'
+ 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:
+ - subscription:read
+ - tokenizer:
+ - subscription:read
+ summary: Get the subscription.
+ tags:
+ - subscriptions
+ post:
+ deprecated: false
+ description: This endpoint creates a subscription for the organization.
+ operationId: CreateSubscription
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SubscriptiontypesPostableSubscription'
+ responses:
+ "201":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/SubscriptiontypesGettableSubscription'
+ 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
+ "404":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Not Found
+ "409":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Conflict
+ "500":
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/RenderErrorResponse'
+ description: Internal Server Error
+ security:
+ - api_key:
+ - subscription:create
+ - tokenizer:
+ - subscription:create
+ summary: Create a subscription.
+ tags:
+ - subscriptions
+ put:
+ deprecated: false
+ description: This endpoint updates the organization's subscription.
+ operationId: UpdateSubscription
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SubscriptiontypesPostableSubscription'
+ responses:
+ "200":
+ content:
+ application/json:
+ schema:
+ properties:
+ data:
+ $ref: '#/components/schemas/SubscriptiontypesGettableSubscription'
+ 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:
+ - subscription:list
+ - subscription:update
+ - tokenizer:
+ - subscription:list
+ - subscription:update
+ summary: Update the subscription.
+ tags:
+ - subscriptions
/api/v1/testChannel:
post:
deprecated: true
diff --git a/ee/subscription/httpsubscription/provider.go b/ee/subscription/httpsubscription/provider.go
new file mode 100644
index 0000000000..361c58a505
--- /dev/null
+++ b/ee/subscription/httpsubscription/provider.go
@@ -0,0 +1,95 @@
+package httpsubscription
+
+import (
+ "context"
+ "encoding/json"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/licensing"
+ "github.com/SigNoz/signoz/pkg/subscription"
+ "github.com/SigNoz/signoz/pkg/types/subscriptiontypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/SigNoz/signoz/pkg/zeus"
+ "github.com/tidwall/gjson"
+)
+
+const upstreamTimeout = 10 * time.Second
+
+type provider struct {
+ zeus zeus.Zeus
+ licensing licensing.Licensing
+}
+
+func New(zeus zeus.Zeus, licensing licensing.Licensing) subscription.Subscription {
+ return &provider{
+ zeus: zeus,
+ licensing: licensing,
+ }
+}
+
+func (provider *provider) Create(ctx context.Context, organizationID valuer.UUID, postableSubscription *subscriptiontypes.PostableSubscription) (*subscriptiontypes.GettableSubscription, error) {
+ ctx, cancel := context.WithTimeout(ctx, upstreamTimeout)
+ defer cancel()
+
+ license, err := provider.licensing.GetActive(ctx, organizationID)
+ if err != nil {
+ return nil, err
+ }
+
+ body, err := json.Marshal(postableSubscription)
+ if err != nil {
+ return nil, errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "failed to marshal subscription payload")
+ }
+
+ response, err := provider.zeus.GetCheckoutURL(ctx, license.Key, body)
+ if err != nil {
+ if errors.Ast(err, errors.TypeAlreadyExists) {
+ return nil, errors.WithAdditionalf(err, "checkout has already been completed for this account. Please click 'Refresh Status' to sync your subscription")
+ }
+ return nil, err
+ }
+
+ return &subscriptiontypes.GettableSubscription{RedirectURL: gjson.GetBytes(response, "url").String()}, nil
+}
+
+func (provider *provider) Update(ctx context.Context, organizationID valuer.UUID, postableSubscription *subscriptiontypes.PostableSubscription) (*subscriptiontypes.GettableSubscription, error) {
+ ctx, cancel := context.WithTimeout(ctx, upstreamTimeout)
+ defer cancel()
+
+ license, err := provider.licensing.GetActive(ctx, organizationID)
+ if err != nil {
+ return nil, err
+ }
+
+ body, err := json.Marshal(postableSubscription)
+ if err != nil {
+ return nil, errors.Wrapf(err, errors.TypeInvalidInput, errors.CodeInvalidInput, "failed to marshal subscription payload")
+ }
+
+ response, err := provider.zeus.GetPortalURL(ctx, license.Key, body)
+ if err != nil {
+ return nil, err
+ }
+
+ return &subscriptiontypes.GettableSubscription{RedirectURL: gjson.GetBytes(response, "url").String()}, nil
+}
+
+func (provider *provider) Get(ctx context.Context, organizationID valuer.UUID) (*subscriptiontypes.GettableSubscriptionUsage, error) {
+ license, err := provider.licensing.GetActive(ctx, organizationID)
+ if err != nil {
+ return nil, err
+ }
+
+ data, err := provider.zeus.GetMeters(ctx, license.Key)
+ if err != nil {
+ return nil, err
+ }
+
+ usage, err := subscriptiontypes.NewGettableSubscriptionUsage(data)
+ if err != nil {
+ return nil, errors.Wrapf(err, errors.TypeInternal, zeus.ErrCodeResponseMalformed, "failed to unmarshal subscription usage")
+ }
+
+ return usage, nil
+}
diff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.ts
index e059724ebc..973c64d2bd 100644
--- a/frontend/src/api/generated/services/sigNoz.schemas.ts
+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts
@@ -10522,6 +10522,153 @@ export interface SpantypesUpdatableSpanMapperGroupDTO {
name?: string | null;
}
+export interface SubscriptiontypesGettableSubscriptionDTO {
+ /**
+ * @type string
+ */
+ redirectURL: string;
+}
+
+export interface SubscriptiontypesSubscriptionUsageDayWiseDataDTO {
+ /**
+ * @type number
+ * @format double
+ */
+ count?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ quantity?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ size?: number;
+ /**
+ * @type integer
+ * @format int64
+ */
+ timestamp?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ total?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ unitPrice?: number;
+}
+
+export interface SubscriptiontypesSubscriptionUsageDayWiseBreakdownDTO {
+ /**
+ * @type array,null
+ */
+ breakdown?: SubscriptiontypesSubscriptionUsageDayWiseDataDTO[] | null;
+ /**
+ * @type string
+ */
+ type?: string;
+}
+
+export interface SubscriptiontypesSubscriptionUsageTierDTO {
+ /**
+ * @type number
+ * @format double
+ */
+ quantity?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ tierCost?: number;
+ /**
+ * @type integer
+ * @format int64
+ */
+ tierEnd?: number;
+ /**
+ * @type integer
+ * @format int64
+ */
+ tierStart?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ unitPrice?: number;
+}
+
+export interface SubscriptiontypesSubscriptionUsageBreakdownDTO {
+ dayWiseBreakdown?: SubscriptiontypesSubscriptionUsageDayWiseBreakdownDTO;
+ /**
+ * @type array,null
+ */
+ tiers?: SubscriptiontypesSubscriptionUsageTierDTO[] | null;
+ /**
+ * @type string
+ */
+ type?: string;
+ /**
+ * @type string
+ */
+ unit?: string;
+}
+
+export interface SubscriptiontypesSubscriptionUsageDetailsDTO {
+ /**
+ * @type number
+ * @format double
+ */
+ baseFee?: number;
+ /**
+ * @type number
+ * @format double
+ */
+ billTotal?: number;
+ /**
+ * @type array,null
+ */
+ breakdown?: SubscriptiontypesSubscriptionUsageBreakdownDTO[] | null;
+ /**
+ * @type number
+ * @format double
+ */
+ total?: number;
+}
+
+export interface SubscriptiontypesGettableSubscriptionUsageDTO {
+ /**
+ * @type integer
+ * @format int64
+ */
+ billingPeriodEnd?: number;
+ /**
+ * @type integer
+ * @format int64
+ */
+ billingPeriodStart?: number;
+ details?: SubscriptiontypesSubscriptionUsageDetailsDTO;
+ /**
+ * @type number
+ * @format double
+ */
+ discount?: number;
+ /**
+ * @type string
+ */
+ subscriptionStatus?: string;
+}
+
+export interface SubscriptiontypesPostableSubscriptionDTO {
+ /**
+ * @type string
+ */
+ url: string;
+}
+
export type TelemetrytypesGettableFieldKeysDTOKeysAnyOf = {
[key: string]: TelemetrytypesTelemetryFieldKeyDTO[];
};
@@ -11740,6 +11887,30 @@ export type GetStats200 = {
status: string;
};
+export type GetSubscription200 = {
+ data: SubscriptiontypesGettableSubscriptionUsageDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
+export type CreateSubscription201 = {
+ data: SubscriptiontypesGettableSubscriptionDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
+export type UpdateSubscription200 = {
+ data: SubscriptiontypesGettableSubscriptionDTO;
+ /**
+ * @type string
+ */
+ status: string;
+};
+
export type GetTraceAggregationsPathParameters = {
traceID: string;
};
diff --git a/frontend/src/api/generated/services/subscriptions/index.ts b/frontend/src/api/generated/services/subscriptions/index.ts
new file mode 100644
index 0000000000..de14325413
--- /dev/null
+++ b/frontend/src/api/generated/services/subscriptions/index.ts
@@ -0,0 +1,280 @@
+/**
+ * ! Do not edit manually
+ * * The file has been auto-generated using Orval for SigNoz
+ * * regenerate with 'pnpm generate:api'
+ * SigNoz
+ */
+import { useMutation, useQuery } from 'react-query';
+import type {
+ InvalidateOptions,
+ MutationFunction,
+ QueryClient,
+ QueryFunction,
+ QueryKey,
+ UseMutationOptions,
+ UseMutationResult,
+ UseQueryOptions,
+ UseQueryResult,
+} from 'react-query';
+
+import type {
+ CreateSubscription201,
+ GetSubscription200,
+ RenderErrorResponseDTO,
+ SubscriptiontypesPostableSubscriptionDTO,
+ UpdateSubscription200,
+} from '../sigNoz.schemas';
+
+import { GeneratedAPIInstance } from '../../../generatedAPIInstance';
+import type { ErrorType, BodyType } from '../../../generatedAPIInstance';
+
+/**
+ * This endpoint gets the organization's subscription along with its usage and billing details.
+ * @summary Get the subscription.
+ */
+export const getSubscription = (signal?: AbortSignal) => {
+ return GeneratedAPIInstance<GetSubscription200>({
+ url: `/api/v1/subscriptions`,
+ method: 'GET',
+ signal,
+ });
+};
+
+export const getGetSubscriptionQueryKey = () => {
+ return [`/api/v1/subscriptions`] as const;
+};
+
+export const getGetSubscriptionQueryOptions = <
+ TData = Awaited<ReturnType<typeof getSubscription>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getSubscription>>,
+ TError,
+ TData
+ >;
+}) => {
+ const { query: queryOptions } = options ?? {};
+
+ const queryKey = queryOptions?.queryKey ?? getGetSubscriptionQueryKey();
+
+ const queryFn: QueryFunction<Awaited<ReturnType<typeof getSubscription>>> = ({
+ signal,
+ }) => getSubscription(signal);
+
+ return { queryKey, queryFn, ...queryOptions } as UseQueryOptions<
+ Awaited<ReturnType<typeof getSubscription>>,
+ TError,
+ TData
+ > & { queryKey: QueryKey };
+};
+
+export type GetSubscriptionQueryResult = NonNullable<
+ Awaited<ReturnType<typeof getSubscription>>
+>;
+export type GetSubscriptionQueryError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Get the subscription.
+ */
+
+export function useGetSubscription<
+ TData = Awaited<ReturnType<typeof getSubscription>>,
+ TError = ErrorType<RenderErrorResponseDTO>,
+>(options?: {
+ query?: UseQueryOptions<
+ Awaited<ReturnType<typeof getSubscription>>,
+ TError,
+ TData
+ >;
+}): UseQueryResult<TData, TError> & { queryKey: QueryKey } {
+ const queryOptions = getGetSubscriptionQueryOptions(options);
+
+ const query = useQuery(queryOptions) as UseQueryResult<TData, TError> & {
+ queryKey: QueryKey;
+ };
+
+ return { ...query, queryKey: queryOptions.queryKey };
+}
+
+/**
+ * @summary Get the subscription.
+ */
+export const invalidateGetSubscription = async (
+ queryClient: QueryClient,
+ options?: InvalidateOptions,
+): Promise<QueryClient> => {
+ await queryClient.invalidateQueries(
+ { queryKey: getGetSubscriptionQueryKey() },
+ options,
+ );
+
+ return queryClient;
+};
+
+/**
+ * This endpoint creates a subscription for the organization.
+ * @summary Create a subscription.
+ */
+export const createSubscription = (
+ subscriptiontypesPostableSubscriptionDTO?: BodyType<SubscriptiontypesPostableSubscriptionDTO>,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<CreateSubscription201>({
+ url: `/api/v1/subscriptions`,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ data: subscriptiontypesPostableSubscriptionDTO,
+ signal,
+ });
+};
+
+export const getCreateSubscriptionMutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof createSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+> => {
+ const mutationKey = ['createSubscription'];
+ 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 createSubscription>>,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> }
+ > = (props) => {
+ const { data } = props ?? {};
+
+ return createSubscription(data);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type CreateSubscriptionMutationResult = NonNullable<
+ Awaited<ReturnType<typeof createSubscription>>
+>;
+export type CreateSubscriptionMutationBody =
+ | BodyType<SubscriptiontypesPostableSubscriptionDTO>
+ | undefined;
+export type CreateSubscriptionMutationError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Create a subscription.
+ */
+export const useCreateSubscription = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof createSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof createSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+> => {
+ return useMutation(getCreateSubscriptionMutationOptions(options));
+};
+/**
+ * This endpoint updates the organization's subscription.
+ * @summary Update the subscription.
+ */
+export const updateSubscription = (
+ subscriptiontypesPostableSubscriptionDTO?: BodyType<SubscriptiontypesPostableSubscriptionDTO>,
+ signal?: AbortSignal,
+) => {
+ return GeneratedAPIInstance<UpdateSubscription200>({
+ url: `/api/v1/subscriptions`,
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ data: subscriptiontypesPostableSubscriptionDTO,
+ signal,
+ });
+};
+
+export const getUpdateSubscriptionMutationOptions = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof updateSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+ >;
+}): UseMutationOptions<
+ Awaited<ReturnType<typeof updateSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+> => {
+ const mutationKey = ['updateSubscription'];
+ 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 updateSubscription>>,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> }
+ > = (props) => {
+ const { data } = props ?? {};
+
+ return updateSubscription(data);
+ };
+
+ return { mutationFn, ...mutationOptions };
+};
+
+export type UpdateSubscriptionMutationResult = NonNullable<
+ Awaited<ReturnType<typeof updateSubscription>>
+>;
+export type UpdateSubscriptionMutationBody =
+ | BodyType<SubscriptiontypesPostableSubscriptionDTO>
+ | undefined;
+export type UpdateSubscriptionMutationError = ErrorType<RenderErrorResponseDTO>;
+
+/**
+ * @summary Update the subscription.
+ */
+export const useUpdateSubscription = <
+ TError = ErrorType<RenderErrorResponseDTO>,
+ TContext = unknown,
+>(options?: {
+ mutation?: UseMutationOptions<
+ Awaited<ReturnType<typeof updateSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+ >;
+}): UseMutationResult<
+ Awaited<ReturnType<typeof updateSubscription>>,
+ TError,
+ { data?: BodyType<SubscriptiontypesPostableSubscriptionDTO> },
+ TContext
+> => {
+ return useMutation(getUpdateSubscriptionMutationOptions(options));
+};
diff --git a/pkg/apiserver/signozapiserver/provider.go b/pkg/apiserver/signozapiserver/provider.go
index 4842ee910a..cc110f30cf 100644
--- a/pkg/apiserver/signozapiserver/provider.go
+++ b/pkg/apiserver/signozapiserver/provider.go
@@ -38,6 +38,7 @@ import (
"github.com/SigNoz/signoz/pkg/querier"
"github.com/SigNoz/signoz/pkg/ruler"
"github.com/SigNoz/signoz/pkg/statsreporter"
+ "github.com/SigNoz/signoz/pkg/subscription"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/zeus"
@@ -72,6 +73,7 @@ type provider struct {
rawDataExportHandler rawdataexport.Handler
zeusHandler zeus.Handler
licensingHandler licensing.Handler
+ subscriptionHandler subscription.Handler
querierHandler querier.Handler
serviceAccountHandler serviceaccount.Handler
serviceAccountGetter serviceaccount.Getter
@@ -115,6 +117,7 @@ func NewFactory(
rawDataExportHandler rawdataexport.Handler,
zeusHandler zeus.Handler,
licensingHandler licensing.Handler,
+ subscriptionHandler subscription.Handler,
querierHandler querier.Handler,
serviceAccountHandler serviceaccount.Handler,
serviceAccountGetter serviceaccount.Getter,
@@ -161,6 +164,7 @@ func NewFactory(
rawDataExportHandler,
zeusHandler,
licensingHandler,
+ subscriptionHandler,
querierHandler,
serviceAccountHandler,
serviceAccountGetter,
@@ -209,6 +213,7 @@ func newProvider(
rawDataExportHandler rawdataexport.Handler,
zeusHandler zeus.Handler,
licensingHandler licensing.Handler,
+ subscriptionHandler subscription.Handler,
querierHandler querier.Handler,
serviceAccountHandler serviceaccount.Handler,
serviceAccountGetter serviceaccount.Getter,
@@ -256,6 +261,7 @@ func newProvider(
rawDataExportHandler: rawDataExportHandler,
zeusHandler: zeusHandler,
licensingHandler: licensingHandler,
+ subscriptionHandler: subscriptionHandler,
querierHandler: querierHandler,
serviceAccountHandler: serviceAccountHandler,
serviceAccountGetter: serviceAccountGetter,
@@ -368,6 +374,10 @@ func (provider *provider) AddToRouter(router *mux.Router) error {
return err
}
+ if err := provider.addSubscriptionRoutes(router); err != nil {
+ return err
+ }
+
if err := provider.addQuerierRoutes(router); err != nil {
return err
}
diff --git a/pkg/apiserver/signozapiserver/subscription.go b/pkg/apiserver/signozapiserver/subscription.go
new file mode 100644
index 0000000000..6b1fd22ae5
--- /dev/null
+++ b/pkg/apiserver/signozapiserver/subscription.go
@@ -0,0 +1,89 @@
+package signozapiserver
+
+import (
+ "net/http"
+
+ "github.com/SigNoz/signoz/pkg/http/handler"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/coretypes"
+ "github.com/SigNoz/signoz/pkg/types/subscriptiontypes"
+ "github.com/gorilla/mux"
+)
+
+func (provider *provider) addSubscriptionRoutes(router *mux.Router) error {
+ if err := router.Handle("/api/v1/subscriptions", handler.New(provider.authzMiddleware.CheckResources(provider.subscriptionHandler.Create, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
+ ID: "CreateSubscription",
+ Tags: []string{"subscriptions"},
+ Summary: "Create a subscription.",
+ Description: "This endpoint creates a subscription for the organization.",
+ Request: new(subscriptiontypes.PostableSubscription),
+ RequestContentType: "application/json",
+ Response: new(subscriptiontypes.GettableSubscription),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusCreated,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound, http.StatusConflict},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSubscription.Scope(coretypes.VerbCreate)}),
+ }, handler.WithResourceDefs(handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceSubscription,
+ Verb: coretypes.VerbCreate,
+ Category: coretypes.ActionCategoryConfigurationChange,
+ Selector: coretypes.WildcardSelector,
+ }))).Methods(http.MethodPost).GetError(); err != nil {
+ return err
+ }
+
+ if err := router.Handle("/api/v1/subscriptions", handler.New(provider.authzMiddleware.CheckResources(provider.subscriptionHandler.Update, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
+ ID: "UpdateSubscription",
+ Tags: []string{"subscriptions"},
+ Summary: "Update the subscription.",
+ Description: "This endpoint updates the organization's subscription.",
+ Request: new(subscriptiontypes.PostableSubscription),
+ RequestContentType: "application/json",
+ Response: new(subscriptiontypes.GettableSubscription),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSubscription.Scope(coretypes.VerbList), coretypes.ResourceMetaResourceSubscription.Scope(coretypes.VerbUpdate)}),
+ }, handler.WithResourceDefs(
+ handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceSubscription,
+ Verb: coretypes.VerbList,
+ Category: coretypes.ActionCategoryDataAccess,
+ Selector: coretypes.WildcardSelector,
+ },
+ handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceSubscription,
+ Verb: coretypes.VerbUpdate,
+ Category: coretypes.ActionCategoryConfigurationChange,
+ Selector: coretypes.WildcardSelector,
+ },
+ ))).Methods(http.MethodPut).GetError(); err != nil {
+ return err
+ }
+
+ if err := router.Handle("/api/v1/subscriptions", handler.New(provider.authzMiddleware.CheckResources(provider.subscriptionHandler.Get, authtypes.SigNozAdminRoleName), handler.OpenAPIDef{
+ ID: "GetSubscription",
+ Tags: []string{"subscriptions"},
+ Summary: "Get the subscription.",
+ Description: "This endpoint gets the organization's subscription along with its usage and billing details.",
+ Request: nil,
+ RequestContentType: "",
+ Response: new(subscriptiontypes.GettableSubscriptionUsage),
+ ResponseContentType: "application/json",
+ SuccessStatusCode: http.StatusOK,
+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusNotFound},
+ Deprecated: false,
+ SecuritySchemes: newScopedSecuritySchemes([]string{coretypes.ResourceMetaResourceSubscription.Scope(coretypes.VerbRead)}),
+ }, handler.WithResourceDefs(handler.BasicResourceDef{
+ Resource: coretypes.ResourceMetaResourceSubscription,
+ Verb: coretypes.VerbRead,
+ Category: coretypes.ActionCategoryDataAccess,
+ Selector: coretypes.WildcardSelector,
+ }))).Methods(http.MethodGet).GetError(); err != nil {
+ return err
+ }
+
+ return nil
+}
diff --git a/pkg/signoz/handler.go b/pkg/signoz/handler.go
index 3dca50d9b0..f89d3df224 100644
--- a/pkg/signoz/handler.go
+++ b/pkg/signoz/handler.go
@@ -55,6 +55,7 @@ import (
"github.com/SigNoz/signoz/pkg/ruler"
"github.com/SigNoz/signoz/pkg/ruler/signozruler"
"github.com/SigNoz/signoz/pkg/statsreporter"
+ "github.com/SigNoz/signoz/pkg/subscription"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/zeus"
)
@@ -79,6 +80,7 @@ type Handlers struct {
AuthzHandler authz.Handler
ZeusHandler zeus.Handler
LicensingHandler licensing.Handler
+ SubscriptionHandler subscription.Handler
QuerierHandler querier.Handler
ServiceAccountHandler serviceaccount.Handler
RegistryHandler factory.Handler
@@ -105,6 +107,7 @@ func NewHandlers(
telemetryMetadataStore telemetrytypes.MetadataStore,
authz authz.AuthZ,
zeusService zeus.Zeus,
+ subscriptionService subscription.Subscription,
registryHandler factory.Handler,
alertmanagerService alertmanager.Alertmanager,
prometheusService prometheus.Prometheus,
@@ -131,6 +134,7 @@ func NewHandlers(
AuthzHandler: signozauthzapi.NewHandler(authz),
ZeusHandler: zeus.NewHandler(zeusService, licensingService),
LicensingHandler: licensing.NewHandler(licensingService),
+ SubscriptionHandler: subscription.NewHandler(subscriptionService),
QuerierHandler: querierHandler,
ServiceAccountHandler: implserviceaccount.NewHandler(modules.ServiceAccount, modules.ServiceAccountGetter),
RegistryHandler: registryHandler,
diff --git a/pkg/signoz/handler_test.go b/pkg/signoz/handler_test.go
index 9b53f3dedd..afea165f96 100644
--- a/pkg/signoz/handler_test.go
+++ b/pkg/signoz/handler_test.go
@@ -65,7 +65,7 @@ func TestNewHandlers(t *testing.T) {
querierHandler := querier.NewHandler(providerSettings, nil, nil)
registryHandler := factory.NewHandler(nil)
- handlers := NewHandlers(modules, providerSettings, nil, querierHandler, nil, nil, nil, nil, nil, nil, nil, registryHandler, alertmanager, nil, nil, nil)
+ handlers := NewHandlers(modules, providerSettings, nil, querierHandler, nil, nil, nil, nil, nil, nil, nil, nil, registryHandler, alertmanager, nil, nil, nil)
reflectVal := reflect.ValueOf(handlers)
for i := 0; i < reflectVal.NumField(); i++ {
f := reflectVal.Field(i)
diff --git a/pkg/signoz/openapi.go b/pkg/signoz/openapi.go
index 8fe8aaf0c0..c00b9011b7 100644
--- a/pkg/signoz/openapi.go
+++ b/pkg/signoz/openapi.go
@@ -43,6 +43,7 @@ import (
"github.com/SigNoz/signoz/pkg/querier"
"github.com/SigNoz/signoz/pkg/ruler"
"github.com/SigNoz/signoz/pkg/statsreporter"
+ "github.com/SigNoz/signoz/pkg/subscription"
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/zeus"
"github.com/swaggest/jsonschema-go"
@@ -85,6 +86,7 @@ func NewOpenAPI(ctx context.Context, instrumentation instrumentation.Instrumenta
struct{ rawdataexport.Handler }{},
struct{ zeus.Handler }{},
struct{ licensing.Handler }{},
+ struct{ subscription.Handler }{},
struct{ querier.Handler }{},
struct{ serviceaccount.Handler }{},
struct{ serviceaccount.Getter }{},
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index 74fe2b5eb0..fd302cf4bd 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -252,6 +252,7 @@ func NewSQLMigrationProviderFactories(
sqlmigration.NewMigrateQuickFiltersFactory(sqlstore),
sqlmigration.NewAddQuickFilterTuplesFactory(sqlstore),
sqlmigration.NewAddIngestionTuplesFactory(sqlstore),
+ sqlmigration.NewAddSubscriptionTuplesFactory(sqlstore),
)
}
@@ -344,6 +345,7 @@ func NewAPIServerProviderFactories(orgGetter organization.Getter, authz authz.Au
handlers.RawDataExport,
handlers.ZeusHandler,
handlers.LicensingHandler,
+ handlers.SubscriptionHandler,
handlers.QuerierHandler,
handlers.ServiceAccountHandler,
modules.ServiceAccountGetter,
diff --git a/pkg/signoz/signoz.go b/pkg/signoz/signoz.go
index 3fab0be1a9..0ce5f0dbdb 100644
--- a/pkg/signoz/signoz.go
+++ b/pkg/signoz/signoz.go
@@ -56,6 +56,7 @@ import (
"github.com/SigNoz/signoz/pkg/statementbuilder/metricsstatementbuilder"
"github.com/SigNoz/signoz/pkg/statementbuilder/tracesstatementbuilder"
"github.com/SigNoz/signoz/pkg/statsreporter"
+ "github.com/SigNoz/signoz/pkg/subscription"
"github.com/SigNoz/signoz/pkg/telemetrymetadata"
"github.com/SigNoz/signoz/pkg/telemetrystore"
pkgtokenizer "github.com/SigNoz/signoz/pkg/tokenizer"
@@ -168,6 +169,7 @@ func New(
zeusProviderFactory factory.ProviderFactory[zeus.Zeus, zeus.Config],
licenseConfig licensing.Config,
licenseProviderFactory func(sqlstore.SQLStore, zeus.Zeus, organization.Getter, analytics.Analytics) factory.ProviderFactory[licensing.Licensing, licensing.Config],
+ subscriptionCallback func(zeus.Zeus, licensing.Licensing) subscription.Subscription,
emailingProviderFactories factory.NamedMap[factory.ProviderFactory[emailing.Emailing, emailing.Config]],
cacheProviderFactories factory.NamedMap[factory.ProviderFactory[cache.Cache, cache.Config]],
webProviderFactories factory.NamedMap[factory.ProviderFactory[web.Web, web.Config]],
@@ -624,7 +626,9 @@ func New(
// Initialize all handlers for the modules
registryHandler := factory.NewHandler(registry)
- handlers := NewHandlers(modules, providerSettings, analytics, querierHandler, licensing, global, flagger, gateway, telemetryMetadataStore, authz, zeus, registryHandler, alertmanager, prometheus, rulerInstance, statsAggregator)
+ subscriptionService := subscriptionCallback(zeus, licensing)
+
+ handlers := NewHandlers(modules, providerSettings, analytics, querierHandler, licensing, global, flagger, gateway, telemetryMetadataStore, authz, zeus, subscriptionService, registryHandler, alertmanager, prometheus, rulerInstance, statsAggregator)
// Initialize the API server (after registry so it can access service health)
apiserverInstance, err := factory.NewProviderFromNamedMap(
diff --git a/pkg/sqlmigration/125_add_subscription_tuples.go b/pkg/sqlmigration/125_add_subscription_tuples.go
new file mode 100644
index 0000000000..5c63b409ba
--- /dev/null
+++ b/pkg/sqlmigration/125_add_subscription_tuples.go
@@ -0,0 +1,134 @@
+package sqlmigration
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/oklog/ulid/v2"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/dialect"
+ "github.com/uptrace/bun/migrate"
+)
+
+type addSubscriptionTuples struct {
+ sqlstore sqlstore.SQLStore
+}
+
+func NewAddSubscriptionTuplesFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(factory.MustNewName("add_subscription_tuples"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return &addSubscriptionTuples{sqlstore: sqlstore}, nil
+ })
+}
+
+func (migration *addSubscriptionTuples) Register(migrations *migrate.Migrations) error {
+ return migrations.Register(migration.Up, migration.Down)
+}
+
+func (migration *addSubscriptionTuples) Up(ctx context.Context, db *bun.DB) error {
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+ defer func() { _ = tx.Rollback() }()
+
+ var storeID string
+ err = tx.QueryRowContext(ctx, `SELECT id FROM store WHERE name = ? LIMIT 1`, "signoz").Scan(&storeID)
+ if err != nil {
+ return err
+ }
+
+ var orgIDs []string
+ err = tx.NewSelect().
+ Table("organizations").
+ Column("id").
+ Scan(ctx, &orgIDs)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+
+ isPG := migration.sqlstore.BunDB().Dialect().Name() == dialect.PG
+
+ tuples := []migrationTuple{
+ {authtypes.SigNozAdminRoleName, "metaresource", "subscription", "create"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "subscription", "read"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "subscription", "update"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "subscription", "delete"},
+ {authtypes.SigNozAdminRoleName, "metaresource", "subscription", "list"},
+ }
+
+ for _, orgID := range orgIDs {
+ for _, tuple := range tuples {
+ entropy := ulid.DefaultEntropy()
+ now := time.Now().UTC()
+ tupleID := ulid.MustNew(ulid.Timestamp(now), entropy).String()
+
+ objectID := "organization/" + orgID + "/" + tuple.objectName + "/*"
+ roleSubject := "organization/" + orgID + "/role/" + tuple.roleName
+
+ if isPG {
+ user := "role:" + roleSubject + "#assignee"
+ result, err := tx.ExecContext(ctx, `
+ INSERT INTO tuple (store, object_type, object_id, relation, _user, user_type, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, object_type, object_id, relation, _user) DO NOTHING`,
+ storeID, tuple.objectType, objectID, tuple.relation, user, "userset", tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if rowsAffected == 0 {
+ continue
+ }
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO changelog (store, object_type, object_id, relation, _user, operation, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, ulid, object_type) DO NOTHING`,
+ storeID, tuple.objectType, objectID, tuple.relation, user, 0, tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+ } else {
+ result, err := tx.ExecContext(ctx, `
+ INSERT INTO tuple (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, user_type, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation) DO NOTHING`,
+ storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", "userset", tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+ rowsAffected, err := result.RowsAffected()
+ if err != nil {
+ return err
+ }
+ if rowsAffected == 0 {
+ continue
+ }
+ _, err = tx.ExecContext(ctx, `
+ INSERT INTO changelog (store, object_type, object_id, relation, user_object_type, user_object_id, user_relation, operation, ulid, inserted_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
+ ON CONFLICT (store, ulid, object_type) DO NOTHING`,
+ storeID, tuple.objectType, objectID, tuple.relation, "role", roleSubject, "assignee", 0, tupleID, now,
+ )
+ if err != nil {
+ return err
+ }
+ }
+ }
+ }
+
+ return tx.Commit()
+}
+
+func (migration *addSubscriptionTuples) Down(context.Context, *bun.DB) error {
+ return nil
+}
diff --git a/pkg/subscription/handler.go b/pkg/subscription/handler.go
new file mode 100644
index 0000000000..536e259770
--- /dev/null
+++ b/pkg/subscription/handler.go
@@ -0,0 +1,85 @@
+package subscription
+
+import (
+ "net/http"
+
+ "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/subscriptiontypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+type handler struct {
+ subscription Subscription
+}
+
+func NewHandler(subscription Subscription) Handler {
+ return &handler{subscription: subscription}
+}
+
+func (handler *handler) Create(rw http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ req := new(subscriptiontypes.PostableSubscription)
+ if err := binding.JSON.BindBody(r.Body, req); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ gettableSubscription, err := handler.subscription.Create(ctx, valuer.MustNewUUID(claims.OrgID), req)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusCreated, gettableSubscription)
+}
+
+func (handler *handler) Update(rw http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ req := new(subscriptiontypes.PostableSubscription)
+ if err := binding.JSON.BindBody(r.Body, req); err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ gettableSubscription, err := handler.subscription.Update(ctx, valuer.MustNewUUID(claims.OrgID), req)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, gettableSubscription)
+}
+
+func (handler *handler) Get(rw http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+
+ claims, err := authtypes.ClaimsFromContext(ctx)
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ usage, err := handler.subscription.Get(ctx, valuer.MustNewUUID(claims.OrgID))
+ if err != nil {
+ render.Error(rw, err)
+ return
+ }
+
+ render.Success(rw, http.StatusOK, usage)
+}
diff --git a/pkg/subscription/noopsubscription/provider.go b/pkg/subscription/noopsubscription/provider.go
new file mode 100644
index 0000000000..1cc8ea7b8c
--- /dev/null
+++ b/pkg/subscription/noopsubscription/provider.go
@@ -0,0 +1,28 @@
+package noopsubscription
+
+import (
+ "context"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/subscription"
+ "github.com/SigNoz/signoz/pkg/types/subscriptiontypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+type provider struct{}
+
+func New() subscription.Subscription {
+ return &provider{}
+}
+
+func (provider *provider) Create(context.Context, valuer.UUID, *subscriptiontypes.PostableSubscription) (*subscriptiontypes.GettableSubscription, error) {
+ return nil, errors.New(errors.TypeUnsupported, subscription.ErrCodeUnsupported, "creating a subscription is not supported")
+}
+
+func (provider *provider) Update(context.Context, valuer.UUID, *subscriptiontypes.PostableSubscription) (*subscriptiontypes.GettableSubscription, error) {
+ return nil, errors.New(errors.TypeUnsupported, subscription.ErrCodeUnsupported, "updating a subscription is not supported")
+}
+
+func (provider *provider) Get(context.Context, valuer.UUID) (*subscriptiontypes.GettableSubscriptionUsage, error) {
+ return nil, errors.New(errors.TypeUnsupported, subscription.ErrCodeUnsupported, "fetching the subscription is not supported")
+}
diff --git a/pkg/subscription/subscription.go b/pkg/subscription/subscription.go
new file mode 100644
index 0000000000..754962fb01
--- /dev/null
+++ b/pkg/subscription/subscription.go
@@ -0,0 +1,30 @@
+package subscription
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/types/subscriptiontypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
+
+var (
+ ErrCodeUnsupported = errors.MustNewCode("subscription_unsupported")
+)
+
+type Subscription interface {
+ Create(ctx context.Context, organizationID valuer.UUID, postableSubscription *subscriptiontypes.PostableSubscription) (*subscriptiontypes.GettableSubscription, error)
+
+ Update(ctx context.Context, organizationID valuer.UUID, postableSubscription *subscriptiontypes.PostableSubscription) (*subscriptiontypes.GettableSubscription, error)
+
+ Get(ctx context.Context, organizationID valuer.UUID) (*subscriptiontypes.GettableSubscriptionUsage, error)
+}
+
+type Handler interface {
+ Create(http.ResponseWriter, *http.Request)
+
+ Update(http.ResponseWriter, *http.Request)
+
+ Get(http.ResponseWriter, *http.Request)
+}
diff --git a/pkg/types/coretypes/registry_managed_role.go b/pkg/types/coretypes/registry_managed_role.go
index d141075950..d1cb203db3 100644
--- a/pkg/types/coretypes/registry_managed_role.go
+++ b/pkg/types/coretypes/registry_managed_role.go
@@ -74,11 +74,9 @@ var ManagedRoleToTransactions = map[string][]Transaction{
{Verb: VerbCreate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLicense}, WildCardSelectorString)},
{Verb: VerbList, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindLicense}, WildCardSelectorString)},
// subscription — admin only.
- // Uniform LCRUD shape; actual ee routes are POST /api/v1/checkout
- // (create), POST /api/v1/portal (update — opens Stripe portal), GET
- // /api/v1/billing (read — current billing state). delete and list are
- // placeholders for shape parity; cancellation flows through Stripe's
- // portal, no in-process route serves them.
+ // create = POST /api/v1/subscriptions, list + update = PUT /api/v1/subscriptions,
+ // read = GET /api/v1/subscriptions. delete is a placeholder for shape parity;
+ // no in-process route serves it.
{Verb: VerbRead, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSubscription}, WildCardSelectorString)},
{Verb: VerbUpdate, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSubscription}, WildCardSelectorString)},
{Verb: VerbDelete, Object: *MustNewObject(ResourceRef{Type: TypeMetaResource, Kind: KindSubscription}, WildCardSelectorString)},
diff --git a/pkg/types/subscriptiontypes/subscription.go b/pkg/types/subscriptiontypes/subscription.go
new file mode 100644
index 0000000000..af22bece3b
--- /dev/null
+++ b/pkg/types/subscriptiontypes/subscription.go
@@ -0,0 +1,32 @@
+package subscriptiontypes
+
+import (
+ "encoding/json"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+)
+
+type PostableSubscription struct {
+ SuccessURL string `json:"url" required:"true"`
+}
+
+func (postableSubscription *PostableSubscription) UnmarshalJSON(data []byte) error {
+ var raw struct {
+ SuccessURL string `json:"url"`
+ }
+
+ if err := json.Unmarshal(data, &raw); err != nil {
+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "failed to unmarshal payload")
+ }
+
+ if raw.SuccessURL == "" {
+ return errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "success url cannot be empty")
+ }
+
+ postableSubscription.SuccessURL = raw.SuccessURL
+ return nil
+}
+
+type GettableSubscription struct {
+ RedirectURL string `json:"redirectURL" required:"true"`
+}
diff --git a/pkg/types/subscriptiontypes/usage.go b/pkg/types/subscriptiontypes/usage.go
new file mode 100644
index 0000000000..d180ca1dca
--- /dev/null
+++ b/pkg/types/subscriptiontypes/usage.go
@@ -0,0 +1,56 @@
+package subscriptiontypes
+
+import "encoding/json"
+
+type GettableSubscriptionUsage struct {
+ BillingPeriodStart int64 `json:"billingPeriodStart"`
+ BillingPeriodEnd int64 `json:"billingPeriodEnd"`
+ Details SubscriptionUsageDetails `json:"details"`
+ Discount float64 `json:"discount"`
+ SubscriptionStatus string `json:"subscriptionStatus"`
+}
+
+type SubscriptionUsageDetails struct {
+ Total float64 `json:"total"`
+ Breakdown []SubscriptionUsageBreakdown `json:"breakdown"`
+ BaseFee float64 `json:"baseFee"`
+ BillTotal float64 `json:"billTotal"`
+}
+
+type SubscriptionUsageBreakdown struct {
+ Type string `json:"type"`
+ Unit string `json:"unit"`
+ Tiers []SubscriptionUsageTier `json:"tiers"`
+ DayWiseBreakdown SubscriptionUsageDayWiseBreakdown `json:"dayWiseBreakdown"`
+}
+
+type SubscriptionUsageTier struct {
+ UnitPrice float64 `json:"unitPrice"`
+ Quantity float64 `json:"quantity"`
+ TierStart int64 `json:"tierStart"`
+ TierEnd int64 `json:"tierEnd"`
+ TierCost float64 `json:"tierCost"`
+}
+
+type SubscriptionUsageDayWiseBreakdown struct {
+ Type string `json:"type"`
+ Breakdown []SubscriptionUsageDayWiseData `json:"breakdown"`
+}
+
+type SubscriptionUsageDayWiseData struct {
+ Timestamp int64 `json:"timestamp"`
+ Count float64 `json:"count"`
+ Size float64 `json:"size"`
+ UnitPrice float64 `json:"unitPrice"`
+ Quantity float64 `json:"quantity"`
+ Total float64 `json:"total"`
+}
+
+func NewGettableSubscriptionUsage(data []byte) (*GettableSubscriptionUsage, error) {
+ usage := new(GettableSubscriptionUsage)
+ if err := json.Unmarshal(data, usage); err != nil {
+ return nil, err
+ }
+
+ return usage, nil
+}
diff --git a/pkg/zeus/zeus.go b/pkg/zeus/zeus.go
index 3707885932..db4dede963 100644
--- a/pkg/zeus/zeus.go
+++ b/pkg/zeus/zeus.go
@@ -53,12 +53,9 @@ type Zeus interface {
}
type Handler interface {
- // API level handler for PutProfile
PutProfile(http.ResponseWriter, *http.Request)
- // API level handler for getting hosts a slim wrapper around GetDeployment
GetHosts(http.ResponseWriter, *http.Request)
- // API level handler for PutHost
PutHost(http.ResponseWriter, *http.Request)
}