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(infra-monitoring): v2 jobs list api (#11148)
Nikhil Mantri3b9ee4901e49
diff --git a/docs/api/openapi.yml b/docs/api/openapi.ymlindex ea42f20bfc..1168d88fa4 100644--- a/docs/api/openapi.yml+++ b/docs/api/openapi.yml@@ -2728,6 +2728,82 @@ components:- requiredMetricsCheck- endTimeBeforeRetentiontype: object+ InframonitoringtypesJobRecord:+ properties:+ activePods:+ type: integer+ desiredSuccessfulPods:+ type: integer+ failedPods:+ type: integer+ jobCPU:+ format: double+ type: number+ jobCPULimit:+ format: double+ type: number+ jobCPURequest:+ format: double+ type: number+ jobMemory:+ format: double+ type: number+ jobMemoryLimit:+ format: double+ type: number+ jobMemoryRequest:+ format: double+ type: number+ jobName:+ type: string+ meta:+ additionalProperties:+ type: string+ nullable: true+ type: object+ podCountsByPhase:+ $ref: '#/components/schemas/InframonitoringtypesPodCountsByPhase'+ successfulPods:+ type: integer+ required:+ - jobName+ - jobCPU+ - jobCPURequest+ - jobCPULimit+ - jobMemory+ - jobMemoryRequest+ - jobMemoryLimit+ - desiredSuccessfulPods+ - activePods+ - failedPods+ - successfulPods+ - podCountsByPhase+ - meta+ type: object+ InframonitoringtypesJobs:+ properties:+ endTimeBeforeRetention:+ type: boolean+ records:+ items:+ $ref: '#/components/schemas/InframonitoringtypesJobRecord'+ nullable: true+ type: array+ requiredMetricsCheck:+ $ref: '#/components/schemas/InframonitoringtypesRequiredMetricsCheck'+ total:+ type: integer+ type:+ $ref: '#/components/schemas/InframonitoringtypesResponseType'+ warning:+ $ref: '#/components/schemas/Querybuildertypesv5QueryWarnData'+ required:+ - type+ - records+ - total+ - requiredMetricsCheck+ - endTimeBeforeRetention+ type: objectInframonitoringtypesNamespaceRecord:properties:meta:@@ -3031,6 +3107,32 @@ components:- end- limittype: object+ InframonitoringtypesPostableJobs:+ properties:+ end:+ format: int64+ type: integer+ filter:+ $ref: '#/components/schemas/Querybuildertypesv5Filter'+ groupBy:+ items:+ $ref: '#/components/schemas/Querybuildertypesv5GroupByKey'+ nullable: true+ type: array+ limit:+ type: integer+ offset:+ type: integer+ orderBy:+ $ref: '#/components/schemas/Querybuildertypesv5OrderBy'+ start:+ format: int64+ type: integer+ required:+ - start+ - end+ - limit+ type: objectInframonitoringtypesPostableNamespaces:properties:end:@@ -12311,6 +12413,84 @@ paths:summary: List Hosts for Infra Monitoringtags:- inframonitoring+ /api/v2/infra_monitoring/jobs:+ post:+ deprecated: false+ description: 'Returns a paginated list of Kubernetes Jobs with key aggregated+ pod metrics: CPU usage and memory working set summed across pods owned by+ the job, plus average CPU/memory request and limit utilization (jobCPURequest,+ jobCPULimit, jobMemoryRequest, jobMemoryLimit). Each row also reports the+ latest known job-level counters from kube-state-metrics: desiredSuccessfulPods+ (k8s.job.desired_successful_pods, the target completion count), activePods+ (k8s.job.active_pods), failedPods (k8s.job.failed_pods, cumulative across+ the lifetime of the job), and successfulPods (k8s.job.successful_pods, cumulative).+ It also reports per-group podCountsByPhase ({ pending, running, succeeded,+ failed, unknown } from each pod''s latest k8s.pod.phase value); note podCountsByPhase.failed+ (current pod-phase) is distinct from failedPods (cumulative job kube-state-metric).+ Each job includes metadata attributes (k8s.job.name, k8s.namespace.name, k8s.cluster.name).+ The response type is ''list'' for the default k8s.job.name grouping or ''grouped_list''+ for custom groupBy keys; in both modes every row aggregates pods owned by+ jobs in the group. Supports filtering via a filter expression, custom groupBy,+ ordering by cpu / cpu_request / cpu_limit / memory / memory_request / memory_limit+ / desired_successful_pods / active_pods / failed_pods / successful_pods, and+ pagination via offset/limit. Also reports missing required metrics and whether+ the requested time range falls before the data retention boundary. Numeric+ metric fields (jobCPU, jobCPURequest, jobCPULimit, jobMemory, jobMemoryRequest,+ jobMemoryLimit, desiredSuccessfulPods, activePods, failedPods, successfulPods)+ return -1 as a sentinel when no data is available for that field.'+ operationId: ListJobs+ requestBody:+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/InframonitoringtypesPostableJobs'+ responses:+ "200":+ content:+ application/json:+ schema:+ properties:+ data:+ $ref: '#/components/schemas/InframonitoringtypesJobs'+ status:+ type: string+ required:+ - status+ - data+ type: object+ description: OK+ "400":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Bad Request+ "401":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Unauthorized+ "403":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Forbidden+ "500":+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/RenderErrorResponse'+ description: Internal Server Error+ security:+ - api_key:+ - VIEWER+ - tokenizer:+ - VIEWER+ summary: List Jobs for Infra Monitoring+ tags:+ - inframonitoring/api/v2/infra_monitoring/namespaces:post:deprecated: falsediff --git a/frontend/src/api/generated/services/inframonitoring/index.ts b/frontend/src/api/generated/services/inframonitoring/index.tsindex 9b1dd6bc5f..1d9b727b6f 100644--- a/frontend/src/api/generated/services/inframonitoring/index.ts+++ b/frontend/src/api/generated/services/inframonitoring/index.ts@@ -15,6 +15,7 @@ import type {InframonitoringtypesPostableClustersDTO,InframonitoringtypesPostableDeploymentsDTO,InframonitoringtypesPostableHostsDTO,+ InframonitoringtypesPostableJobsDTO,InframonitoringtypesPostableNamespacesDTO,InframonitoringtypesPostableNodesDTO,InframonitoringtypesPostablePodsDTO,@@ -23,6 +24,7 @@ import type {ListClusters200,ListDeployments200,ListHosts200,+ ListJobs200,ListNamespaces200,ListNodes200,ListPods200,@@ -286,6 +288,90 @@ export const useListHosts = <return useMutation(mutationOptions);};+/**+ * Returns a paginated list of Kubernetes Jobs with key aggregated pod metrics: CPU usage and memory working set summed across pods owned by the job, plus average CPU/memory request and limit utilization (jobCPURequest, jobCPULimit, jobMemoryRequest, jobMemoryLimit). Each row also reports the latest known job-level counters from kube-state-metrics: desiredSuccessfulPods (k8s.job.desired_successful_pods, the target completion count), activePods (k8s.job.active_pods), failedPods (k8s.job.failed_pods, cumulative across the lifetime of the job), and successfulPods (k8s.job.successful_pods, cumulative). It also reports per-group podCountsByPhase ({ pending, running, succeeded, failed, unknown } from each pod's latest k8s.pod.phase value); note podCountsByPhase.failed (current pod-phase) is distinct from failedPods (cumulative job kube-state-metric). Each job includes metadata attributes (k8s.job.name, k8s.namespace.name, k8s.cluster.name). The response type is 'list' for the default k8s.job.name grouping or 'grouped_list' for custom groupBy keys; in both modes every row aggregates pods owned by jobs in the group. Supports filtering via a filter expression, custom groupBy, ordering by cpu / cpu_request / cpu_limit / memory / memory_request / memory_limit / desired_successful_pods / active_pods / failed_pods / successful_pods, and pagination via offset/limit. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (jobCPU, jobCPURequest, jobCPULimit, jobMemory, jobMemoryRequest, jobMemoryLimit, desiredSuccessfulPods, activePods, failedPods, successfulPods) return -1 as a sentinel when no data is available for that field.+ * @summary List Jobs for Infra Monitoring+ */+export const listJobs = (+ inframonitoringtypesPostableJobsDTO: BodyType<InframonitoringtypesPostableJobsDTO>,+ signal?: AbortSignal,+) => {+ return GeneratedAPIInstance<ListJobs200>({+ url: `/api/v2/infra_monitoring/jobs`,+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ data: inframonitoringtypesPostableJobsDTO,+ signal,+ });+};++export const getListJobsMutationOptions = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof listJobs>>,+ TError,+ { data: BodyType<InframonitoringtypesPostableJobsDTO> },+ TContext+ >;+}): UseMutationOptions<+ Awaited<ReturnType<typeof listJobs>>,+ TError,+ { data: BodyType<InframonitoringtypesPostableJobsDTO> },+ TContext+> => {+ const mutationKey = ['listJobs'];+ 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 listJobs>>,+ { data: BodyType<InframonitoringtypesPostableJobsDTO> }+ > = (props) => {+ const { data } = props ?? {};++ return listJobs(data);+ };++ return { mutationFn, ...mutationOptions };+};++export type ListJobsMutationResult = NonNullable<+ Awaited<ReturnType<typeof listJobs>>+>;+export type ListJobsMutationBody =+ BodyType<InframonitoringtypesPostableJobsDTO>;+export type ListJobsMutationError = ErrorType<RenderErrorResponseDTO>;++/**+ * @summary List Jobs for Infra Monitoring+ */+export const useListJobs = <+ TError = ErrorType<RenderErrorResponseDTO>,+ TContext = unknown,+>(options?: {+ mutation?: UseMutationOptions<+ Awaited<ReturnType<typeof listJobs>>,+ TError,+ { data: BodyType<InframonitoringtypesPostableJobsDTO> },+ TContext+ >;+}): UseMutationResult<+ Awaited<ReturnType<typeof listJobs>>,+ TError,+ { data: BodyType<InframonitoringtypesPostableJobsDTO> },+ TContext+> => {+ const mutationOptions = getListJobsMutationOptions(options);++ return useMutation(mutationOptions);+};/*** Returns a paginated list of Kubernetes namespaces with key aggregated pod metrics: CPU usage and memory working set (summed across pods in the group), plus per-group podCountsByPhase ({ pending, running, succeeded, failed, unknown } from each pod's latest k8s.pod.phase value in the window). Each namespace includes metadata attributes (k8s.namespace.name, k8s.cluster.name). The response type is 'list' for the default k8s.namespace.name grouping or 'grouped_list' for custom groupBy keys; in both modes every row aggregates pods in the group. Supports filtering via a filter expression, custom groupBy, ordering by cpu / memory, and pagination via offset/limit. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (namespaceCPU, namespaceMemory) return -1 as a sentinel when no data is available for that field.* @summary List Namespaces for Infra Monitoringdiff --git a/frontend/src/api/generated/services/sigNoz.schemas.ts b/frontend/src/api/generated/services/sigNoz.schemas.tsindex 3be6279041..5634d85eb5 100644--- a/frontend/src/api/generated/services/sigNoz.schemas.ts+++ b/frontend/src/api/generated/services/sigNoz.schemas.ts@@ -4790,6 +4790,91 @@ export interface InframonitoringtypesHostsDTO {warning?: Querybuildertypesv5QueryWarnDataDTO;}+/**+ * @nullable+ */+export type InframonitoringtypesJobRecordDTOMeta = {+ [key: string]: string;+} | null;++export interface InframonitoringtypesJobRecordDTO {+ /**+ * @type integer+ */+ activePods: number;+ /**+ * @type integer+ */+ desiredSuccessfulPods: number;+ /**+ * @type integer+ */+ failedPods: number;+ /**+ * @type number+ * @format double+ */+ jobCPU: number;+ /**+ * @type number+ * @format double+ */+ jobCPULimit: number;+ /**+ * @type number+ * @format double+ */+ jobCPURequest: number;+ /**+ * @type number+ * @format double+ */+ jobMemory: number;+ /**+ * @type number+ * @format double+ */+ jobMemoryLimit: number;+ /**+ * @type number+ * @format double+ */+ jobMemoryRequest: number;+ /**+ * @type string+ */+ jobName: string;+ /**+ * @type object+ * @nullable true+ */+ meta: InframonitoringtypesJobRecordDTOMeta;+ podCountsByPhase: InframonitoringtypesPodCountsByPhaseDTO;+ /**+ * @type integer+ */+ successfulPods: number;+}++export interface InframonitoringtypesJobsDTO {+ /**+ * @type boolean+ */+ endTimeBeforeRetention: boolean;+ /**+ * @type array+ * @nullable true+ */+ records: InframonitoringtypesJobRecordDTO[] | null;+ requiredMetricsCheck: InframonitoringtypesRequiredMetricsCheckDTO;+ /**+ * @type integer+ */+ total: number;+ type: InframonitoringtypesResponseTypeDTO;+ warning?: Querybuildertypesv5QueryWarnDataDTO;+}+/*** @nullable*/@@ -5106,6 +5191,34 @@ export interface InframonitoringtypesPostableHostsDTO {start: number;}+export interface InframonitoringtypesPostableJobsDTO {+ /**+ * @type integer+ * @format int64+ */+ end: number;+ filter?: Querybuildertypesv5FilterDTO;+ /**+ * @type array+ * @nullable true+ */+ groupBy?: Querybuildertypesv5GroupByKeyDTO[] | null;+ /**+ * @type integer+ */+ limit: number;+ /**+ * @type integer+ */+ offset?: number;+ orderBy?: Querybuildertypesv5OrderByDTO;+ /**+ * @type integer+ * @format int64+ */+ start: number;+}+export interface InframonitoringtypesPostableNamespacesDTO {/*** @type integer@@ -9735,6 +9848,14 @@ export type ListHosts200 = {status: string;};+export type ListJobs200 = {+ data: InframonitoringtypesJobsDTO;+ /**+ * @type string+ */+ status: string;+};+export type ListNamespaces200 = {data: InframonitoringtypesNamespacesDTO;/**diff --git a/pkg/apiserver/signozapiserver/inframonitoring.go b/pkg/apiserver/signozapiserver/inframonitoring.goindex 70380b87db..3e034f421f 100644--- a/pkg/apiserver/signozapiserver/inframonitoring.go+++ b/pkg/apiserver/signozapiserver/inframonitoring.go@@ -162,5 +162,24 @@ func (provider *provider) addInfraMonitoringRoutes(router *mux.Router) error {return err}+ if err := router.Handle("/api/v2/infra_monitoring/jobs", handler.New(+ provider.authzMiddleware.ViewAccess(provider.infraMonitoringHandler.ListJobs),+ handler.OpenAPIDef{+ ID: "ListJobs",+ Tags: []string{"inframonitoring"},+ Summary: "List Jobs for Infra Monitoring",+ Description: "Returns a paginated list of Kubernetes Jobs with key aggregated pod metrics: CPU usage and memory working set summed across pods owned by the job, plus average CPU/memory request and limit utilization (jobCPURequest, jobCPULimit, jobMemoryRequest, jobMemoryLimit). Each row also reports the latest known job-level counters from kube-state-metrics: desiredSuccessfulPods (k8s.job.desired_successful_pods, the target completion count), activePods (k8s.job.active_pods), failedPods (k8s.job.failed_pods, cumulative across the lifetime of the job), and successfulPods (k8s.job.successful_pods, cumulative). It also reports per-group podCountsByPhase ({ pending, running, succeeded, failed, unknown } from each pod's latest k8s.pod.phase value); note podCountsByPhase.failed (current pod-phase) is distinct from failedPods (cumulative job kube-state-metric). Each job includes metadata attributes (k8s.job.name, k8s.namespace.name, k8s.cluster.name). The response type is 'list' for the default k8s.job.name grouping or 'grouped_list' for custom groupBy keys; in both modes every row aggregates pods owned by jobs in the group. Supports filtering via a filter expression, custom groupBy, ordering by cpu / cpu_request / cpu_limit / memory / memory_request / memory_limit / desired_successful_pods / active_pods / failed_pods / successful_pods, and pagination via offset/limit. Also reports missing required metrics and whether the requested time range falls before the data retention boundary. Numeric metric fields (jobCPU, jobCPURequest, jobCPULimit, jobMemory, jobMemoryRequest, jobMemoryLimit, desiredSuccessfulPods, activePods, failedPods, successfulPods) return -1 as a sentinel when no data is available for that field.",+ Request: new(inframonitoringtypes.PostableJobs),+ RequestContentType: "application/json",+ Response: new(inframonitoringtypes.Jobs),+ ResponseContentType: "application/json",+ SuccessStatusCode: http.StatusOK,+ ErrorStatusCodes: []int{http.StatusBadRequest, http.StatusUnauthorized},+ Deprecated: false,+ SecuritySchemes: newSecuritySchemes(types.RoleViewer),+ })).Methods(http.MethodPost).GetError(); err != nil {+ return err+ }+return nil}diff --git a/pkg/modules/inframonitoring/implinframonitoring/handler.go b/pkg/modules/inframonitoring/implinframonitoring/handler.goindex 0a410743f4..d6b93df1f9 100644--- a/pkg/modules/inframonitoring/implinframonitoring/handler.go+++ b/pkg/modules/inframonitoring/implinframonitoring/handler.go@@ -213,3 +213,27 @@ func (h *handler) ListStatefulSets(rw http.ResponseWriter, req *http.Request) {render.Success(rw, http.StatusOK, result)}++func (h *handler) ListJobs(rw http.ResponseWriter, req *http.Request) {+ claims, err := authtypes.ClaimsFromContext(req.Context())+ if err != nil {+ render.Error(rw, err)+ return+ }++ orgID := valuer.MustNewUUID(claims.OrgID)++ var parsedReq inframonitoringtypes.PostableJobs+ if err := binding.JSON.BindBody(req.Body, &parsedReq); err != nil {+ render.Error(rw, err)+ return+ }++ result, err := h.module.ListJobs(req.Context(), orgID, &parsedReq)+ if err != nil {+ render.Error(rw, err)+ return+ }++ render.Success(rw, http.StatusOK, result)+}diff --git a/pkg/modules/inframonitoring/implinframonitoring/jobs.go b/pkg/modules/inframonitoring/implinframonitoring/jobs.gonew file mode 100644index 0000000000..cb0823a447--- /dev/null+++ b/pkg/modules/inframonitoring/implinframonitoring/jobs.go@@ -0,0 +1,156 @@+package implinframonitoring++import (+ "context"+ "slices"++ "github.com/SigNoz/signoz/pkg/types/inframonitoringtypes"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/valuer"+)++// buildJobRecords assembles the page records. Pod phase counts come from+// phaseCounts in both modes; every row is a group of pods (one job in+// list mode, an arbitrary roll-up in grouped_list mode), so there's no+// per-row "current phase" concept.+func buildJobRecords(+ resp *qbtypes.QueryRangeResponse,+ pageGroups []map[string]string,+ groupBy []qbtypes.GroupByKey,+ metadataMap map[string]map[string]string,+ phaseCounts map[string]podPhaseCounts,+) []inframonitoringtypes.JobRecord {+ metricsMap := parseFullQueryResponse(resp, groupBy)++ records := make([]inframonitoringtypes.JobRecord, 0, len(pageGroups))+ for _, labels := range pageGroups {+ compositeKey := compositeKeyFromLabels(labels, groupBy)+ jobName := labels[jobNameAttrKey]++ record := inframonitoringtypes.JobRecord{ // initialize with default values+ JobName: jobName,+ JobCPU: -1,+ JobCPURequest: -1,+ JobCPULimit: -1,+ JobMemory: -1,+ JobMemoryRequest: -1,+ JobMemoryLimit: -1,+ DesiredSuccessfulPods: -1,+ ActivePods: -1,+ FailedPods: -1,+ SuccessfulPods: -1,+ Meta: map[string]string{},+ }++ if metrics, ok := metricsMap[compositeKey]; ok {+ if v, exists := metrics["A"]; exists {+ record.JobCPU = v+ }+ if v, exists := metrics["B"]; exists {+ record.JobCPURequest = v+ }+ if v, exists := metrics["C"]; exists {+ record.JobCPULimit = v+ }+ if v, exists := metrics["D"]; exists {+ record.JobMemory = v+ }+ if v, exists := metrics["E"]; exists {+ record.JobMemoryRequest = v+ }+ if v, exists := metrics["F"]; exists {+ record.JobMemoryLimit = v+ }+ if v, exists := metrics["H"]; exists {+ record.DesiredSuccessfulPods = int(v)+ }+ if v, exists := metrics["I"]; exists {+ record.ActivePods = int(v)+ }+ if v, exists := metrics["J"]; exists {+ record.FailedPods = int(v)+ }+ if v, exists := metrics["K"]; exists {+ record.SuccessfulPods = int(v)+ }+ }++ if phaseCountsForGroup, ok := phaseCounts[compositeKey]; ok {+ record.PodCountsByPhase = inframonitoringtypes.PodCountsByPhase{+ Pending: phaseCountsForGroup.Pending,+ Running: phaseCountsForGroup.Running,+ Succeeded: phaseCountsForGroup.Succeeded,+ Failed: phaseCountsForGroup.Failed,+ Unknown: phaseCountsForGroup.Unknown,+ }+ }++ if attrs, ok := metadataMap[compositeKey]; ok {+ for k, v := range attrs {+ record.Meta[k] = v+ }+ }++ records = append(records, record)+ }+ return records+}++func (m *module) getTopJobGroups(+ ctx context.Context,+ orgID valuer.UUID,+ req *inframonitoringtypes.PostableJobs,+ metadataMap map[string]map[string]string,+) ([]map[string]string, error) {+ orderByKey := req.OrderBy.Key.Name+ queryNamesForOrderBy := orderByToJobsQueryNames[orderByKey]+ rankingQueryName := queryNamesForOrderBy[len(queryNamesForOrderBy)-1]++ topReq := &qbtypes.QueryRangeRequest{+ Start: uint64(req.Start),+ End: uint64(req.End),+ RequestType: qbtypes.RequestTypeScalar,+ CompositeQuery: qbtypes.CompositeQuery{+ Queries: make([]qbtypes.QueryEnvelope, 0, len(queryNamesForOrderBy)),+ },+ }++ for _, envelope := range m.newJobsTableListQuery().CompositeQuery.Queries {+ if !slices.Contains(queryNamesForOrderBy, envelope.GetQueryName()) {+ continue+ }+ copied := envelope+ if copied.Type == qbtypes.QueryTypeBuilder {+ existingExpr := ""+ if f := copied.GetFilter(); f != nil {+ existingExpr = f.Expression+ }+ reqFilterExpr := ""+ if req.Filter != nil {+ reqFilterExpr = req.Filter.Expression+ }+ merged := mergeFilterExpressions(existingExpr, reqFilterExpr)+ copied.SetFilter(&qbtypes.Filter{Expression: merged})+ copied.SetGroupBy(req.GroupBy)+ }+ topReq.CompositeQuery.Queries = append(topReq.CompositeQuery.Queries, copied)+ }++ resp, err := m.querier.QueryRange(ctx, orgID, topReq)+ if err != nil {+ return nil, err+ }++ allMetricGroups := parseAndSortGroups(resp, rankingQueryName, req.GroupBy, req.OrderBy.Direction)+ return paginateWithBackfill(allMetricGroups, metadataMap, req.GroupBy, req.Offset, req.Limit), nil+}++func (m *module) getJobsTableMetadata(ctx context.Context, req *inframonitoringtypes.PostableJobs) (map[string]map[string]string, error) {+ var nonGroupByAttrs []string+ for _, key := range jobAttrKeysForMetadata {+ if !isKeyInGroupByAttrs(req.GroupBy, key) {+ nonGroupByAttrs = append(nonGroupByAttrs, key)+ }+ }+ return m.getMetadata(ctx, jobsTableMetricNamesList, req.GroupBy, nonGroupByAttrs, req.Filter, req.Start, req.End)+}diff --git a/pkg/modules/inframonitoring/implinframonitoring/jobs_constants.go b/pkg/modules/inframonitoring/implinframonitoring/jobs_constants.gonew file mode 100644index 0000000000..483c97ddb2--- /dev/null+++ b/pkg/modules/inframonitoring/implinframonitoring/jobs_constants.go@@ -0,0 +1,278 @@+package implinframonitoring++import (+ "github.com/SigNoz/signoz/pkg/types/inframonitoringtypes"+ "github.com/SigNoz/signoz/pkg/types/metrictypes"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+)++const (+ jobNameAttrKey = "k8s.job.name"+ jobsBaseFilterExpr = "k8s.job.name != ''"+)++var jobNameGroupByKey = qbtypes.GroupByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: jobNameAttrKey,+ FieldContext: telemetrytypes.FieldContextResource,+ FieldDataType: telemetrytypes.FieldDataTypeString,+ },+}++// jobsTableMetricNamesList drives the existence/retention check.+// Includes k8s.pod.phase even though phase isn't part of the QB composite query —+// it is queried separately via getPerGroupPodPhaseCounts, and we want the+// response to short-circuit cleanly when the phase metric is absent.+var jobsTableMetricNamesList = []string{+ "k8s.pod.phase",+ "k8s.pod.cpu.usage",+ "k8s.pod.cpu_request_utilization",+ "k8s.pod.cpu_limit_utilization",+ "k8s.pod.memory.working_set",+ "k8s.pod.memory_request_utilization",+ "k8s.pod.memory_limit_utilization",+ "k8s.job.active_pods",+ "k8s.job.failed_pods",+ "k8s.job.successful_pods",+ "k8s.job.desired_successful_pods",+}++// Carried forward from v1 jobAttrsToEnrich+// (pkg/query-service/app/inframetrics/jobs.go:31-35).+var jobAttrKeysForMetadata = []string{+ "k8s.job.name",+ "k8s.namespace.name",+ "k8s.cluster.name",+}++// orderByToJobsQueryNames maps the orderBy column to the query name+// used for ranking job groups. v2 B/C/E/F are direct metrics, no+// formula deps — so unlike v1 we don't carry A/D.+var orderByToJobsQueryNames = map[string][]string{+ inframonitoringtypes.JobsOrderByCPU: {"A"},+ inframonitoringtypes.JobsOrderByCPURequest: {"B"},+ inframonitoringtypes.JobsOrderByCPULimit: {"C"},+ inframonitoringtypes.JobsOrderByMemory: {"D"},+ inframonitoringtypes.JobsOrderByMemoryRequest: {"E"},+ inframonitoringtypes.JobsOrderByMemoryLimit: {"F"},+ inframonitoringtypes.JobsOrderByDesiredSuccessfulPods: {"H"},+ inframonitoringtypes.JobsOrderByActivePods: {"I"},+ inframonitoringtypes.JobsOrderByFailedPods: {"J"},+ inframonitoringtypes.JobsOrderBySuccessfulPods: {"K"},+}++// newJobsTableListQuery builds the composite QB v5 request for the jobs list.+// Ten builder queries: A..F roll up pod-level metrics by job, H/I/J/K take the+// latest job-level desired/active/failed/successful counts. Restarts (v1 query G)+// is intentionally omitted to match the v2 pods/deployments pattern.+//+// Every builder query carries the base filter `jobsBaseFilterExpr`. Reason:+// pod-level metrics (A..F) are emitted for every pod regardless of whether the+// pod belongs to a Job; only Job-owned pods carry the `k8s.job.name` resource+// attribute. Without this filter, standalone pods and pods owned by other+// workloads (Deployment/StatefulSet/DaemonSet/...) collapse into a single+// empty-string group under the default groupBy.+func (m *module) newJobsTableListQuery() *qbtypes.QueryRangeRequest {+ queries := []qbtypes.QueryEnvelope{+ // Query A: k8s.pod.cpu.usage — sum of pod CPU within the group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "A",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.pod.cpu.usage",+ TimeAggregation: metrictypes.TimeAggregationAvg,+ SpaceAggregation: metrictypes.SpaceAggregationSum,+ ReduceTo: qbtypes.ReduceToAvg,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query B: k8s.pod.cpu_request_utilization — avg across pods in the group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "B",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.pod.cpu_request_utilization",+ TimeAggregation: metrictypes.TimeAggregationAvg,+ SpaceAggregation: metrictypes.SpaceAggregationAvg,+ ReduceTo: qbtypes.ReduceToAvg,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query C: k8s.pod.cpu_limit_utilization — avg across pods in the group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "C",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.pod.cpu_limit_utilization",+ TimeAggregation: metrictypes.TimeAggregationAvg,+ SpaceAggregation: metrictypes.SpaceAggregationAvg,+ ReduceTo: qbtypes.ReduceToAvg,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query D: k8s.pod.memory.working_set — sum of pod memory within the group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "D",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.pod.memory.working_set",+ TimeAggregation: metrictypes.TimeAggregationAvg,+ SpaceAggregation: metrictypes.SpaceAggregationSum,+ ReduceTo: qbtypes.ReduceToAvg,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query E: k8s.pod.memory_request_utilization — avg across pods in the group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "E",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.pod.memory_request_utilization",+ TimeAggregation: metrictypes.TimeAggregationAvg,+ SpaceAggregation: metrictypes.SpaceAggregationAvg,+ ReduceTo: qbtypes.ReduceToAvg,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query F: k8s.pod.memory_limit_utilization — avg across pods in the group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "F",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.pod.memory_limit_utilization",+ TimeAggregation: metrictypes.TimeAggregationAvg,+ SpaceAggregation: metrictypes.SpaceAggregationAvg,+ ReduceTo: qbtypes.ReduceToAvg,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query H: k8s.job.desired_successful_pods — latest known desired completion count per group.+ // v1 used TimeAggregationAnyLast (v3) → mapped to TimeAggregationLatest in v5;+ // SpaceAggregationSum + ReduceToLast preserve v1's "latest, summed across the group".+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "H",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.job.desired_successful_pods",+ TimeAggregation: metrictypes.TimeAggregationLatest,+ SpaceAggregation: metrictypes.SpaceAggregationSum,+ ReduceTo: qbtypes.ReduceToLast,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query I: k8s.job.active_pods — latest known active pod count per group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "I",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.job.active_pods",+ TimeAggregation: metrictypes.TimeAggregationLatest,+ SpaceAggregation: metrictypes.SpaceAggregationSum,+ ReduceTo: qbtypes.ReduceToLast,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query J: k8s.job.failed_pods — cumulative failed pod count per group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "J",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.job.failed_pods",+ TimeAggregation: metrictypes.TimeAggregationLatest,+ SpaceAggregation: metrictypes.SpaceAggregationSum,+ ReduceTo: qbtypes.ReduceToLast,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ // Query K: k8s.job.successful_pods — cumulative successful pod count per group.+ {+ Type: qbtypes.QueryTypeBuilder,+ Spec: qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]{+ Name: "K",+ Signal: telemetrytypes.SignalMetrics,+ Aggregations: []qbtypes.MetricAggregation{+ {+ MetricName: "k8s.job.successful_pods",+ TimeAggregation: metrictypes.TimeAggregationLatest,+ SpaceAggregation: metrictypes.SpaceAggregationSum,+ ReduceTo: qbtypes.ReduceToLast,+ },+ },+ Filter: &qbtypes.Filter{Expression: jobsBaseFilterExpr},+ GroupBy: []qbtypes.GroupByKey{jobNameGroupByKey},+ Disabled: false,+ },+ },+ }++ return &qbtypes.QueryRangeRequest{+ RequestType: qbtypes.RequestTypeScalar,+ CompositeQuery: qbtypes.CompositeQuery{+ Queries: queries,+ },+ }+}diff --git a/pkg/modules/inframonitoring/implinframonitoring/module.go b/pkg/modules/inframonitoring/implinframonitoring/module.goindex ae56e0a608..4c1ae0a014 100644--- a/pkg/modules/inframonitoring/implinframonitoring/module.go+++ b/pkg/modules/inframonitoring/implinframonitoring/module.go@@ -803,3 +803,100 @@ func (m *module) ListStatefulSets(ctx context.Context, orgID valuer.UUID, req *ireturn resp, nil}++func (m *module) ListJobs(ctx context.Context, orgID valuer.UUID, req *inframonitoringtypes.PostableJobs) (*inframonitoringtypes.Jobs, error) {+ if err := req.Validate(); err != nil {+ return nil, err+ }++ resp := &inframonitoringtypes.Jobs{}++ if req.OrderBy == nil {+ req.OrderBy = &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: inframonitoringtypes.JobsOrderByCPU,+ },+ },+ Direction: qbtypes.OrderDirectionDesc,+ }+ }++ if len(req.GroupBy) == 0 {+ req.GroupBy = []qbtypes.GroupByKey{jobNameGroupByKey}+ resp.Type = inframonitoringtypes.ResponseTypeList+ } else {+ resp.Type = inframonitoringtypes.ResponseTypeGroupedList+ }++ // Bake the jobs base filter into req.Filter so all downstream helpers pick it up.+ if req.Filter == nil {+ req.Filter = &qbtypes.Filter{}+ }+ req.Filter.Expression = mergeFilterExpressions(jobsBaseFilterExpr, req.Filter.Expression)++ missingMetrics, minFirstReportedUnixMilli, err := m.getMetricsExistenceAndEarliestTime(ctx, jobsTableMetricNamesList)+ if err != nil {+ return nil, err+ }+ if len(missingMetrics) > 0 {+ resp.RequiredMetricsCheck = inframonitoringtypes.RequiredMetricsCheck{MissingMetrics: missingMetrics}+ resp.Records = []inframonitoringtypes.JobRecord{}+ resp.Total = 0+ return resp, nil+ }+ if req.End < int64(minFirstReportedUnixMilli) {+ resp.EndTimeBeforeRetention = true+ resp.Records = []inframonitoringtypes.JobRecord{}+ resp.Total = 0+ return resp, nil+ }+ resp.RequiredMetricsCheck = inframonitoringtypes.RequiredMetricsCheck{MissingMetrics: []string{}}++ metadataMap, err := m.getJobsTableMetadata(ctx, req)+ if err != nil {+ return nil, err+ }++ resp.Total = len(metadataMap)++ pageGroups, err := m.getTopJobGroups(ctx, orgID, req, metadataMap)+ if err != nil {+ return nil, err+ }++ if len(pageGroups) == 0 {+ resp.Records = []inframonitoringtypes.JobRecord{}+ return resp, nil+ }++ filterExpr := ""+ if req.Filter != nil {+ filterExpr = req.Filter.Expression+ }++ fullQueryReq := buildFullQueryRequest(req.Start, req.End, filterExpr, req.GroupBy, pageGroups, m.newJobsTableListQuery())+ queryResp, err := m.querier.QueryRange(ctx, orgID, fullQueryReq)+ if err != nil {+ return nil, err+ }++ // Reuse the pods phase-counts CTE function via a temp struct — it reads only+ // Start/End/Filter/GroupBy from PostablePods. Pods owned by a Job carry+ // k8s.job.name as a resource attribute, so default-groupBy gives+ // per-job phase counts automatically.+ phaseCounts, err := m.getPerGroupPodPhaseCounts(ctx, &inframonitoringtypes.PostablePods{+ Start: req.Start,+ End: req.End,+ Filter: req.Filter,+ GroupBy: req.GroupBy,+ }, pageGroups)+ if err != nil {+ return nil, err+ }++ resp.Records = buildJobRecords(queryResp, pageGroups, req.GroupBy, metadataMap, phaseCounts)+ resp.Warning = queryResp.Warning++ return resp, nil+}diff --git a/pkg/modules/inframonitoring/inframonitoring.go b/pkg/modules/inframonitoring/inframonitoring.goindex a5feb7e8ad..74e0151e8d 100644--- a/pkg/modules/inframonitoring/inframonitoring.go+++ b/pkg/modules/inframonitoring/inframonitoring.go@@ -17,6 +17,7 @@ type Handler interface {ListVolumes(http.ResponseWriter, *http.Request)ListDeployments(http.ResponseWriter, *http.Request)ListStatefulSets(http.ResponseWriter, *http.Request)+ ListJobs(http.ResponseWriter, *http.Request)}type Module interface {@@ -28,4 +29,5 @@ type Module interface {ListVolumes(ctx context.Context, orgID valuer.UUID, req *inframonitoringtypes.PostableVolumes) (*inframonitoringtypes.Volumes, error)ListDeployments(ctx context.Context, orgID valuer.UUID, req *inframonitoringtypes.PostableDeployments) (*inframonitoringtypes.Deployments, error)ListStatefulSets(ctx context.Context, orgID valuer.UUID, req *inframonitoringtypes.PostableStatefulSets) (*inframonitoringtypes.StatefulSets, error)+ ListJobs(ctx context.Context, orgID valuer.UUID, req *inframonitoringtypes.PostableJobs) (*inframonitoringtypes.Jobs, error)}diff --git a/pkg/types/inframonitoringtypes/jobs.go b/pkg/types/inframonitoringtypes/jobs.gonew file mode 100644index 0000000000..7c8892c9c6--- /dev/null+++ b/pkg/types/inframonitoringtypes/jobs.go@@ -0,0 +1,107 @@+package inframonitoringtypes++import (+ "encoding/json"+ "slices"++ "github.com/SigNoz/signoz/pkg/errors"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+)++type Jobs struct {+ Type ResponseType `json:"type" required:"true"`+ Records []JobRecord `json:"records" required:"true"`+ Total int `json:"total" required:"true"`+ RequiredMetricsCheck RequiredMetricsCheck `json:"requiredMetricsCheck" required:"true"`+ EndTimeBeforeRetention bool `json:"endTimeBeforeRetention" required:"true"`+ Warning *qbtypes.QueryWarnData `json:"warning,omitempty"`+}++type JobRecord struct {+ JobName string `json:"jobName" required:"true"`+ JobCPU float64 `json:"jobCPU" required:"true"`+ JobCPURequest float64 `json:"jobCPURequest" required:"true"`+ JobCPULimit float64 `json:"jobCPULimit" required:"true"`+ JobMemory float64 `json:"jobMemory" required:"true"`+ JobMemoryRequest float64 `json:"jobMemoryRequest" required:"true"`+ JobMemoryLimit float64 `json:"jobMemoryLimit" required:"true"`+ DesiredSuccessfulPods int `json:"desiredSuccessfulPods" required:"true"`+ ActivePods int `json:"activePods" required:"true"`+ FailedPods int `json:"failedPods" required:"true"`+ SuccessfulPods int `json:"successfulPods" required:"true"`+ PodCountsByPhase PodCountsByPhase `json:"podCountsByPhase" required:"true"`+ Meta map[string]string `json:"meta" required:"true"`+}++// PostableJobs is the request body for the v2 jobs list API.+type PostableJobs struct {+ Start int64 `json:"start" required:"true"`+ End int64 `json:"end" required:"true"`+ Filter *qbtypes.Filter `json:"filter"`+ GroupBy []qbtypes.GroupByKey `json:"groupBy"`+ OrderBy *qbtypes.OrderBy `json:"orderBy"`+ Offset int `json:"offset"`+ Limit int `json:"limit" required:"true"`+}++// Validate ensures PostableJobs contains acceptable values.+func (req *PostableJobs) Validate() error {+ if req == nil {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "request is nil")+ }++ if req.Start <= 0 {+ return errors.NewInvalidInputf(+ errors.CodeInvalidInput,+ "invalid start time %d: start must be greater than 0",+ req.Start,+ )+ }++ if req.End <= 0 {+ return errors.NewInvalidInputf(+ errors.CodeInvalidInput,+ "invalid end time %d: end must be greater than 0",+ req.End,+ )+ }++ if req.Start >= req.End {+ return errors.NewInvalidInputf(+ errors.CodeInvalidInput,+ "invalid time range: start (%d) must be less than end (%d)",+ req.Start,+ req.End,+ )+ }++ if req.Limit < 1 || req.Limit > 5000 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "limit must be between 1 and 5000")+ }++ if req.Offset < 0 {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "offset cannot be negative")+ }++ if req.OrderBy != nil {+ if !slices.Contains(JobsValidOrderByKeys, req.OrderBy.Key.Name) {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid order by key: %s", req.OrderBy.Key.Name)+ }+ if req.OrderBy.Direction != qbtypes.OrderDirectionAsc && req.OrderBy.Direction != qbtypes.OrderDirectionDesc {+ return errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid order by direction: %s", req.OrderBy.Direction)+ }+ }++ return nil+}++// UnmarshalJSON validates input immediately after decoding.+func (req *PostableJobs) UnmarshalJSON(data []byte) error {+ type raw PostableJobs+ var decoded raw+ if err := json.Unmarshal(data, &decoded); err != nil {+ return err+ }+ *req = PostableJobs(decoded)+ return req.Validate()+}diff --git a/pkg/types/inframonitoringtypes/jobs_constants.go b/pkg/types/inframonitoringtypes/jobs_constants.gonew file mode 100644index 0000000000..6e7008dd4d--- /dev/null+++ b/pkg/types/inframonitoringtypes/jobs_constants.go@@ -0,0 +1,27 @@+package inframonitoringtypes++const (+ JobsOrderByCPU = "cpu"+ JobsOrderByCPURequest = "cpu_request"+ JobsOrderByCPULimit = "cpu_limit"+ JobsOrderByMemory = "memory"+ JobsOrderByMemoryRequest = "memory_request"+ JobsOrderByMemoryLimit = "memory_limit"+ JobsOrderByDesiredSuccessfulPods = "desired_successful_pods"+ JobsOrderByActivePods = "active_pods"+ JobsOrderByFailedPods = "failed_pods"+ JobsOrderBySuccessfulPods = "successful_pods"+)++var JobsValidOrderByKeys = []string{+ JobsOrderByCPU,+ JobsOrderByCPURequest,+ JobsOrderByCPULimit,+ JobsOrderByMemory,+ JobsOrderByMemoryRequest,+ JobsOrderByMemoryLimit,+ JobsOrderByDesiredSuccessfulPods,+ JobsOrderByActivePods,+ JobsOrderByFailedPods,+ JobsOrderBySuccessfulPods,+}diff --git a/pkg/types/inframonitoringtypes/jobs_test.go b/pkg/types/inframonitoringtypes/jobs_test.gonew file mode 100644index 0000000000..edb49b25da--- /dev/null+++ b/pkg/types/inframonitoringtypes/jobs_test.go@@ -0,0 +1,309 @@+package inframonitoringtypes++import (+ "testing"++ "github.com/SigNoz/signoz/pkg/errors"+ qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"+ "github.com/SigNoz/signoz/pkg/types/telemetrytypes"+ "github.com/SigNoz/signoz/pkg/valuer"+ "github.com/stretchr/testify/require"+)++func TestPostableJobs_Validate(t *testing.T) {+ tests := []struct {+ name string+ req *PostableJobs+ wantErr bool+ }{+ {+ name: "valid request",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ },+ wantErr: false,+ },+ {+ name: "nil request",+ req: nil,+ wantErr: true,+ },+ {+ name: "start time zero",+ req: &PostableJobs{+ Start: 0,+ End: 2000,+ Limit: 100,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "start time negative",+ req: &PostableJobs{+ Start: -1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "end time zero",+ req: &PostableJobs{+ Start: 1000,+ End: 0,+ Limit: 100,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "start time greater than end time",+ req: &PostableJobs{+ Start: 2000,+ End: 1000,+ Limit: 100,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "start time equal to end time",+ req: &PostableJobs{+ Start: 1000,+ End: 1000,+ Limit: 100,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "limit zero",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 0,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "limit negative",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: -10,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "limit exceeds max",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 5001,+ Offset: 0,+ },+ wantErr: true,+ },+ {+ name: "offset negative",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: -5,+ },+ wantErr: true,+ },+ {+ name: "orderBy nil is valid",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ },+ wantErr: false,+ },+ {+ name: "orderBy with valid key cpu and direction asc",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: JobsOrderByCPU,+ },+ },+ Direction: qbtypes.OrderDirectionAsc,+ },+ },+ wantErr: false,+ },+ {+ name: "orderBy with valid key memory_limit and direction desc",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: JobsOrderByMemoryLimit,+ },+ },+ Direction: qbtypes.OrderDirectionDesc,+ },+ },+ wantErr: false,+ },+ {+ name: "orderBy with valid key desired_successful_pods and direction desc",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: JobsOrderByDesiredSuccessfulPods,+ },+ },+ Direction: qbtypes.OrderDirectionDesc,+ },+ },+ wantErr: false,+ },+ {+ name: "orderBy with valid key active_pods and direction asc",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: JobsOrderByActivePods,+ },+ },+ Direction: qbtypes.OrderDirectionAsc,+ },+ },+ wantErr: false,+ },+ {+ name: "orderBy with valid key failed_pods",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: JobsOrderByFailedPods,+ },+ },+ Direction: qbtypes.OrderDirectionDesc,+ },+ },+ wantErr: false,+ },+ {+ name: "orderBy with valid key successful_pods",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: JobsOrderBySuccessfulPods,+ },+ },+ Direction: qbtypes.OrderDirectionDesc,+ },+ },+ wantErr: false,+ },+ {+ name: "orderBy with restarts key is rejected",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: "restarts",+ },+ },+ Direction: qbtypes.OrderDirectionDesc,+ },+ },+ wantErr: true,+ },+ {+ name: "orderBy with invalid key",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: "unknown",+ },+ },+ Direction: qbtypes.OrderDirectionDesc,+ },+ },+ wantErr: true,+ },+ {+ name: "orderBy with valid key but invalid direction",+ req: &PostableJobs{+ Start: 1000,+ End: 2000,+ Limit: 100,+ Offset: 0,+ OrderBy: &qbtypes.OrderBy{+ Key: qbtypes.OrderByKey{+ TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{+ Name: JobsOrderByCPU,+ },+ },+ Direction: qbtypes.OrderDirection{String: valuer.NewString("invalid")},+ },+ },+ wantErr: true,+ },+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ err := tt.req.Validate()+ if tt.wantErr {+ require.Error(t, err)+ require.True(t, errors.Ast(err, errors.TypeInvalidInput), "expected error to be of type InvalidInput")+ } else {+ require.NoError(t, err)+ }+ })+ }+}