mirror of
https://github.com/SigNoz/signoz.git
synced 2026-02-20 15:52:41 +00:00
Compare commits
3 Commits
merge-json
...
fix/chart-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
41f5f6e421 | ||
|
|
da2e050a23 | ||
|
|
5a69f16410 |
@@ -2,11 +2,9 @@ package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"time"
|
||||
|
||||
"github.com/SigNoz/signoz/ee/licensing/httplicensing"
|
||||
"github.com/SigNoz/signoz/ee/query-service/integrations/gateway"
|
||||
"github.com/SigNoz/signoz/ee/query-service/usage"
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager"
|
||||
"github.com/SigNoz/signoz/pkg/global"
|
||||
@@ -31,7 +29,6 @@ type APIHandlerOptions struct {
|
||||
IntegrationsController *integrations.Controller
|
||||
CloudIntegrationsController *cloudintegrations.Controller
|
||||
LogsParsingPipelineController *logparsingpipeline.LogParsingPipelineController
|
||||
Gateway *httputil.ReverseProxy
|
||||
GatewayUrl string
|
||||
// Querier Influx Interval
|
||||
FluxInterval time.Duration
|
||||
@@ -77,10 +74,6 @@ func (ah *APIHandler) UM() *usage.Manager {
|
||||
return ah.opts.UsageManager
|
||||
}
|
||||
|
||||
func (ah *APIHandler) Gateway() *httputil.ReverseProxy {
|
||||
return ah.opts.Gateway
|
||||
}
|
||||
|
||||
// RegisterRoutes registers routes for this handler on the given router
|
||||
func (ah *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {
|
||||
// note: add ee override methods first
|
||||
@@ -103,9 +96,6 @@ func (ah *APIHandler) RegisterRoutes(router *mux.Router, am *middleware.AuthZ) {
|
||||
// v4
|
||||
router.HandleFunc("/api/v4/query_range", am.ViewAccess(ah.queryRangeV4)).Methods(http.MethodPost)
|
||||
|
||||
// Gateway
|
||||
router.PathPrefix(gateway.RoutePrefix).HandlerFunc(am.EditAccess(ah.ServeGatewayHTTP))
|
||||
|
||||
ah.APIHandler.RegisterRoutes(router, am)
|
||||
|
||||
}
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/SigNoz/signoz/ee/query-service/integrations/gateway"
|
||||
"github.com/SigNoz/signoz/pkg/errors"
|
||||
"github.com/SigNoz/signoz/pkg/http/render"
|
||||
"github.com/SigNoz/signoz/pkg/types/authtypes"
|
||||
"github.com/SigNoz/signoz/pkg/valuer"
|
||||
)
|
||||
|
||||
func (ah *APIHandler) ServeGatewayHTTP(rw http.ResponseWriter, req *http.Request) {
|
||||
ctx := req.Context()
|
||||
claims, err := authtypes.ClaimsFromContext(ctx)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
orgID, err := valuer.NewUUID(claims.OrgID)
|
||||
if err != nil {
|
||||
render.Error(rw, errors.Newf(errors.TypeInvalidInput, errors.CodeInvalidInput, "orgId is invalid"))
|
||||
return
|
||||
}
|
||||
|
||||
validPath := false
|
||||
for _, allowedPrefix := range gateway.AllowedPrefix {
|
||||
if strings.HasPrefix(req.URL.Path, gateway.RoutePrefix+allowedPrefix) {
|
||||
validPath = true
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if !validPath {
|
||||
rw.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
license, err := ah.Signoz.Licensing.GetActive(ctx, orgID)
|
||||
if err != nil {
|
||||
render.Error(rw, err)
|
||||
return
|
||||
}
|
||||
|
||||
//Create headers
|
||||
var licenseKey string
|
||||
if license != nil {
|
||||
licenseKey = license.Key
|
||||
}
|
||||
|
||||
req.Header.Set("X-Signoz-Cloud-Api-Key", licenseKey)
|
||||
req.Header.Set("X-Consumer-Username", "lid:00000000-0000-0000-0000-000000000000")
|
||||
req.Header.Set("X-Consumer-Groups", "ns:default")
|
||||
|
||||
ah.Gateway().ServeHTTP(rw, req)
|
||||
}
|
||||
@@ -19,7 +19,6 @@ import (
|
||||
"github.com/gorilla/handlers"
|
||||
|
||||
"github.com/SigNoz/signoz/ee/query-service/app/api"
|
||||
"github.com/SigNoz/signoz/ee/query-service/integrations/gateway"
|
||||
"github.com/SigNoz/signoz/ee/query-service/rules"
|
||||
"github.com/SigNoz/signoz/ee/query-service/usage"
|
||||
"github.com/SigNoz/signoz/pkg/alertmanager"
|
||||
@@ -72,11 +71,6 @@ type Server struct {
|
||||
|
||||
// NewServer creates and initializes Server
|
||||
func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {
|
||||
gatewayProxy, err := gateway.NewProxy(config.Gateway.URL.String(), gateway.RoutePrefix)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
cacheForTraceDetail, err := memorycache.New(context.TODO(), signoz.Instrumentation.ToProviderSettings(), cache.Config{
|
||||
Provider: "memory",
|
||||
Memory: cache.Memory{
|
||||
@@ -170,7 +164,6 @@ func NewServer(config signoz.Config, signoz *signoz.SigNoz) (*Server, error) {
|
||||
CloudIntegrationsController: cloudIntegrationsController,
|
||||
LogsParsingPipelineController: logParsingPipelineController,
|
||||
FluxInterval: config.Querier.FluxInterval,
|
||||
Gateway: gatewayProxy,
|
||||
GatewayUrl: config.Gateway.URL.String(),
|
||||
GlobalConfig: config.Global,
|
||||
}
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http/httputil"
|
||||
)
|
||||
|
||||
func NewNoopProxy() (*httputil.ReverseProxy, error) {
|
||||
return &httputil.ReverseProxy{}, nil
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"path"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var (
|
||||
RoutePrefix string = "/api/gateway"
|
||||
AllowedPrefix []string = []string{"/v1/workspaces/me", "/v2/profiles/me", "/v2/deployments/me"}
|
||||
)
|
||||
|
||||
type proxy struct {
|
||||
url *url.URL
|
||||
stripPath string
|
||||
}
|
||||
|
||||
func NewProxy(u string, stripPath string) (*httputil.ReverseProxy, error) {
|
||||
url, err := url.Parse(u)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
proxy := &proxy{url: url, stripPath: stripPath}
|
||||
|
||||
return &httputil.ReverseProxy{
|
||||
Rewrite: proxy.rewrite,
|
||||
ModifyResponse: proxy.modifyResponse,
|
||||
ErrorHandler: proxy.errorHandler,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *proxy) rewrite(pr *httputil.ProxyRequest) {
|
||||
pr.SetURL(p.url)
|
||||
pr.SetXForwarded()
|
||||
pr.Out.URL.Path = cleanPath(strings.ReplaceAll(pr.Out.URL.Path, p.stripPath, ""))
|
||||
}
|
||||
|
||||
func (p *proxy) modifyResponse(res *http.Response) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *proxy) errorHandler(rw http.ResponseWriter, req *http.Request, err error) {
|
||||
rw.WriteHeader(http.StatusBadGateway)
|
||||
}
|
||||
|
||||
func cleanPath(p string) string {
|
||||
if p == "" {
|
||||
return "/"
|
||||
}
|
||||
if p[0] != '/' {
|
||||
p = "/" + p
|
||||
}
|
||||
np := path.Clean(p)
|
||||
if p[len(p)-1] == '/' && np != "/" {
|
||||
if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
|
||||
np = p
|
||||
} else {
|
||||
np += "/"
|
||||
}
|
||||
}
|
||||
return np
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestProxyRewrite(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
url *url.URL
|
||||
stripPath string
|
||||
in *url.URL
|
||||
expected *url.URL
|
||||
}{
|
||||
{
|
||||
name: "SamePathAdded",
|
||||
url: &url.URL{Scheme: "http", Host: "backend", Path: "/path1"},
|
||||
stripPath: "/strip",
|
||||
in: &url.URL{Scheme: "http", Host: "localhost", Path: "/strip/path1"},
|
||||
expected: &url.URL{Scheme: "http", Host: "backend", Path: "/path1/path1"},
|
||||
},
|
||||
{
|
||||
name: "NoStripPathInput",
|
||||
url: &url.URL{Scheme: "http", Host: "backend"},
|
||||
stripPath: "",
|
||||
in: &url.URL{Scheme: "http", Host: "localhost", Path: "/strip/path1"},
|
||||
expected: &url.URL{Scheme: "http", Host: "backend", Path: "/strip/path1"},
|
||||
},
|
||||
{
|
||||
name: "NoStripPathPresentInReq",
|
||||
url: &url.URL{Scheme: "http", Host: "backend"},
|
||||
stripPath: "/not-found",
|
||||
in: &url.URL{Scheme: "http", Host: "localhost", Path: "/strip/path1"},
|
||||
expected: &url.URL{Scheme: "http", Host: "backend", Path: "/strip/path1"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
proxy, err := NewProxy(tc.url.String(), tc.stripPath)
|
||||
require.NoError(t, err)
|
||||
inReq, err := http.NewRequest(http.MethodGet, tc.in.String(), nil)
|
||||
require.NoError(t, err)
|
||||
proxyReq := &httputil.ProxyRequest{
|
||||
In: inReq,
|
||||
Out: inReq.Clone(context.Background()),
|
||||
}
|
||||
proxy.Rewrite(proxyReq)
|
||||
|
||||
assert.Equal(t, tc.expected.Host, proxyReq.Out.URL.Host)
|
||||
assert.Equal(t, tc.expected.Scheme, proxyReq.Out.URL.Scheme)
|
||||
assert.Equal(t, tc.expected.Path, proxyReq.Out.URL.Path)
|
||||
assert.Equal(t, tc.expected.Query(), proxyReq.Out.URL.Query())
|
||||
}
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
import { GatewayApiV1Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import {
|
||||
CreateIngestionKeyProps,
|
||||
IngestionKeyProps,
|
||||
} from 'types/api/ingestionKeys/types';
|
||||
|
||||
const createIngestionKey = async (
|
||||
props: CreateIngestionKeyProps,
|
||||
): Promise<SuccessResponse<IngestionKeyProps> | ErrorResponse> => {
|
||||
try {
|
||||
const response = await GatewayApiV1Instance.post('/workspaces/me/keys', {
|
||||
...props,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default createIngestionKey;
|
||||
@@ -1,26 +0,0 @@
|
||||
import { GatewayApiV1Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { AllIngestionKeyProps } from 'types/api/ingestionKeys/types';
|
||||
|
||||
const deleteIngestionKey = async (
|
||||
id: string,
|
||||
): Promise<SuccessResponse<AllIngestionKeyProps> | ErrorResponse> => {
|
||||
try {
|
||||
const response = await GatewayApiV1Instance.delete(
|
||||
`/workspaces/me/keys/${id}`,
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default deleteIngestionKey;
|
||||
@@ -1,21 +0,0 @@
|
||||
import { GatewayApiV1Instance } from 'api';
|
||||
import { AxiosResponse } from 'axios';
|
||||
import {
|
||||
AllIngestionKeyProps,
|
||||
GetIngestionKeyProps,
|
||||
} from 'types/api/ingestionKeys/types';
|
||||
|
||||
export const getAllIngestionKeys = (
|
||||
props: GetIngestionKeyProps,
|
||||
): Promise<AxiosResponse<AllIngestionKeyProps>> => {
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
const { search, per_page, page } = props;
|
||||
|
||||
const BASE_URL = '/workspaces/me/keys';
|
||||
const URL_QUERY_PARAMS =
|
||||
search && search.length > 0
|
||||
? `/search?name=${search}&page=1&per_page=100`
|
||||
: `?page=${page}&per_page=${per_page}`;
|
||||
|
||||
return GatewayApiV1Instance.get(`${BASE_URL}${URL_QUERY_PARAMS}`);
|
||||
};
|
||||
@@ -1,65 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-throw-literal */
|
||||
import { GatewayApiV1Instance } from 'api';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
AddLimitProps,
|
||||
LimitSuccessProps,
|
||||
} from 'types/api/ingestionKeys/limits/types';
|
||||
|
||||
interface SuccessResponse<T> {
|
||||
statusCode: number;
|
||||
error: null;
|
||||
message: string;
|
||||
payload: T;
|
||||
}
|
||||
|
||||
interface ErrorResponse {
|
||||
statusCode: number;
|
||||
error: string;
|
||||
message: string;
|
||||
payload: null;
|
||||
}
|
||||
|
||||
const createLimitForIngestionKey = async (
|
||||
props: AddLimitProps,
|
||||
): Promise<SuccessResponse<LimitSuccessProps> | ErrorResponse> => {
|
||||
try {
|
||||
const response = await GatewayApiV1Instance.post(
|
||||
`/workspaces/me/keys/${props.keyID}/limits`,
|
||||
{
|
||||
...props,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error)) {
|
||||
// Axios error
|
||||
const errResponse: ErrorResponse = {
|
||||
statusCode: error.response?.status || 500,
|
||||
error: error.response?.data?.error,
|
||||
message: error.response?.data?.status || 'An error occurred',
|
||||
payload: null,
|
||||
};
|
||||
|
||||
throw errResponse;
|
||||
} else {
|
||||
// Non-Axios error
|
||||
const errResponse: ErrorResponse = {
|
||||
statusCode: 500,
|
||||
error: 'Unknown error',
|
||||
message: 'An unknown error occurred',
|
||||
payload: null,
|
||||
};
|
||||
|
||||
throw errResponse;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default createLimitForIngestionKey;
|
||||
@@ -1,26 +0,0 @@
|
||||
import { GatewayApiV1Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { AllIngestionKeyProps } from 'types/api/ingestionKeys/types';
|
||||
|
||||
const deleteLimitsForIngestionKey = async (
|
||||
id: string,
|
||||
): Promise<SuccessResponse<AllIngestionKeyProps> | ErrorResponse> => {
|
||||
try {
|
||||
const response = await GatewayApiV1Instance.delete(
|
||||
`/workspaces/me/limits/${id}`,
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default deleteLimitsForIngestionKey;
|
||||
@@ -1,65 +0,0 @@
|
||||
/* eslint-disable @typescript-eslint/no-throw-literal */
|
||||
import { GatewayApiV1Instance } from 'api';
|
||||
import axios from 'axios';
|
||||
import {
|
||||
LimitSuccessProps,
|
||||
UpdateLimitProps,
|
||||
} from 'types/api/ingestionKeys/limits/types';
|
||||
|
||||
interface SuccessResponse<T> {
|
||||
statusCode: number;
|
||||
error: null;
|
||||
message: string;
|
||||
payload: T;
|
||||
}
|
||||
|
||||
interface ErrorResponse {
|
||||
statusCode: number;
|
||||
error: string;
|
||||
message: string;
|
||||
payload: null;
|
||||
}
|
||||
|
||||
const updateLimitForIngestionKey = async (
|
||||
props: UpdateLimitProps,
|
||||
): Promise<SuccessResponse<LimitSuccessProps> | ErrorResponse> => {
|
||||
try {
|
||||
const response = await GatewayApiV1Instance.patch(
|
||||
`/workspaces/me/limits/${props.limitID}`,
|
||||
{
|
||||
config: props.config,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
} catch (error) {
|
||||
if (axios.isAxiosError(error)) {
|
||||
// Axios error
|
||||
const errResponse: ErrorResponse = {
|
||||
statusCode: error.response?.status || 500,
|
||||
error: error.response?.data?.error,
|
||||
message: error.response?.data?.status || 'An error occurred',
|
||||
payload: null,
|
||||
};
|
||||
|
||||
throw errResponse;
|
||||
} else {
|
||||
// Non-Axios error
|
||||
const errResponse: ErrorResponse = {
|
||||
statusCode: 500,
|
||||
error: 'Unknown error',
|
||||
message: 'An unknown error occurred',
|
||||
payload: null,
|
||||
};
|
||||
|
||||
throw errResponse;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default updateLimitForIngestionKey;
|
||||
@@ -1,32 +0,0 @@
|
||||
import { GatewayApiV1Instance } from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import {
|
||||
IngestionKeysPayloadProps,
|
||||
UpdateIngestionKeyProps,
|
||||
} from 'types/api/ingestionKeys/types';
|
||||
|
||||
const updateIngestionKey = async (
|
||||
props: UpdateIngestionKeyProps,
|
||||
): Promise<SuccessResponse<IngestionKeysPayloadProps> | ErrorResponse> => {
|
||||
try {
|
||||
const response = await GatewayApiV1Instance.patch(
|
||||
`/workspaces/me/keys/${props.id}`,
|
||||
{
|
||||
...props.data,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default updateIngestionKey;
|
||||
@@ -4,8 +4,6 @@ export const apiV2 = '/api/v2/';
|
||||
export const apiV3 = '/api/v3/';
|
||||
export const apiV4 = '/api/v4/';
|
||||
export const apiV5 = '/api/v5/';
|
||||
export const gatewayApiV1 = '/api/gateway/v1/';
|
||||
export const gatewayApiV2 = '/api/gateway/v2/';
|
||||
export const apiAlertManager = '/api/alertmanager/';
|
||||
|
||||
export default apiV1;
|
||||
|
||||
@@ -15,15 +15,7 @@ import { Events } from 'constants/events';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { eventEmitter } from 'utils/getEventEmitter';
|
||||
|
||||
import apiV1, {
|
||||
apiAlertManager,
|
||||
apiV2,
|
||||
apiV3,
|
||||
apiV4,
|
||||
apiV5,
|
||||
gatewayApiV1,
|
||||
gatewayApiV2,
|
||||
} from './apiV1';
|
||||
import apiV1, { apiAlertManager, apiV2, apiV3, apiV4, apiV5 } from './apiV1';
|
||||
import { Logout } from './utils';
|
||||
|
||||
const RESPONSE_TIMEOUT_THRESHOLD = 5000; // 5 seconds
|
||||
@@ -211,24 +203,6 @@ LogEventAxiosInstance.interceptors.response.use(
|
||||
LogEventAxiosInstance.interceptors.request.use(interceptorsRequestResponse);
|
||||
//
|
||||
|
||||
// gateway Api V1
|
||||
export const GatewayApiV1Instance = axios.create({
|
||||
baseURL: `${ENVIRONMENT.baseURL}${gatewayApiV1}`,
|
||||
});
|
||||
|
||||
GatewayApiV1Instance.interceptors.response.use(
|
||||
interceptorsResponse,
|
||||
interceptorRejected,
|
||||
);
|
||||
|
||||
GatewayApiV1Instance.interceptors.request.use(interceptorsRequestResponse);
|
||||
//
|
||||
|
||||
// gateway Api V2
|
||||
export const GatewayApiV2Instance = axios.create({
|
||||
baseURL: `${ENVIRONMENT.baseURL}${gatewayApiV2}`,
|
||||
});
|
||||
|
||||
// generated API Instance
|
||||
export const GeneratedAPIInstance = axios.create({
|
||||
baseURL: ENVIRONMENT.baseURL,
|
||||
@@ -240,14 +214,6 @@ GeneratedAPIInstance.interceptors.response.use(
|
||||
interceptorRejected,
|
||||
);
|
||||
|
||||
GatewayApiV2Instance.interceptors.response.use(
|
||||
interceptorsResponse,
|
||||
interceptorRejected,
|
||||
);
|
||||
|
||||
GatewayApiV2Instance.interceptors.request.use(interceptorsRequestResponse);
|
||||
//
|
||||
|
||||
AxiosAlertManagerInstance.interceptors.response.use(
|
||||
interceptorsResponse,
|
||||
interceptorRejected,
|
||||
|
||||
@@ -1,3 +1,22 @@
|
||||
.chart-manager-series-label {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
max-width: 100%;
|
||||
cursor: pointer;
|
||||
border: none;
|
||||
background-color: transparent;
|
||||
color: inherit;
|
||||
text-align: left;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
}
|
||||
|
||||
.chart-manager-container {
|
||||
width: 100%;
|
||||
max-height: calc(40% - 40px);
|
||||
|
||||
@@ -1,24 +1,28 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Button, Input } from 'antd';
|
||||
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
|
||||
import { ResizeTable } from 'components/ResizeTable';
|
||||
import { getGraphManagerTableColumns } from 'container/GridCardLayout/GridCard/FullView/TableRender/GraphManagerColumns';
|
||||
import { ExtendedChartDataset } from 'container/GridCardLayout/GridCard/FullView/types';
|
||||
import { getDefaultTableDataSet } from 'container/GridCardLayout/GridCard/FullView/utils';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import { usePlotContext } from 'lib/uPlotV2/context/PlotContext';
|
||||
import useLegendsSync from 'lib/uPlotV2/hooks/useLegendsSync';
|
||||
import { useDashboard } from 'providers/Dashboard/Dashboard';
|
||||
|
||||
import { getChartManagerColumns } from './columns';
|
||||
import { ExtendedChartDataset, getDefaultTableDataSet } from './utils';
|
||||
|
||||
import './ChartManager.styles.scss';
|
||||
|
||||
interface ChartManagerProps {
|
||||
config: UPlotConfigBuilder;
|
||||
alignedData: uPlot.AlignedData;
|
||||
yAxisUnit?: string;
|
||||
decimalPrecision?: PrecisionOption;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
const X_AXIS_INDEX = 0;
|
||||
|
||||
/**
|
||||
* ChartManager provides a tabular view to manage the visibility of
|
||||
* individual series on a uPlot chart.
|
||||
@@ -28,16 +32,12 @@ interface ChartManagerProps {
|
||||
* - filter series by label
|
||||
* - toggle individual series on/off
|
||||
* - persist the visibility configuration to local storage.
|
||||
*
|
||||
* @param config - `UPlotConfigBuilder` instance used to derive chart options.
|
||||
* @param alignedData - uPlot aligned data used to build the initial table dataset.
|
||||
* @param yAxisUnit - Optional unit label for Y-axis values shown in the table.
|
||||
* @param onCancel - Optional callback invoked when the user cancels the dialog.
|
||||
*/
|
||||
export default function ChartManager({
|
||||
config,
|
||||
alignedData,
|
||||
yAxisUnit,
|
||||
decimalPrecision = PrecisionOptionsEnum.TWO,
|
||||
onCancel,
|
||||
}: ChartManagerProps): JSX.Element {
|
||||
const { notifications } = useNotifications();
|
||||
@@ -53,8 +53,13 @@ export default function ChartManager({
|
||||
const { isDashboardLocked } = useDashboard();
|
||||
|
||||
const [tableDataSet, setTableDataSet] = useState<ExtendedChartDataset[]>(() =>
|
||||
getDefaultTableDataSet(config.getConfig() as uPlot.Options, alignedData),
|
||||
getDefaultTableDataSet(
|
||||
config.getConfig() as uPlot.Options,
|
||||
alignedData,
|
||||
decimalPrecision,
|
||||
),
|
||||
);
|
||||
const [filterValue, setFilterValue] = useState('');
|
||||
|
||||
const graphVisibilityState = useMemo(
|
||||
() =>
|
||||
@@ -67,46 +72,62 @@ export default function ChartManager({
|
||||
|
||||
useEffect(() => {
|
||||
setTableDataSet(
|
||||
getDefaultTableDataSet(config.getConfig() as uPlot.Options, alignedData),
|
||||
);
|
||||
}, [alignedData, config]);
|
||||
|
||||
const filterHandler = useCallback(
|
||||
(event: React.ChangeEvent<HTMLInputElement>): void => {
|
||||
const value = event.target.value.toString().toLowerCase();
|
||||
const updatedDataSet = tableDataSet.map((item) => {
|
||||
if (item.label?.toLocaleLowerCase().includes(value)) {
|
||||
return { ...item, show: true };
|
||||
}
|
||||
return { ...item, show: false };
|
||||
});
|
||||
setTableDataSet(updatedDataSet);
|
||||
},
|
||||
[tableDataSet],
|
||||
);
|
||||
|
||||
const dataSource = useMemo(
|
||||
() =>
|
||||
tableDataSet.filter(
|
||||
(item, index) => index !== 0 && item.show, // skipping the first item as it is the x-axis
|
||||
getDefaultTableDataSet(
|
||||
config.getConfig() as uPlot.Options,
|
||||
alignedData,
|
||||
decimalPrecision,
|
||||
),
|
||||
[tableDataSet],
|
||||
);
|
||||
setFilterValue('');
|
||||
}, [alignedData, config, decimalPrecision]);
|
||||
|
||||
const handleFilterChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>): void => {
|
||||
setFilterValue(e.target.value.toLowerCase());
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const handleToggleSeriesOnOff = useCallback(
|
||||
(index: number): void => {
|
||||
onToggleSeriesOnOff(index);
|
||||
},
|
||||
[onToggleSeriesOnOff],
|
||||
);
|
||||
|
||||
const dataSource = useMemo(() => {
|
||||
const filter = filterValue.trim();
|
||||
return tableDataSet.filter((item, index) => {
|
||||
if (index === X_AXIS_INDEX) {
|
||||
return false;
|
||||
}
|
||||
if (!filter) {
|
||||
return true;
|
||||
}
|
||||
return item.label?.toLowerCase().includes(filter) ?? false;
|
||||
});
|
||||
}, [tableDataSet, filterValue]);
|
||||
|
||||
const columns = useMemo(
|
||||
() =>
|
||||
getGraphManagerTableColumns({
|
||||
getChartManagerColumns({
|
||||
tableDataSet,
|
||||
checkBoxOnChangeHandler: (_e, index) => {
|
||||
onToggleSeriesOnOff(index);
|
||||
},
|
||||
graphVisibilityState,
|
||||
labelClickedHandler: onToggleSeriesVisibility,
|
||||
onToggleSeriesOnOff: handleToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
yAxisUnit,
|
||||
isGraphDisabled: isDashboardLocked,
|
||||
decimalPrecision,
|
||||
}),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[tableDataSet, graphVisibilityState, yAxisUnit, isDashboardLocked],
|
||||
[
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
handleToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
yAxisUnit,
|
||||
isDashboardLocked,
|
||||
decimalPrecision,
|
||||
],
|
||||
);
|
||||
|
||||
const handleSave = useCallback((): void => {
|
||||
@@ -114,20 +135,23 @@ export default function ChartManager({
|
||||
notifications.success({
|
||||
message: 'The updated graphs & legends are saved',
|
||||
});
|
||||
if (onCancel) {
|
||||
onCancel();
|
||||
}
|
||||
onCancel?.();
|
||||
}, [syncSeriesVisibilityToLocalStorage, notifications, onCancel]);
|
||||
|
||||
return (
|
||||
<div className="chart-manager-container">
|
||||
<div className="chart-manager-header">
|
||||
<Input onChange={filterHandler} placeholder="Filter Series" />
|
||||
<Input
|
||||
placeholder="Filter Series"
|
||||
value={filterValue}
|
||||
onChange={handleFilterChange}
|
||||
data-testid="filter-input"
|
||||
/>
|
||||
<div className="chart-manager-actions-container">
|
||||
<Button type="default" onClick={onCancel}>
|
||||
<Button type="default" onClick={onCancel} data-testid="cancel-button">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button type="primary" onClick={handleSave}>
|
||||
<Button type="primary" onClick={handleSave} data-testid="save-button">
|
||||
Save
|
||||
</Button>
|
||||
</div>
|
||||
@@ -136,10 +160,10 @@ export default function ChartManager({
|
||||
<ResizeTable
|
||||
columns={columns}
|
||||
dataSource={dataSource}
|
||||
virtual
|
||||
rowKey="index"
|
||||
scroll={{ y: 200 }}
|
||||
pagination={false}
|
||||
virtual
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
import { Tooltip } from 'antd';
|
||||
|
||||
import './ChartManager.styles.scss';
|
||||
|
||||
interface SeriesLabelProps {
|
||||
label: string;
|
||||
labelIndex: number;
|
||||
onClick: (idx: number) => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function SeriesLabel({
|
||||
label,
|
||||
labelIndex,
|
||||
onClick,
|
||||
disabled,
|
||||
}: SeriesLabelProps): JSX.Element {
|
||||
return (
|
||||
<Tooltip placement="topLeft" title={label}>
|
||||
<button
|
||||
className="chart-manager-series-label"
|
||||
disabled={disabled}
|
||||
type="button"
|
||||
data-testid={`series-label-button-${labelIndex}`}
|
||||
onClick={(): void => onClick(labelIndex)}
|
||||
>
|
||||
{label}
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { UPlotConfigBuilder } from 'lib/uPlotV2/config/UPlotConfigBuilder';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import ChartManager from '../ChartManager';
|
||||
|
||||
const mockSyncSeriesVisibilityToLocalStorage = jest.fn();
|
||||
const mockNotificationsSuccess = jest.fn();
|
||||
|
||||
jest.mock('lib/uPlotV2/context/PlotContext', () => ({
|
||||
usePlotContext: (): {
|
||||
onToggleSeriesOnOff: jest.Mock;
|
||||
onToggleSeriesVisibility: jest.Mock;
|
||||
syncSeriesVisibilityToLocalStorage: jest.Mock;
|
||||
} => ({
|
||||
onToggleSeriesOnOff: jest.fn(),
|
||||
onToggleSeriesVisibility: jest.fn(),
|
||||
syncSeriesVisibilityToLocalStorage: mockSyncSeriesVisibilityToLocalStorage,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('lib/uPlotV2/hooks/useLegendsSync', () => ({
|
||||
__esModule: true,
|
||||
default: (): {
|
||||
legendItemsMap: { [key: number]: { show: boolean; label: string } };
|
||||
} => ({
|
||||
legendItemsMap: {
|
||||
0: { show: true, label: 'Time' },
|
||||
1: { show: true, label: 'Series 1' },
|
||||
2: { show: true, label: 'Series 2' },
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('providers/Dashboard/Dashboard', () => ({
|
||||
useDashboard: (): { isDashboardLocked: boolean } => ({
|
||||
isDashboardLocked: false,
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('hooks/useNotifications', () => ({
|
||||
useNotifications: (): { notifications: { success: jest.Mock } } => ({
|
||||
notifications: {
|
||||
success: mockNotificationsSuccess,
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('components/ResizeTable', () => {
|
||||
const MockTable = ({
|
||||
dataSource,
|
||||
columns,
|
||||
}: {
|
||||
dataSource: { index: number; label?: string }[];
|
||||
columns: { key: string; title: string }[];
|
||||
}): JSX.Element => (
|
||||
<div data-testid="resize-table">
|
||||
{columns.map((col) => (
|
||||
<span key={col.key}>{col.title}</span>
|
||||
))}
|
||||
{dataSource.map((row) => (
|
||||
<div key={row.index} data-testid={`row-${row.index}`}>
|
||||
{row.label}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
return { ResizeTable: MockTable };
|
||||
});
|
||||
|
||||
const createMockConfig = (): { getConfig: () => uPlot.Options } => ({
|
||||
getConfig: (): uPlot.Options => ({
|
||||
width: 100,
|
||||
height: 100,
|
||||
series: [
|
||||
{ label: 'Time', value: 'time' },
|
||||
{ label: 'Series 1', scale: 'y' },
|
||||
{ label: 'Series 2', scale: 'y' },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
const createAlignedData = (): uPlot.AlignedData => [
|
||||
[1000, 2000, 3000],
|
||||
[10, 20, 30],
|
||||
[1, 2, 3],
|
||||
];
|
||||
|
||||
describe('ChartManager', () => {
|
||||
const mockOnCancel = jest.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders filter input and action buttons', () => {
|
||||
render(
|
||||
<ChartManager
|
||||
config={createMockConfig() as any}
|
||||
alignedData={createAlignedData()}
|
||||
onCancel={mockOnCancel}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByPlaceholderText('Filter Series')).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders ResizeTable with data', () => {
|
||||
render(
|
||||
<ChartManager
|
||||
config={createMockConfig() as UPlotConfigBuilder}
|
||||
alignedData={createAlignedData()}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(screen.getByTestId('resize-table')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls onCancel when Cancel button is clicked', async () => {
|
||||
render(
|
||||
<ChartManager
|
||||
config={createMockConfig() as UPlotConfigBuilder}
|
||||
alignedData={createAlignedData()}
|
||||
onCancel={mockOnCancel}
|
||||
/>,
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByTestId('cancel-button'));
|
||||
|
||||
expect(mockOnCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('filters table data when typing in filter input', async () => {
|
||||
render(
|
||||
<ChartManager
|
||||
config={createMockConfig() as UPlotConfigBuilder}
|
||||
alignedData={createAlignedData()}
|
||||
/>,
|
||||
);
|
||||
|
||||
// Before filter: both Series 1 and Series 2 rows are visible
|
||||
expect(screen.getByTestId('row-1')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('row-2')).toBeInTheDocument();
|
||||
|
||||
const filterInput = screen.getByTestId('filter-input');
|
||||
await userEvent.type(filterInput, 'Series 1');
|
||||
|
||||
// After filter: only Series 1 row is visible, Series 2 row is filtered out
|
||||
expect(screen.getByTestId('row-1')).toBeInTheDocument();
|
||||
expect(screen.queryByTestId('row-2')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('calls syncSeriesVisibilityToLocalStorage, notifications.success, and onCancel when Save is clicked', async () => {
|
||||
render(
|
||||
<ChartManager
|
||||
config={createMockConfig() as UPlotConfigBuilder}
|
||||
alignedData={createAlignedData()}
|
||||
onCancel={mockOnCancel}
|
||||
/>,
|
||||
);
|
||||
|
||||
await userEvent.click(screen.getByTestId('save-button'));
|
||||
|
||||
expect(mockSyncSeriesVisibilityToLocalStorage).toHaveBeenCalledTimes(1);
|
||||
expect(mockNotificationsSuccess).toHaveBeenCalledWith({
|
||||
message: 'The updated graphs & legends are saved',
|
||||
});
|
||||
expect(mockOnCancel).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
|
||||
import { SeriesLabel } from '../SeriesLabel';
|
||||
|
||||
describe('SeriesLabel', () => {
|
||||
it('renders the label text', () => {
|
||||
render(
|
||||
<SeriesLabel label="Test Series Label" labelIndex={1} onClick={jest.fn()} />,
|
||||
);
|
||||
expect(screen.getByTestId('series-label-button-1')).toHaveTextContent(
|
||||
'Test Series Label',
|
||||
);
|
||||
});
|
||||
|
||||
it('calls onClick with labelIndex when clicked', async () => {
|
||||
const onClick = jest.fn();
|
||||
render(<SeriesLabel label="Series A" labelIndex={2} onClick={onClick} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId('series-label-button-2'));
|
||||
|
||||
expect(onClick).toHaveBeenCalledWith(2);
|
||||
expect(onClick).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('renders disabled button when disabled prop is true', () => {
|
||||
render(
|
||||
<SeriesLabel label="Disabled" labelIndex={0} onClick={jest.fn()} disabled />,
|
||||
);
|
||||
const button = screen.getByTestId('series-label-button-0');
|
||||
expect(button).toBeDisabled();
|
||||
});
|
||||
|
||||
it('has chart-manager-series-label class', () => {
|
||||
render(<SeriesLabel label="Label" labelIndex={0} onClick={jest.fn()} />);
|
||||
const button = screen.getByTestId('series-label-button-0');
|
||||
expect(button).toHaveClass('chart-manager-series-label');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,167 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { Y_AXIS_UNIT_NAMES } from 'components/YAxisUnitSelector/constants';
|
||||
import { UniversalYAxisUnit } from 'components/YAxisUnitSelector/types';
|
||||
|
||||
import { getChartManagerColumns } from '../columns';
|
||||
import { ExtendedChartDataset } from '../utils';
|
||||
|
||||
const createMockDataset = (
|
||||
index: number,
|
||||
overrides: Partial<ExtendedChartDataset> = {},
|
||||
): ExtendedChartDataset =>
|
||||
({
|
||||
index,
|
||||
label: `Series ${index}`,
|
||||
show: true,
|
||||
sum: 100,
|
||||
avg: 50,
|
||||
min: 10,
|
||||
max: 90,
|
||||
stroke: '#ff0000',
|
||||
...overrides,
|
||||
} as ExtendedChartDataset);
|
||||
|
||||
describe('getChartManagerColumns', () => {
|
||||
const tableDataSet: ExtendedChartDataset[] = [
|
||||
createMockDataset(0, { label: 'Time' }),
|
||||
createMockDataset(1),
|
||||
createMockDataset(2),
|
||||
];
|
||||
const graphVisibilityState = [true, true, false];
|
||||
const onToggleSeriesOnOff = jest.fn();
|
||||
const onToggleSeriesVisibility = jest.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns columns with expected structure', () => {
|
||||
const columns = getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
});
|
||||
|
||||
expect(columns).toHaveLength(6);
|
||||
expect(columns[0].key).toBe('index');
|
||||
expect(columns[1].key).toBe('label');
|
||||
expect(columns[2].key).toBe('avg');
|
||||
expect(columns[3].key).toBe('sum');
|
||||
expect(columns[4].key).toBe('max');
|
||||
expect(columns[5].key).toBe('min');
|
||||
});
|
||||
|
||||
it('includes Label column with title', () => {
|
||||
const columns = getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
});
|
||||
|
||||
const labelCol = columns.find((c) => c.key === 'label');
|
||||
expect(labelCol?.title).toBe('Label');
|
||||
});
|
||||
|
||||
it('formats column titles with yAxisUnit', () => {
|
||||
const columns = getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
yAxisUnit: 'ms',
|
||||
});
|
||||
|
||||
const avgCol = columns.find((c) => c.key === 'avg');
|
||||
expect(avgCol?.title).toBe(
|
||||
`Avg (in ${Y_AXIS_UNIT_NAMES[UniversalYAxisUnit.MILLISECONDS]})`,
|
||||
);
|
||||
});
|
||||
|
||||
it('numeric column render returns formatted string with yAxisUnit', () => {
|
||||
const columns = getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
yAxisUnit: 'ms',
|
||||
});
|
||||
|
||||
const avgCol = columns.find((c) => c.key === 'avg');
|
||||
const renderFn = avgCol?.render as
|
||||
| ((val: number, record: ExtendedChartDataset, index: number) => string)
|
||||
| undefined;
|
||||
expect(renderFn).toBeDefined();
|
||||
const output = renderFn?.(123.45, tableDataSet[1], 1);
|
||||
expect(output).toBe('123.45 ms');
|
||||
});
|
||||
|
||||
it('numeric column render formats zero when value is undefined', () => {
|
||||
const columns = getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
yAxisUnit: 'none',
|
||||
});
|
||||
|
||||
const sumCol = columns.find((c) => c.key === 'sum');
|
||||
const renderFn = sumCol?.render as
|
||||
| ((
|
||||
val: number | undefined,
|
||||
record: ExtendedChartDataset,
|
||||
index: number,
|
||||
) => string)
|
||||
| undefined;
|
||||
const output = renderFn?.(undefined, tableDataSet[1], 1);
|
||||
expect(output).toBe('0');
|
||||
});
|
||||
|
||||
it('label column render displays label text and is clickable', () => {
|
||||
const columns = getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
});
|
||||
|
||||
const labelCol = columns.find((c) => c.key === 'label');
|
||||
const renderFn = labelCol?.render as
|
||||
| ((
|
||||
label: string,
|
||||
record: ExtendedChartDataset,
|
||||
index: number,
|
||||
) => JSX.Element)
|
||||
| undefined;
|
||||
expect(renderFn).toBeDefined();
|
||||
const renderResult = renderFn!('Series 1', tableDataSet[1], 1);
|
||||
|
||||
const { getByRole } = render(renderResult);
|
||||
expect(getByRole('button', { name: 'Series 1' })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('index column render renders checkbox with correct checked state', () => {
|
||||
const columns = getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
});
|
||||
|
||||
const indexCol = columns.find((c) => c.key === 'index');
|
||||
const renderFn = indexCol?.render as
|
||||
| ((
|
||||
_val: unknown,
|
||||
record: ExtendedChartDataset,
|
||||
index: number,
|
||||
) => JSX.Element)
|
||||
| undefined;
|
||||
expect(renderFn).toBeDefined();
|
||||
const { container } = render(renderFn!(null, tableDataSet[1], 1));
|
||||
|
||||
const checkbox = container.querySelector('input[type="checkbox"]');
|
||||
expect(checkbox).toBeInTheDocument();
|
||||
expect(checkbox).toBeChecked(); // graphVisibilityState[1] is true
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,113 @@
|
||||
import { PrecisionOptionsEnum } from 'components/Graph/types';
|
||||
|
||||
import {
|
||||
formatTableValueWithUnit,
|
||||
getDefaultTableDataSet,
|
||||
getTableColumnTitle,
|
||||
} from '../utils';
|
||||
|
||||
describe('ChartManager utils', () => {
|
||||
describe('getDefaultTableDataSet', () => {
|
||||
const createOptions = (seriesCount: number): uPlot.Options => ({
|
||||
series: Array.from({ length: seriesCount }, (_, i) =>
|
||||
i === 0
|
||||
? { label: 'Time', value: 'time' }
|
||||
: { label: `Series ${i}`, scale: 'y' },
|
||||
),
|
||||
width: 100,
|
||||
height: 100,
|
||||
});
|
||||
|
||||
it('returns one row per series with computed stats', () => {
|
||||
const options = createOptions(3);
|
||||
const data: uPlot.AlignedData = [
|
||||
[1000, 2000, 3000],
|
||||
[10, 20, 30],
|
||||
[1, 2, 3],
|
||||
];
|
||||
|
||||
const result = getDefaultTableDataSet(options, data);
|
||||
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result[0]).toMatchObject({
|
||||
index: 0,
|
||||
label: 'Time',
|
||||
show: true,
|
||||
});
|
||||
expect(result[1]).toMatchObject({
|
||||
index: 1,
|
||||
label: 'Series 1',
|
||||
show: true,
|
||||
sum: 60,
|
||||
avg: 20,
|
||||
max: 30,
|
||||
min: 10,
|
||||
});
|
||||
expect(result[2]).toMatchObject({
|
||||
index: 2,
|
||||
label: 'Series 2',
|
||||
show: true,
|
||||
sum: 6,
|
||||
avg: 2,
|
||||
max: 3,
|
||||
min: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('handles empty data arrays', () => {
|
||||
const options = createOptions(2);
|
||||
const data: uPlot.AlignedData = [[], []];
|
||||
|
||||
const result = getDefaultTableDataSet(options, data);
|
||||
|
||||
expect(result[0]).toMatchObject({
|
||||
sum: 0,
|
||||
avg: 0,
|
||||
max: 0,
|
||||
min: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('respects decimalPrecision parameter', () => {
|
||||
const options = createOptions(2);
|
||||
const data: uPlot.AlignedData = [[1000], [123.454]];
|
||||
|
||||
const resultTwo = getDefaultTableDataSet(
|
||||
options,
|
||||
data,
|
||||
PrecisionOptionsEnum.TWO,
|
||||
);
|
||||
expect(resultTwo[1].avg).toBe(123.45);
|
||||
|
||||
const resultZero = getDefaultTableDataSet(
|
||||
options,
|
||||
data,
|
||||
PrecisionOptionsEnum.ZERO,
|
||||
);
|
||||
expect(resultZero[1].avg).toBe(123);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatTableValueWithUnit', () => {
|
||||
it('formats value with unit', () => {
|
||||
const result = formatTableValueWithUnit(1234.56, 'ms');
|
||||
expect(result).toBe('1.23 s');
|
||||
});
|
||||
|
||||
it('falls back to none format when yAxisUnit is undefined', () => {
|
||||
const result = formatTableValueWithUnit(123.45);
|
||||
expect(result).toBe('123.45');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getTableColumnTitle', () => {
|
||||
it('returns title only when yAxisUnit is undefined', () => {
|
||||
expect(getTableColumnTitle('Avg')).toBe('Avg');
|
||||
});
|
||||
|
||||
it('returns title with unit when yAxisUnit is provided', () => {
|
||||
const result = getTableColumnTitle('Avg', 'ms');
|
||||
expect(result).toBe('Avg (in Milliseconds (ms))');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
import { ColumnType } from 'antd/es/table';
|
||||
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
|
||||
import CustomCheckBox from 'container/GridCardLayout/GridCard/FullView/TableRender/CustomCheckBox';
|
||||
|
||||
import { SeriesLabel } from './SeriesLabel';
|
||||
import {
|
||||
ExtendedChartDataset,
|
||||
formatTableValueWithUnit,
|
||||
getTableColumnTitle,
|
||||
} from './utils';
|
||||
|
||||
export interface GetChartManagerColumnsParams {
|
||||
tableDataSet: ExtendedChartDataset[];
|
||||
graphVisibilityState: boolean[];
|
||||
onToggleSeriesOnOff: (index: number) => void;
|
||||
onToggleSeriesVisibility: (index: number) => void;
|
||||
yAxisUnit?: string;
|
||||
decimalPrecision?: PrecisionOption;
|
||||
isGraphDisabled?: boolean;
|
||||
}
|
||||
|
||||
export function getChartManagerColumns({
|
||||
tableDataSet,
|
||||
graphVisibilityState,
|
||||
onToggleSeriesOnOff,
|
||||
onToggleSeriesVisibility,
|
||||
yAxisUnit,
|
||||
decimalPrecision = PrecisionOptionsEnum.TWO,
|
||||
isGraphDisabled,
|
||||
}: GetChartManagerColumnsParams): ColumnType<ExtendedChartDataset>[] {
|
||||
return [
|
||||
{
|
||||
title: '',
|
||||
width: 50,
|
||||
dataIndex: 'index',
|
||||
key: 'index',
|
||||
render: (_: unknown, record: ExtendedChartDataset): JSX.Element => (
|
||||
<CustomCheckBox
|
||||
data={tableDataSet}
|
||||
graphVisibilityState={graphVisibilityState}
|
||||
index={record.index}
|
||||
disabled={isGraphDisabled}
|
||||
checkBoxOnChangeHandler={(_e, idx): void => onToggleSeriesOnOff(idx)}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: 'Label',
|
||||
width: 300,
|
||||
dataIndex: 'label',
|
||||
key: 'label',
|
||||
render: (label: string, record: ExtendedChartDataset): JSX.Element => (
|
||||
<SeriesLabel
|
||||
label={label ?? ''}
|
||||
labelIndex={record.index}
|
||||
disabled={isGraphDisabled}
|
||||
onClick={onToggleSeriesVisibility}
|
||||
/>
|
||||
),
|
||||
},
|
||||
{
|
||||
title: getTableColumnTitle('Avg', yAxisUnit),
|
||||
width: 90,
|
||||
dataIndex: 'avg',
|
||||
key: 'avg',
|
||||
render: (val: number | undefined): string =>
|
||||
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
|
||||
},
|
||||
{
|
||||
title: getTableColumnTitle('Sum', yAxisUnit),
|
||||
width: 90,
|
||||
dataIndex: 'sum',
|
||||
key: 'sum',
|
||||
render: (val: number | undefined): string =>
|
||||
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
|
||||
},
|
||||
{
|
||||
title: getTableColumnTitle('Max', yAxisUnit),
|
||||
width: 90,
|
||||
dataIndex: 'max',
|
||||
key: 'max',
|
||||
render: (val: number | undefined): string =>
|
||||
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
|
||||
},
|
||||
{
|
||||
title: getTableColumnTitle('Min', yAxisUnit),
|
||||
width: 90,
|
||||
dataIndex: 'min',
|
||||
key: 'min',
|
||||
render: (val: number | undefined): string =>
|
||||
formatTableValueWithUnit(val ?? 0, yAxisUnit, decimalPrecision),
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { PrecisionOption, PrecisionOptionsEnum } from 'components/Graph/types';
|
||||
import { getYAxisFormattedValue } from 'components/Graph/yAxisConfig';
|
||||
import { Y_AXIS_UNIT_NAMES } from 'components/YAxisUnitSelector/constants';
|
||||
import uPlot from 'uplot';
|
||||
|
||||
/** Extended series with computed stats for table display */
|
||||
export type ExtendedChartDataset = uPlot.Series & {
|
||||
show: boolean;
|
||||
sum: number;
|
||||
avg: number;
|
||||
min: number;
|
||||
max: number;
|
||||
index: number;
|
||||
};
|
||||
|
||||
function roundToDecimalPrecision(
|
||||
value: number,
|
||||
decimalPrecision: PrecisionOption = PrecisionOptionsEnum.TWO,
|
||||
): number {
|
||||
if (
|
||||
typeof value !== 'number' ||
|
||||
Number.isNaN(value) ||
|
||||
value === Infinity ||
|
||||
value === -Infinity
|
||||
) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (decimalPrecision === PrecisionOptionsEnum.FULL) {
|
||||
return value;
|
||||
}
|
||||
|
||||
// regex to match the decimal precision for the given decimal precision
|
||||
const regex = new RegExp(`^-?\\d*\\.?0*\\d{0,${decimalPrecision}}`);
|
||||
const matched = value ? value.toFixed(decimalPrecision).match(regex) : null;
|
||||
return matched ? parseFloat(matched[0]) : 0;
|
||||
}
|
||||
|
||||
/** Build table dataset from uPlot options and aligned data */
|
||||
export function getDefaultTableDataSet(
|
||||
options: uPlot.Options,
|
||||
data: uPlot.AlignedData,
|
||||
decimalPrecision: PrecisionOption = PrecisionOptionsEnum.TWO,
|
||||
): ExtendedChartDataset[] {
|
||||
return options.series.map(
|
||||
(series: uPlot.Series, index: number): ExtendedChartDataset => {
|
||||
const arr = (data[index] as number[]) ?? [];
|
||||
const sum = arr.reduce((a, b) => a + b, 0) || 0;
|
||||
const count = arr.length || 1;
|
||||
|
||||
const hasValues = arr.length > 0;
|
||||
return {
|
||||
...series,
|
||||
index,
|
||||
show: true,
|
||||
sum: roundToDecimalPrecision(sum, decimalPrecision),
|
||||
avg: roundToDecimalPrecision(sum / count, decimalPrecision),
|
||||
max: hasValues
|
||||
? roundToDecimalPrecision(Math.max(...arr), decimalPrecision)
|
||||
: 0,
|
||||
min: hasValues
|
||||
? roundToDecimalPrecision(Math.min(...arr), decimalPrecision)
|
||||
: 0,
|
||||
};
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/** Format numeric value for table display using yAxisUnit */
|
||||
export function formatTableValueWithUnit(
|
||||
value: number,
|
||||
yAxisUnit?: string,
|
||||
decimalPrecision: PrecisionOption = PrecisionOptionsEnum.TWO,
|
||||
): string {
|
||||
return `${getYAxisFormattedValue(
|
||||
String(value),
|
||||
yAxisUnit ?? 'none',
|
||||
decimalPrecision,
|
||||
)}`;
|
||||
}
|
||||
|
||||
/** Format column header with optional unit */
|
||||
export function getTableColumnTitle(title: string, yAxisUnit?: string): string {
|
||||
if (!yAxisUnit) {
|
||||
return title;
|
||||
}
|
||||
const universalName =
|
||||
Y_AXIS_UNIT_NAMES[yAxisUnit as keyof typeof Y_AXIS_UNIT_NAMES];
|
||||
if (!universalName) {
|
||||
return `${title} (in ${yAxisUnit})`;
|
||||
}
|
||||
return `${title} (in ${universalName})`;
|
||||
}
|
||||
@@ -96,6 +96,7 @@ function BarPanel(props: PanelWrapperProps): JSX.Element {
|
||||
config={config}
|
||||
alignedData={chartData}
|
||||
yAxisUnit={widget.yAxisUnit}
|
||||
decimalPrecision={widget.decimalPrecision}
|
||||
onCancel={onToggleModelHandler}
|
||||
/>
|
||||
);
|
||||
@@ -105,6 +106,7 @@ function BarPanel(props: PanelWrapperProps): JSX.Element {
|
||||
chartData,
|
||||
widget.yAxisUnit,
|
||||
onToggleModelHandler,
|
||||
widget.decimalPrecision,
|
||||
]);
|
||||
|
||||
const onPlotDestroy = useCallback(() => {
|
||||
|
||||
@@ -95,6 +95,7 @@ function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {
|
||||
config={config}
|
||||
alignedData={chartData}
|
||||
yAxisUnit={widget.yAxisUnit}
|
||||
decimalPrecision={widget.decimalPrecision}
|
||||
onCancel={onToggleModelHandler}
|
||||
/>
|
||||
);
|
||||
@@ -104,6 +105,7 @@ function TimeSeriesPanel(props: PanelWrapperProps): JSX.Element {
|
||||
chartData,
|
||||
widget.yAxisUnit,
|
||||
onToggleModelHandler,
|
||||
widget.decimalPrecision,
|
||||
]);
|
||||
|
||||
return (
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
import { useQuery, UseQueryResult } from 'react-query';
|
||||
import { getAllIngestionKeys } from 'api/IngestionKeys/getAllIngestionKeys';
|
||||
import { AxiosError, AxiosResponse } from 'axios';
|
||||
import {
|
||||
AllIngestionKeyProps,
|
||||
GetIngestionKeyProps,
|
||||
} from 'types/api/ingestionKeys/types';
|
||||
|
||||
export const useGetAllIngestionsKeys = (
|
||||
props: GetIngestionKeyProps,
|
||||
): UseQueryResult<AxiosResponse<AllIngestionKeyProps>, AxiosError> =>
|
||||
useQuery<AxiosResponse<AllIngestionKeyProps>, AxiosError>({
|
||||
queryKey: [`IngestionKeys-${props.page}-${props.search}`],
|
||||
queryFn: () => getAllIngestionKeys(props),
|
||||
});
|
||||
Reference in New Issue
Block a user