mirror of
https://github.com/SigNoz/signoz.git
synced 2026-07-31 10:10:36 +01:00
Compare commits
9 Commits
issue_5601
...
v0.135.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9197cb8b3b | ||
|
|
a0a17a99a6 | ||
|
|
8fb5703eb1 | ||
|
|
ee06d549e6 | ||
|
|
e7ab03e47f | ||
|
|
110d5971a7 | ||
|
|
7cc728a9c8 | ||
|
|
bad3850117 | ||
|
|
5a8ca9573c |
1
.github/workflows/integrationci.yaml
vendored
1
.github/workflows/integrationci.yaml
vendored
@@ -53,7 +53,6 @@ jobs:
|
||||
- queriermetrics
|
||||
- querierscalar
|
||||
- queriercommon
|
||||
- querierai
|
||||
- rawexportdata
|
||||
- promqlconformance
|
||||
- querierauthz
|
||||
|
||||
@@ -1497,6 +1497,8 @@ components:
|
||||
- cloudsql_postgres
|
||||
- memorystore_redis
|
||||
- computeengine
|
||||
- gke
|
||||
- cloudstorage
|
||||
type: string
|
||||
CloudintegrationtypesServiceMetadata:
|
||||
properties:
|
||||
@@ -6900,7 +6902,6 @@ components:
|
||||
Querybuildertypesv5QueryEnvelope:
|
||||
discriminator:
|
||||
mapping:
|
||||
builder_ai_query: '#/components/schemas/Querybuildertypesv5QueryEnvelopeBuilderAI'
|
||||
builder_formula: '#/components/schemas/Querybuildertypesv5QueryEnvelopeFormula'
|
||||
builder_query: '#/components/schemas/Querybuildertypesv5QueryEnvelopeBuilder'
|
||||
builder_trace_operator: '#/components/schemas/Querybuildertypesv5QueryEnvelopeTraceOperator'
|
||||
@@ -6909,7 +6910,6 @@ components:
|
||||
propertyName: type
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryEnvelopeBuilder'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryEnvelopeBuilderAI'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryEnvelopeFormula'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryEnvelopeTraceOperator'
|
||||
- $ref: '#/components/schemas/Querybuildertypesv5QueryEnvelopePromQL'
|
||||
@@ -6924,15 +6924,6 @@ components:
|
||||
required:
|
||||
- type
|
||||
type: object
|
||||
Querybuildertypesv5QueryEnvelopeBuilderAI:
|
||||
properties:
|
||||
spec:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregation'
|
||||
type:
|
||||
$ref: '#/components/schemas/Querybuildertypesv5QueryType'
|
||||
required:
|
||||
- type
|
||||
type: object
|
||||
Querybuildertypesv5QueryEnvelopeClickHouseSQL:
|
||||
properties:
|
||||
spec:
|
||||
@@ -7046,7 +7037,6 @@ components:
|
||||
Querybuildertypesv5QueryType:
|
||||
enum:
|
||||
- builder_query
|
||||
- builder_ai_query
|
||||
- builder_formula
|
||||
- builder_trace_operator
|
||||
- clickhouse_sql
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { AlertRuleStatsPayload } from 'types/api/alerts/def';
|
||||
import { RuleStatsProps } from 'types/api/alerts/ruleStats';
|
||||
|
||||
const ruleStats = async (
|
||||
props: RuleStatsProps,
|
||||
): Promise<SuccessResponse<AlertRuleStatsPayload> | ErrorResponse> => {
|
||||
try {
|
||||
const response = await axios.post(`/rules/${props.id}/history/stats`, {
|
||||
start: props.start,
|
||||
end: props.end,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default ruleStats;
|
||||
@@ -1,33 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { AlertRuleTimelineGraphResponsePayload } from 'types/api/alerts/def';
|
||||
import { GetTimelineGraphRequestProps } from 'types/api/alerts/timelineGraph';
|
||||
|
||||
const timelineGraph = async (
|
||||
props: GetTimelineGraphRequestProps,
|
||||
): Promise<
|
||||
SuccessResponse<AlertRuleTimelineGraphResponsePayload> | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`/rules/${props.id}/history/overall_status`,
|
||||
{
|
||||
start: props.start,
|
||||
end: props.end,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default timelineGraph;
|
||||
@@ -1,36 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { AlertRuleTimelineTableResponsePayload } from 'types/api/alerts/def';
|
||||
import { GetTimelineTableRequestProps } from 'types/api/alerts/timelineTable';
|
||||
|
||||
const timelineTable = async (
|
||||
props: GetTimelineTableRequestProps,
|
||||
): Promise<
|
||||
SuccessResponse<AlertRuleTimelineTableResponsePayload> | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
const response = await axios.post(`/rules/${props.id}/history/timeline`, {
|
||||
start: props.start,
|
||||
end: props.end,
|
||||
offset: props.offset,
|
||||
limit: props.limit,
|
||||
order: props.order,
|
||||
state: props.state,
|
||||
// TODO(shaheer): implement filters
|
||||
filters: props.filters,
|
||||
});
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default timelineTable;
|
||||
@@ -1,33 +0,0 @@
|
||||
import axios from 'api';
|
||||
import { ErrorResponseHandler } from 'api/ErrorResponseHandler';
|
||||
import { AxiosError } from 'axios';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { AlertRuleTopContributorsPayload } from 'types/api/alerts/def';
|
||||
import { TopContributorsProps } from 'types/api/alerts/topContributors';
|
||||
|
||||
const topContributors = async (
|
||||
props: TopContributorsProps,
|
||||
): Promise<
|
||||
SuccessResponse<AlertRuleTopContributorsPayload> | ErrorResponse
|
||||
> => {
|
||||
try {
|
||||
const response = await axios.post(
|
||||
`/rules/${props.id}/history/top_contributors`,
|
||||
{
|
||||
start: props.start,
|
||||
end: props.end,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
statusCode: 200,
|
||||
error: null,
|
||||
message: response.data.status,
|
||||
payload: response.data,
|
||||
};
|
||||
} catch (error) {
|
||||
return ErrorResponseHandler(error as AxiosError);
|
||||
}
|
||||
};
|
||||
|
||||
export default topContributors;
|
||||
@@ -2816,6 +2816,8 @@ export enum CloudintegrationtypesServiceIDDTO {
|
||||
cloudsql_postgres = 'cloudsql_postgres',
|
||||
memorystore_redis = 'memorystore_redis',
|
||||
computeengine = 'computeengine',
|
||||
gke = 'gke',
|
||||
cloudstorage = 'cloudstorage',
|
||||
}
|
||||
export type CloudintegrationtypesCloudIntegrationServiceDTOAnyOf = {
|
||||
/**
|
||||
@@ -4299,18 +4301,6 @@ export interface Querybuildertypesv5QueryEnvelopeBuilderDTO {
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderDTOType;
|
||||
}
|
||||
|
||||
export enum Querybuildertypesv5QueryEnvelopeBuilderAIDTOType {
|
||||
builder_ai_query = 'builder_ai_query',
|
||||
}
|
||||
export interface Querybuildertypesv5QueryEnvelopeBuilderAIDTO {
|
||||
spec?: Querybuildertypesv5QueryBuilderQueryGithubComSigNozSignozPkgTypesQuerybuildertypesQuerybuildertypesv5TraceAggregationDTO;
|
||||
/**
|
||||
* @type string
|
||||
* @enum builder_ai_query
|
||||
*/
|
||||
type: Querybuildertypesv5QueryEnvelopeBuilderAIDTOType;
|
||||
}
|
||||
|
||||
export interface Querybuildertypesv5QueryBuilderFormulaDTO {
|
||||
/**
|
||||
* @type boolean
|
||||
@@ -4494,7 +4484,6 @@ export interface Querybuildertypesv5QueryEnvelopeClickHouseSQLDTO {
|
||||
|
||||
export type Querybuildertypesv5QueryEnvelopeDTO =
|
||||
| Querybuildertypesv5QueryEnvelopeBuilderDTO
|
||||
| Querybuildertypesv5QueryEnvelopeBuilderAIDTO
|
||||
| Querybuildertypesv5QueryEnvelopeFormulaDTO
|
||||
| Querybuildertypesv5QueryEnvelopeTraceOperatorDTO
|
||||
| Querybuildertypesv5QueryEnvelopePromQLDTO
|
||||
@@ -8298,7 +8287,6 @@ export interface Querybuildertypesv5QueryRangeResponseDTO {
|
||||
|
||||
export enum Querybuildertypesv5QueryTypeDTO {
|
||||
builder_query = 'builder_query',
|
||||
builder_ai_query = 'builder_ai_query',
|
||||
builder_formula = 'builder_formula',
|
||||
builder_trace_operator = 'builder_trace_operator',
|
||||
clickhouse_sql = 'clickhouse_sql',
|
||||
|
||||
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1200" height="800" viewBox="-19.2 -28.483 166.401 170.898"><g transform="translate(0 -7.034)"><linearGradient id="a" x1="64" x2="64" y1="7.034" y2="120.789" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#4387fd"/><stop offset="1" stop-color="#4683ea"/></linearGradient><path fill="url(#a)" d="M27.79 115.217 1.54 69.749a11.5 11.5 0 0 1 0-11.499l26.25-45.467a11.5 11.5 0 0 1 9.96-5.75h52.5a11.5 11.5 0 0 1 9.959 5.75l26.25 45.467a11.5 11.5 0 0 1 0 11.5l-26.25 45.466a11.5 11.5 0 0 1-9.959 5.75h-52.5a11.5 11.5 0 0 1-9.96-5.75z"/></g><g transform="translate(0 -7.034)"><defs><path id="b" d="M27.791 115.217 1.541 69.749a11.5 11.5 0 0 1 0-11.499l26.25-45.467a11.5 11.5 0 0 1 9.959-5.75h52.5a11.5 11.5 0 0 1 9.96 5.75l26.25 45.467a11.5 11.5 0 0 1 0 11.5l-26.25 45.466a11.5 11.5 0 0 1-9.96 5.75h-52.5a11.5 11.5 0 0 1-9.959-5.75z"/></defs><clipPath id="c"><use xlink:href="#b" width="100%" height="100%" overflow="visible"/></clipPath><path d="m49.313 53.875-7.01 6.99 5.957 5.958-5.898 10.476 44.635 44.636 10.816.002L118.936 84 85.489 50.55z" clip-path="url(#c)" opacity=".07"/></g><path fill="#fff" d="M84.7 43.236H43.264c-.667 0-1.212.546-1.212 1.214v8.566c0 .666.546 1.212 1.212 1.212H84.7c.667 0 1.213-.546 1.213-1.212v-8.568c0-.666-.545-1.213-1.212-1.213m-6.416 7.976a2.484 2.484 0 0 1-2.477-2.48 2.475 2.475 0 0 1 2.477-2.477c1.37 0 2.48 1.103 2.48 2.477a2.48 2.48 0 0 1-2.48 2.48m6.415 8.491-41.436.002c-.667 0-1.212.546-1.212 1.214v8.565c0 .666.546 1.213 1.212 1.213H84.7c.667 0 1.213-.547 1.213-1.213v-8.567c0-.666-.545-1.214-1.212-1.214m-6.416 7.976a2.483 2.483 0 0 1-2.477-2.48 2.475 2.475 0 0 1 2.477-2.477 2.48 2.48 0 1 1 0 4.956"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" viewBox="0 0 24 24"><defs><style>.cls-1{fill:#aecbfa;}.cls-2{fill:#669df6;}.cls-3{fill:#4285f4;}.cls-4{fill:#fff;}</style></defs><title>Icon_24px_CloudStorage_Color</title><g data-name="Product Icons"><rect class="cls-1" x="2" y="4" width="20" height="7"/><rect class="cls-2" x="20" y="4" width="2" height="7"/><polygon class="cls-3" points="22 4 20 4 20 11 22 4"/><rect class="cls-2" x="2" y="4" width="2" height="7"/><rect class="cls-4" x="6" y="7" width="6" height="1"/><rect class="cls-4" x="15" y="6" width="3" height="3" rx="1.5"/><rect class="cls-1" x="2" y="13" width="20" height="7"/><rect class="cls-2" x="20" y="13" width="2" height="7"/><polygon class="cls-3" points="22 13 20 13 20 20 22 13"/><rect class="cls-2" x="2" y="13" width="2" height="7"/><rect class="cls-4" x="6" y="16" width="6" height="1"/><rect class="cls-4" x="15" y="15" width="3" height="3" rx="1.5"/></g></svg>
|
||||
|
Before Width: | Height: | Size: 1.7 KiB After Width: | Height: | Size: 958 B |
@@ -1 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24"><path d="M19.73 6.56a1.73 1.73 0 0 0-1.68 1.68 1.83 1.83 0 0 0 .89 1.48v6.9l-5.16 3.06.8 1.28 5.55-3.25a.84.84 0 0 0 .4-.69v-7.3a1.64 1.64 0 0 0 .89-1.48 1.61 1.61 0 0 0-1.69-1.68" style="fill:#aecbfa"/><path d="m18 5.48-5.61-3.16a1.18 1.18 0 0 0-.79 0L5.25 6a1.72 1.72 0 0 0-2.68 1.35A1.73 1.73 0 0 0 4.26 9a1.73 1.73 0 0 0 1.68-1.65L12 3.9l5.15 3ZM11.2 18.5a1.57 1.57 0 0 0-.89.29l-5.16-3V9.92H3.56v6.31a.84.84 0 0 0 .4.69L9.52 20v.09a1.69 1.69 0 0 0 3.37 0 1.65 1.65 0 0 0-1.69-1.59" data-name="Path" style="fill:#aecbfa"/><path d="M16.96 8.63 12.1 5.78 7.13 8.63l4.97 2.77z" data-name="Path" style="fill:#669df6"/><path d="M12.1 12.38 6.84 9.32v2.47l5.26 2.96zM12.1 15.73l-5.26-3.05v2.07l5.26 3.06z" style="fill:#669df6"/><path d="M12.09 12.38v2.37l5.26-3.06V9.33Zm4.32-.94a.38.38 0 1 1 0-.76.38.38 0 0 1 0 .76M12.09 15.73v2.07l5.26-3.05v-2.07Zm4.32-1.07a.38.38 0 1 1 0-.76.38.38 0 0 1 0 .76" style="fill:#4285f4"/></svg>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" viewBox="0 0 24 24"><defs><style>.cls-1{fill:#4285f4;}.cls-1,.cls-2,.cls-4{fill-rule:evenodd;}.cls-2{fill:#669df6;}.cls-3,.cls-4{fill:#aecbfa;}</style></defs><title>Icon_24px_K8Engine_Color</title><g data-name="Product Icons"><g ><polygon class="cls-1" points="14.68 13.06 19.23 15.69 19.23 16.68 14.29 13.83 14.68 13.06"/><polygon class="cls-2" points="9.98 13.65 4.77 16.66 4.45 15.86 9.53 12.92 9.98 13.65"/><rect class="cls-3" x="11.55" y="3.29" width="0.86" height="5.78"/><path class="cls-4" d="M3.25,7V17L12,22l8.74-5V7L12,2Zm15.63,8.89L12,19.78,5.12,15.89V8.11L12,4.22l6.87,3.89v7.78Z"/><polygon class="cls-4" points="11.98 11.5 15.96 9.21 11.98 6.91 8.01 9.21 11.98 11.5"/><polygon class="cls-2" points="11.52 12.3 7.66 10.01 7.66 14.6 11.52 16.89 11.52 12.3"/><polygon class="cls-1" points="12.48 12.3 12.48 16.89 16.34 14.6 16.34 10.01 12.48 12.3"/></g></g></svg>
|
||||
|
Before Width: | Height: | Size: 988 B After Width: | Height: | Size: 941 B |
@@ -102,6 +102,15 @@ interface QuerySearchProps {
|
||||
showFilterSuggestionsWithoutMetric?: boolean;
|
||||
/** When set, the editor shows only the user expression; API/filter uses `initial AND (user)`. */
|
||||
initialExpression?: string;
|
||||
/** When set, replaces the generic value-suggestion API with a custom fetcher. */
|
||||
valueSuggestionsOverride?: (
|
||||
key: string,
|
||||
searchText: string,
|
||||
) => Promise<{
|
||||
stringValues: string[];
|
||||
numberValues: number[];
|
||||
complete: boolean;
|
||||
}>;
|
||||
}
|
||||
|
||||
function QuerySearch({
|
||||
@@ -115,6 +124,7 @@ function QuerySearch({
|
||||
showFilterSuggestionsWithoutMetric,
|
||||
initialExpression,
|
||||
metricNamespace,
|
||||
valueSuggestionsOverride,
|
||||
}: QuerySearchProps): JSX.Element {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
const [valueSuggestions, setValueSuggestions] = useState<any[]>([]);
|
||||
@@ -484,13 +494,24 @@ function QuerySearch({
|
||||
const sanitizedSearchText = searchText ? searchText?.trim() : '';
|
||||
|
||||
try {
|
||||
const response = await getValueSuggestions({
|
||||
key,
|
||||
searchText: sanitizedSearchText,
|
||||
signal: dataSource,
|
||||
signalSource: signalSource as 'meter' | '',
|
||||
metricName: debouncedMetricName ?? undefined,
|
||||
});
|
||||
const values = valueSuggestionsOverride
|
||||
? await valueSuggestionsOverride(key, sanitizedSearchText)
|
||||
: await getValueSuggestions({
|
||||
key,
|
||||
searchText: sanitizedSearchText,
|
||||
signal: dataSource,
|
||||
signalSource: signalSource as 'meter' | '',
|
||||
metricName: debouncedMetricName ?? undefined,
|
||||
}).then((response) => {
|
||||
const responseData = response.data as any;
|
||||
const data = responseData.data || {};
|
||||
const values = data.values || {};
|
||||
return {
|
||||
stringValues: values.stringValues || [],
|
||||
numberValues: values.numberValues || [],
|
||||
complete: data.complete ?? false,
|
||||
};
|
||||
});
|
||||
|
||||
// Skip updates if component unmounted or key changed
|
||||
if (
|
||||
@@ -502,8 +523,6 @@ function QuerySearch({
|
||||
}
|
||||
|
||||
// Process the response data
|
||||
const responseData = response.data as any;
|
||||
const values = responseData.data?.values || {};
|
||||
const stringValues = values.stringValues || [];
|
||||
const numberValues = values.numberValues || [];
|
||||
|
||||
@@ -584,6 +603,7 @@ function QuerySearch({
|
||||
debouncedMetricName,
|
||||
signalSource,
|
||||
toggleSuggestions,
|
||||
valueSuggestionsOverride,
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -45,4 +45,5 @@ export enum LOCALSTORAGE {
|
||||
DASHBOARDS_LIST_VISIBLE_COLUMNS = 'DASHBOARDS_LIST_VISIBLE_COLUMNS',
|
||||
DASHBOARDS_LIST_VIEWS = 'DASHBOARDS_LIST_VIEWS',
|
||||
DASHBOARD_V2_PANEL_COLUMN_WIDTHS = 'DASHBOARD_V2_PANEL_COLUMN_WIDTHS',
|
||||
LLM_ATTRIBUTE_MAPPING_TEST_SPAN = 'LLM_ATTRIBUTE_MAPPING_TEST_SPAN',
|
||||
}
|
||||
|
||||
@@ -20,10 +20,6 @@ export const REACT_QUERY_KEY = {
|
||||
DELETE_DASHBOARD: 'DELETE_DASHBOARD',
|
||||
LOGS_PIPELINE_PREVIEW: 'LOGS_PIPELINE_PREVIEW',
|
||||
ALERT_RULE_DETAILS: 'ALERT_RULE_DETAILS',
|
||||
ALERT_RULE_STATS: 'ALERT_RULE_STATS',
|
||||
ALERT_RULE_TOP_CONTRIBUTORS: 'ALERT_RULE_TOP_CONTRIBUTORS',
|
||||
ALERT_RULE_TIMELINE_TABLE: 'ALERT_RULE_TIMELINE_TABLE',
|
||||
ALERT_RULE_TIMELINE_GRAPH: 'ALERT_RULE_TIMELINE_GRAPH',
|
||||
GET_CONSUMER_LAG_DETAILS: 'GET_CONSUMER_LAG_DETAILS',
|
||||
TOGGLE_ALERT_STATE: 'TOGGLE_ALERT_STATE',
|
||||
GET_ALL_ALERTS: 'GET_ALL_ALERTS',
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import { useGetAlertRuleDetailsStats } from 'pages/AlertDetails/hooks';
|
||||
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
|
||||
import { StatsTimeSeriesItem } from 'types/api/alerts/def';
|
||||
|
||||
import AverageResolutionCard from '../AverageResolutionCard/AverageResolutionCard';
|
||||
import StatsCard from '../StatsCard/StatsCard';
|
||||
@@ -25,24 +26,59 @@ type StatsCardsRendererProps = {
|
||||
};
|
||||
|
||||
// TODO(shaheer): render the DataStateRenderer inside the TotalTriggeredCard/AverageResolutionCard, it should display the title
|
||||
type AdaptedStatsData = {
|
||||
totalCurrentTriggers: number;
|
||||
totalPastTriggers: number;
|
||||
currentAvgResolutionTime: string;
|
||||
pastAvgResolutionTime: string;
|
||||
currentTriggersSeries: StatsTimeSeriesItem[];
|
||||
currentAvgResolutionTimeSeries: StatsTimeSeriesItem[];
|
||||
};
|
||||
|
||||
function StatsCardsRenderer({
|
||||
setTotalCurrentTriggers,
|
||||
}: StatsCardsRendererProps): JSX.Element {
|
||||
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
|
||||
useGetAlertRuleDetailsStats();
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.payload?.data?.totalCurrentTriggers !== undefined) {
|
||||
setTotalCurrentTriggers(data.payload.data.totalCurrentTriggers);
|
||||
const adaptedData = useMemo((): AdaptedStatsData | null => {
|
||||
if (!data?.data) {
|
||||
return null;
|
||||
}
|
||||
}, [data, setTotalCurrentTriggers]);
|
||||
const statsData = data.data;
|
||||
|
||||
const adaptTimeSeries = (
|
||||
series: typeof statsData.currentTriggersSeries,
|
||||
): StatsTimeSeriesItem[] =>
|
||||
series?.values?.map((item) => ({
|
||||
timestamp: item.timestamp ?? 0,
|
||||
value: String(item.value ?? 0),
|
||||
})) ?? [];
|
||||
|
||||
return {
|
||||
totalCurrentTriggers: statsData.totalCurrentTriggers,
|
||||
totalPastTriggers: statsData.totalPastTriggers,
|
||||
currentAvgResolutionTime: String(statsData.currentAvgResolutionTime),
|
||||
pastAvgResolutionTime: String(statsData.pastAvgResolutionTime),
|
||||
currentTriggersSeries: adaptTimeSeries(statsData.currentTriggersSeries),
|
||||
currentAvgResolutionTimeSeries: adaptTimeSeries(
|
||||
statsData.currentAvgResolutionTimeSeries,
|
||||
),
|
||||
};
|
||||
}, [data?.data]);
|
||||
|
||||
useEffect(() => {
|
||||
if (adaptedData?.totalCurrentTriggers !== undefined) {
|
||||
setTotalCurrentTriggers(adaptedData.totalCurrentTriggers);
|
||||
}
|
||||
}, [adaptedData, setTotalCurrentTriggers]);
|
||||
|
||||
return (
|
||||
<DataStateRenderer
|
||||
isLoading={isLoading}
|
||||
isRefetching={isRefetching}
|
||||
isError={isError || !isValidRuleId || !ruleId}
|
||||
data={data?.payload?.data || null}
|
||||
data={adaptedData}
|
||||
>
|
||||
{(data): JSX.Element => {
|
||||
const {
|
||||
@@ -60,7 +96,7 @@ function StatsCardsRenderer({
|
||||
<TotalTriggeredCard
|
||||
totalCurrentTriggers={totalCurrentTriggers}
|
||||
totalPastTriggers={totalPastTriggers}
|
||||
timeSeries={currentTriggersSeries?.values}
|
||||
timeSeries={currentTriggersSeries}
|
||||
/>
|
||||
) : (
|
||||
<StatsCard
|
||||
@@ -77,7 +113,7 @@ function StatsCardsRenderer({
|
||||
<AverageResolutionCard
|
||||
currentAvgResolutionTime={currentAvgResolutionTime}
|
||||
pastAvgResolutionTime={pastAvgResolutionTime}
|
||||
timeSeries={currentAvgResolutionTimeSeries?.values}
|
||||
timeSeries={currentAvgResolutionTimeSeries}
|
||||
/>
|
||||
) : (
|
||||
<StatsCard
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useGetAlertRuleDetailsTopContributors } from 'pages/AlertDetails/hooks';
|
||||
import { labelsArrayToObject } from 'container/AlertHistory/utils/labelAdapters';
|
||||
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
|
||||
import { AlertRuleStats } from 'types/api/alerts/def';
|
||||
import { AlertRuleStats, AlertRuleTopContributors } from 'types/api/alerts/def';
|
||||
|
||||
import TopContributorsCard from '../TopContributorsCard/TopContributorsCard';
|
||||
|
||||
@@ -13,15 +15,27 @@ function TopContributorsRenderer({
|
||||
}: TopContributorsRendererProps): JSX.Element {
|
||||
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
|
||||
useGetAlertRuleDetailsTopContributors();
|
||||
const response = data?.payload?.data;
|
||||
|
||||
// TODO(shaheer): render the DataStateRenderer inside the TopContributorsCard, it should display the title and view all
|
||||
const adaptedData = useMemo((): AlertRuleTopContributors[] | null => {
|
||||
if (!data?.data) {
|
||||
return null;
|
||||
}
|
||||
return data.data.map((contributor) => ({
|
||||
fingerprint: contributor.fingerprint,
|
||||
count: contributor.count,
|
||||
labels: labelsArrayToObject(contributor.labels),
|
||||
relatedLogsLink: contributor.relatedLogsLink ?? '',
|
||||
relatedTracesLink: contributor.relatedTracesLink ?? '',
|
||||
}));
|
||||
}, [data?.data]);
|
||||
|
||||
return (
|
||||
<DataStateRenderer
|
||||
isLoading={isLoading}
|
||||
isRefetching={isRefetching}
|
||||
isError={isError || !isValidRuleId || !ruleId}
|
||||
data={response || null}
|
||||
data={adaptedData}
|
||||
>
|
||||
{(topContributorsData): JSX.Element => (
|
||||
<TopContributorsCard
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
export const ALERT_STATUS: { [key: string]: number } = {
|
||||
firing: 0,
|
||||
inactive: 1,
|
||||
export const ALERT_STATUS: Record<RuletypesAlertStateDTO, number> & {
|
||||
[key: string]: number;
|
||||
} = {
|
||||
[RuletypesAlertStateDTO.firing]: 0,
|
||||
[RuletypesAlertStateDTO.inactive]: 1,
|
||||
normal: 1,
|
||||
'no-data': 2,
|
||||
disabled: 3,
|
||||
muted: 4,
|
||||
[RuletypesAlertStateDTO.pending]: 2,
|
||||
[RuletypesAlertStateDTO.recovering]: 2,
|
||||
'no-data': 3,
|
||||
[RuletypesAlertStateDTO.nodata]: 3,
|
||||
[RuletypesAlertStateDTO.disabled]: 4,
|
||||
muted: 5,
|
||||
};
|
||||
|
||||
export const STATE_VS_COLOR: {
|
||||
@@ -16,9 +22,10 @@ export const STATE_VS_COLOR: {
|
||||
{
|
||||
0: { stroke: Color.BG_CHERRY_500, fill: Color.BG_CHERRY_500 },
|
||||
1: { stroke: Color.BG_FOREST_500, fill: Color.BG_FOREST_500 },
|
||||
2: { stroke: Color.BG_SIENNA_400, fill: Color.BG_SIENNA_400 },
|
||||
3: { stroke: Color.BG_VANILLA_400, fill: Color.BG_VANILLA_400 },
|
||||
4: { stroke: Color.BG_INK_100, fill: Color.BG_INK_100 },
|
||||
2: { stroke: Color.BG_AMBER_500, fill: Color.BG_AMBER_500 },
|
||||
3: { stroke: Color.BG_SIENNA_400, fill: Color.BG_SIENNA_400 },
|
||||
4: { stroke: Color.BG_VANILLA_400, fill: Color.BG_VANILLA_400 },
|
||||
5: { stroke: Color.BG_INK_100, fill: Color.BG_INK_100 },
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useMemo } from 'react';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { useGetAlertRuleDetailsTimelineGraphData } from 'pages/AlertDetails/hooks';
|
||||
import DataStateRenderer from 'periscope/components/DataStateRenderer/DataStateRenderer';
|
||||
import { AlertRuleTimelineGraphResponse } from 'types/api/alerts/def';
|
||||
|
||||
import Graph from '../Graph/Graph';
|
||||
|
||||
@@ -18,26 +20,16 @@ function GraphWrapper({
|
||||
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
|
||||
useGetAlertRuleDetailsTimelineGraphData();
|
||||
|
||||
// TODO(shaheer): uncomment when the API is ready for
|
||||
// const { startTime } = useAlertHistoryQueryParams();
|
||||
|
||||
// const [isVerticalGraph, setIsVerticalGraph] = useState(false);
|
||||
|
||||
// useEffect(() => {
|
||||
// const checkVerticalGraph = (): void => {
|
||||
// if (startTime) {
|
||||
// const startTimeDate = dayjs(Number(startTime));
|
||||
// const twentyFourHoursAgo = dayjs().subtract(
|
||||
// HORIZONTAL_GRAPH_HOURS_THRESHOLD,
|
||||
// DAYJS_MANIPULATE_TYPES.HOUR,
|
||||
// );
|
||||
|
||||
// setIsVerticalGraph(startTimeDate.isBefore(twentyFourHoursAgo));
|
||||
// }
|
||||
// };
|
||||
|
||||
// checkVerticalGraph();
|
||||
// }, [startTime]);
|
||||
const adaptedData = useMemo((): AlertRuleTimelineGraphResponse[] | null => {
|
||||
if (!data?.data) {
|
||||
return null;
|
||||
}
|
||||
return data.data.map((item) => ({
|
||||
start: item.start,
|
||||
end: item.end,
|
||||
state: item.state as AlertRuleTimelineGraphResponse['state'],
|
||||
}));
|
||||
}, [data?.data]);
|
||||
|
||||
return (
|
||||
<div className="timeline-graph">
|
||||
@@ -49,7 +41,7 @@ function GraphWrapper({
|
||||
isLoading={isLoading}
|
||||
isError={isError || !isValidRuleId || !ruleId}
|
||||
isRefetching={isRefetching}
|
||||
data={data?.payload?.data || null}
|
||||
data={adaptedData}
|
||||
>
|
||||
{(data): JSX.Element => <Graph type="horizontal" data={data} />}
|
||||
</DataStateRenderer>
|
||||
|
||||
@@ -1,11 +1,35 @@
|
||||
.timeline-table {
|
||||
border-top: 1px solid var(--l1-border);
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
margin-top: 4px;
|
||||
min-height: 600px;
|
||||
|
||||
&__filter {
|
||||
padding: 12px 16px;
|
||||
background: var(--l1-background);
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
}
|
||||
|
||||
&__filter-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
&__filter-search {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
&__filter--loading,
|
||||
&__filter--loading-skeleton {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
.ant-table {
|
||||
background: var(--l1-background);
|
||||
&-placeholder {
|
||||
background: var(--l1-background) !important;
|
||||
}
|
||||
&-cell {
|
||||
padding: 12px 16px !important;
|
||||
vertical-align: baseline;
|
||||
@@ -23,6 +47,9 @@
|
||||
&-tbody > tr > td {
|
||||
border: none;
|
||||
}
|
||||
&-footer {
|
||||
background-color: var(--l1-background);
|
||||
}
|
||||
}
|
||||
|
||||
.label-filter {
|
||||
@@ -86,4 +113,38 @@
|
||||
background: var(--l2-background);
|
||||
}
|
||||
}
|
||||
|
||||
&__error {
|
||||
display: flex;
|
||||
align-self: flex-start;
|
||||
justify-content: flex-start;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
&__pagination {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
padding: var(--spacing-6) var(--spacing-8);
|
||||
background: var(--l1-background);
|
||||
|
||||
.pagination-controls {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
|
||||
.ant-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 4px;
|
||||
min-width: 24px;
|
||||
height: 24px;
|
||||
|
||||
&:disabled {
|
||||
opacity: 0.4;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,52 +1,126 @@
|
||||
import { HTMLAttributes, useMemo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Table } from 'antd';
|
||||
import { HTMLAttributes, useCallback, useMemo } from 'react';
|
||||
import { Button, Skeleton, Table } from 'antd';
|
||||
import { ChevronLeft, ChevronRight } from '@signozhq/icons';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { initialFilters } from 'constants/queryBuilder';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import ErrorContent from 'components/ErrorModal/components/ErrorContent';
|
||||
import {
|
||||
QuerySearchV2Provider,
|
||||
useExpression,
|
||||
useInputExpression,
|
||||
useQuerySearchOnChange,
|
||||
useQuerySearchOnRun,
|
||||
} from 'components/QueryBuilderV2';
|
||||
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
|
||||
import { initialQueryBuilderFormValuesMap } from 'constants/queryBuilder';
|
||||
import RunQueryBtn from 'container/QueryBuilder/components/RunQueryBtn/RunQueryBtn';
|
||||
import {
|
||||
useGetAlertRuleDetailsTimelineTable,
|
||||
useTimelineTable,
|
||||
} from 'pages/AlertDetails/hooks';
|
||||
import { labelsArrayToObject } from 'container/AlertHistory/utils/labelAdapters';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
import { AlertRuleTimelineTableResponse } from 'types/api/alerts/def';
|
||||
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import { useAlertHistoryFilterSuggestions } from './useAlertHistoryFilterSuggestions';
|
||||
import { timelineTableColumns } from './useTimelineTable';
|
||||
|
||||
import './Table.styles.scss';
|
||||
|
||||
function TimelineTable(): JSX.Element {
|
||||
const [filters, setFilters] = useState<TagFilter>(initialFilters);
|
||||
export const ALERT_HISTORY_EXPRESSION_KEY = 'alertHistoryExpression';
|
||||
|
||||
const { isLoading, isRefetching, isError, data, isValidRuleId, ruleId } =
|
||||
useGetAlertRuleDetailsTimelineTable({ filters });
|
||||
function TimelineTableContent(): JSX.Element {
|
||||
const expression = useExpression();
|
||||
const inputExpression = useInputExpression();
|
||||
const querySearchOnChange = useQuerySearchOnChange();
|
||||
const querySearchOnRun = useQuerySearchOnRun();
|
||||
|
||||
const {
|
||||
isLoading,
|
||||
isRefetching,
|
||||
isError,
|
||||
data,
|
||||
error,
|
||||
ruleId,
|
||||
refetch,
|
||||
cancel,
|
||||
} = useGetAlertRuleDetailsTimelineTable({ filterExpression: expression });
|
||||
|
||||
const apiError = useMemo(() => convertToApiError(error), [error]);
|
||||
|
||||
const { hardcodedAttributeKeys, valueSuggestionsOverride, isLoadingKeys } =
|
||||
useAlertHistoryFilterSuggestions(ruleId ?? null);
|
||||
|
||||
const { timelineData, totalItems, nextCursor } = useMemo(() => {
|
||||
const response = data?.data;
|
||||
const items: AlertRuleTimelineTableResponse[] | undefined =
|
||||
response?.items?.map((item) => {
|
||||
return {
|
||||
ruleID: item.ruleId,
|
||||
ruleName: item.ruleName,
|
||||
overallState: item.overallState as string,
|
||||
overallStateChanged: item.overallStateChanged,
|
||||
state: item.state as string,
|
||||
stateChanged: item.stateChanged,
|
||||
unixMilli: item.unixMilli,
|
||||
fingerprint: item.fingerprint,
|
||||
value: item.value,
|
||||
labels: labelsArrayToObject(item.labels),
|
||||
relatedLogsLink: item.relatedLogsLink,
|
||||
relatedTracesLink: item.relatedTracesLink,
|
||||
};
|
||||
});
|
||||
|
||||
const { timelineData, totalItems, labels } = useMemo(() => {
|
||||
const response = data?.payload?.data;
|
||||
return {
|
||||
timelineData: response?.items,
|
||||
totalItems: response?.total,
|
||||
labels: response?.labels,
|
||||
timelineData: items,
|
||||
totalItems: response?.total ?? 0,
|
||||
nextCursor: response?.nextCursor,
|
||||
};
|
||||
}, [data?.payload?.data]);
|
||||
}, [data?.data]);
|
||||
|
||||
const { paginationConfig, onChangeHandler } = useTimelineTable({
|
||||
const {
|
||||
paginationConfig,
|
||||
onChangeHandler,
|
||||
handleNextPage,
|
||||
handlePrevPage,
|
||||
hasNextPage,
|
||||
hasPrevPage,
|
||||
} = useTimelineTable({
|
||||
totalItems: totalItems ?? 0,
|
||||
nextCursor,
|
||||
});
|
||||
|
||||
const { t } = useTranslation('common');
|
||||
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
|
||||
if (isError || !isValidRuleId || !ruleId) {
|
||||
return <div>{t('something_went_wrong')}</div>;
|
||||
}
|
||||
const handleRunQuery = useCallback(
|
||||
(updatedExpression?: string): void => {
|
||||
const nextExpression = updatedExpression ?? inputExpression;
|
||||
querySearchOnRun(nextExpression);
|
||||
|
||||
if (nextExpression === expression) {
|
||||
refetch();
|
||||
}
|
||||
},
|
||||
[querySearchOnRun, refetch, inputExpression, expression],
|
||||
);
|
||||
|
||||
const queryData = useMemo(
|
||||
() => ({
|
||||
...initialQueryBuilderFormValuesMap.logs,
|
||||
queryName: 'A',
|
||||
dataSource: DataSource.LOGS,
|
||||
filter: { expression },
|
||||
expression,
|
||||
}),
|
||||
[expression],
|
||||
);
|
||||
|
||||
const handleRowClick = (
|
||||
record: AlertRuleTimelineTableResponse,
|
||||
): HTMLAttributes<AlertRuleTimelineTableResponse> => ({
|
||||
onClick: (): void => {
|
||||
logEvent('Alert history: Timeline table row: Clicked', {
|
||||
void logEvent('Alert history: Timeline table row: Clicked', {
|
||||
ruleId: record.ruleID,
|
||||
labels: record.labels,
|
||||
});
|
||||
@@ -55,23 +129,106 @@ function TimelineTable(): JSX.Element {
|
||||
|
||||
return (
|
||||
<div className="timeline-table">
|
||||
{/* If we don't wait to have the keys, the QuerySearch will not render them at first usage */}
|
||||
{!isLoadingKeys && hardcodedAttributeKeys ? (
|
||||
<div className="timeline-table__filter">
|
||||
<div className="timeline-table__filter-row">
|
||||
<div className="timeline-table__filter-search">
|
||||
<QuerySearch
|
||||
onChange={querySearchOnChange}
|
||||
queryData={queryData}
|
||||
dataSource={DataSource.LOGS}
|
||||
onRun={handleRunQuery}
|
||||
hardcodedAttributeKeys={hardcodedAttributeKeys}
|
||||
valueSuggestionsOverride={valueSuggestionsOverride}
|
||||
/>
|
||||
</div>
|
||||
<RunQueryBtn
|
||||
isLoadingQueries={isLoading || isRefetching}
|
||||
onStageRunQuery={(): void => handleRunQuery()}
|
||||
handleCancelQuery={cancel}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="timeline-table__filter timeline-table__filter--loading">
|
||||
<Skeleton.Input
|
||||
className="timeline-table__filter--loading-skeleton"
|
||||
active
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<Table
|
||||
rowKey={(row): string => `${row.fingerprint}-${row.value}-${row.unixMilli}`}
|
||||
columns={timelineTableColumns({
|
||||
filters,
|
||||
labels: labels ?? {},
|
||||
setFilters,
|
||||
formatTimezoneAdjustedTimestamp,
|
||||
})}
|
||||
onRow={handleRowClick}
|
||||
dataSource={timelineData}
|
||||
pagination={paginationConfig}
|
||||
pagination={false}
|
||||
size="middle"
|
||||
onChange={onChangeHandler}
|
||||
loading={isLoading || isRefetching}
|
||||
locale={{
|
||||
emptyText:
|
||||
isError && apiError ? (
|
||||
<div className="timeline-table__error">
|
||||
<ErrorContent error={apiError} />
|
||||
</div>
|
||||
) : undefined,
|
||||
}}
|
||||
footer={(): JSX.Element => (
|
||||
<div className="timeline-table__pagination">
|
||||
<div className="timeline-table__pagination-info">
|
||||
{paginationConfig.showTotal?.(totalItems, [
|
||||
totalItems === 0
|
||||
? 0
|
||||
: ((paginationConfig.current ?? 1) - 1) *
|
||||
(paginationConfig.pageSize ?? 10) +
|
||||
1,
|
||||
Math.min(
|
||||
(paginationConfig.current ?? 1) * (paginationConfig.pageSize ?? 10),
|
||||
totalItems,
|
||||
),
|
||||
])}
|
||||
</div>
|
||||
<div className="pagination-controls">
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
disabled={!hasPrevPage}
|
||||
onClick={handlePrevPage}
|
||||
data-testid="timeline-prev-page"
|
||||
>
|
||||
<ChevronLeft size={14} />
|
||||
</Button>
|
||||
<Button
|
||||
type="text"
|
||||
size="small"
|
||||
disabled={!hasNextPage}
|
||||
onClick={handleNextPage}
|
||||
data-testid="timeline-next-page"
|
||||
>
|
||||
<ChevronRight size={14} />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TimelineTable(): JSX.Element {
|
||||
return (
|
||||
<QuerySearchV2Provider
|
||||
queryParamKey={ALERT_HISTORY_EXPRESSION_KEY}
|
||||
initialExpression=""
|
||||
persistOnUnmount
|
||||
>
|
||||
<TimelineTableContent />
|
||||
</QuerySearchV2Provider>
|
||||
);
|
||||
}
|
||||
|
||||
export default TimelineTable;
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import {
|
||||
getRuleHistoryFilterValues,
|
||||
useGetRuleHistoryFilterKeys,
|
||||
} from 'api/generated/services/rules';
|
||||
import { useAlertHistoryQueryParams } from 'pages/AlertDetails/hooks';
|
||||
import { QueryKeyDataSuggestionsProps } from 'types/api/querySuggestions/types';
|
||||
import { fieldContextToSuggestionContext } from 'container/AlertHistory/Timeline/Table/utils';
|
||||
|
||||
export interface AlertHistoryFilterSuggestions {
|
||||
hardcodedAttributeKeys: QueryKeyDataSuggestionsProps[];
|
||||
valueSuggestionsOverride: (
|
||||
key: string,
|
||||
searchText: string,
|
||||
) => Promise<{
|
||||
stringValues: string[];
|
||||
numberValues: number[];
|
||||
complete: boolean;
|
||||
}>;
|
||||
isLoadingKeys: boolean;
|
||||
}
|
||||
|
||||
export function useAlertHistoryFilterSuggestions(
|
||||
ruleId: string | null,
|
||||
): AlertHistoryFilterSuggestions {
|
||||
const { startTime, endTime } = useAlertHistoryQueryParams();
|
||||
|
||||
const { data: filterKeysData, isLoading: isLoadingKeys } =
|
||||
useGetRuleHistoryFilterKeys(
|
||||
{ id: ruleId ?? '' },
|
||||
{ startUnixMilli: startTime, endUnixMilli: endTime },
|
||||
{
|
||||
query: {
|
||||
enabled: !!ruleId,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const hardcodedAttributeKeys = useMemo((): QueryKeyDataSuggestionsProps[] => {
|
||||
const keys = filterKeysData?.data?.keys;
|
||||
if (!keys) {
|
||||
// by default, when QuerySearch keys fails, we don't render fallback keys
|
||||
// we just return empty to let user write whatever they want with no
|
||||
// key suggestion
|
||||
return [];
|
||||
}
|
||||
return Object.values(keys).flatMap((items) =>
|
||||
items.map(
|
||||
(item) =>
|
||||
({
|
||||
label: item.name,
|
||||
name: item.name,
|
||||
type: item.fieldDataType || 'string',
|
||||
signal: 'logs' as const,
|
||||
fieldDataType: item.fieldDataType,
|
||||
fieldContext: fieldContextToSuggestionContext(item.fieldContext),
|
||||
}) satisfies QueryKeyDataSuggestionsProps,
|
||||
),
|
||||
);
|
||||
}, [filterKeysData]);
|
||||
|
||||
const valueSuggestionsOverride = useCallback(
|
||||
async (
|
||||
key: string,
|
||||
searchText: string,
|
||||
): Promise<{
|
||||
stringValues: string[];
|
||||
numberValues: number[];
|
||||
complete: boolean;
|
||||
}> => {
|
||||
if (!ruleId) {
|
||||
return {
|
||||
stringValues: [],
|
||||
numberValues: [],
|
||||
complete: true,
|
||||
};
|
||||
}
|
||||
const response = await getRuleHistoryFilterValues(
|
||||
{ id: ruleId },
|
||||
{
|
||||
name: key,
|
||||
searchText,
|
||||
startUnixMilli: startTime,
|
||||
endUnixMilli: endTime,
|
||||
},
|
||||
);
|
||||
const values = response.data?.values;
|
||||
return {
|
||||
stringValues: values?.stringValues ?? [],
|
||||
numberValues: values?.numberValues ?? [],
|
||||
complete: response.data?.complete ?? false,
|
||||
};
|
||||
},
|
||||
[ruleId, startTime, endTime],
|
||||
);
|
||||
|
||||
return { hardcodedAttributeKeys, valueSuggestionsOverride, isLoadingKeys };
|
||||
}
|
||||
@@ -1,83 +1,15 @@
|
||||
import { useMemo } from 'react';
|
||||
import { Ellipsis, Search } from '@signozhq/icons';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { Button, TableColumnsType as ColumnsType } from 'antd';
|
||||
import ClientSideQBSearch, {
|
||||
AttributeKey,
|
||||
} from 'components/ClientSideQBSearch/ClientSideQBSearch';
|
||||
import { Ellipsis } from '@signozhq/icons';
|
||||
import { Button, TableColumnsType as ColumnsType, Tooltip } from 'antd';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { ConditionalAlertPopover } from 'container/AlertHistory/AlertPopover/AlertPopover';
|
||||
import { transformKeyValuesToAttributeValuesMap } from 'container/QueryBuilder/filters/utils';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { TimestampInput } from 'hooks/useTimezoneFormatter/useTimezoneFormatter';
|
||||
import AlertLabels, {
|
||||
AlertLabelsProps,
|
||||
} from 'pages/AlertDetails/AlertHeader/AlertLabels/AlertLabels';
|
||||
import AlertLabels from 'pages/AlertDetails/AlertHeader/AlertLabels/AlertLabels';
|
||||
import AlertState from 'pages/AlertDetails/AlertHeader/AlertState/AlertState';
|
||||
import { AlertRuleTimelineTableResponse } from 'types/api/alerts/def';
|
||||
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
const transformLabelsToQbKeys = (
|
||||
labels: AlertRuleTimelineTableResponse['labels'],
|
||||
): AttributeKey[] => Object.keys(labels).flatMap((key) => [{ key }]);
|
||||
|
||||
function LabelFilter({
|
||||
filters,
|
||||
setFilters,
|
||||
labels,
|
||||
}: {
|
||||
setFilters: (filters: TagFilter) => void;
|
||||
filters: TagFilter;
|
||||
labels: AlertLabelsProps['labels'];
|
||||
}): JSX.Element | null {
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
const { transformedKeys, attributesMap } = useMemo(
|
||||
() => ({
|
||||
transformedKeys: transformLabelsToQbKeys(labels || {}),
|
||||
attributesMap: transformKeyValuesToAttributeValuesMap(labels),
|
||||
}),
|
||||
[labels],
|
||||
);
|
||||
|
||||
const handleSearch = (tagFilters: TagFilter): void => {
|
||||
const tagFiltersLength = tagFilters.items.length;
|
||||
|
||||
if (
|
||||
(!tagFiltersLength && (!filters || !filters.items.length)) ||
|
||||
tagFiltersLength === filters?.items.length
|
||||
) {
|
||||
return;
|
||||
}
|
||||
setFilters(tagFilters);
|
||||
};
|
||||
|
||||
return (
|
||||
<ClientSideQBSearch
|
||||
onChange={handleSearch}
|
||||
filters={filters}
|
||||
className="alert-history-label-search"
|
||||
attributeKeys={transformedKeys}
|
||||
attributeValuesMap={attributesMap}
|
||||
suffixIcon={
|
||||
<Search
|
||||
size={14}
|
||||
color={isDarkMode ? Color.TEXT_VANILLA_100 : Color.TEXT_INK_100}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export const timelineTableColumns = ({
|
||||
filters,
|
||||
labels,
|
||||
setFilters,
|
||||
formatTimezoneAdjustedTimestamp,
|
||||
}: {
|
||||
filters: TagFilter;
|
||||
labels: AlertLabelsProps['labels'];
|
||||
setFilters: (filters: TagFilter) => void;
|
||||
formatTimezoneAdjustedTimestamp: (
|
||||
input: TimestampInput,
|
||||
format?: string,
|
||||
@@ -95,9 +27,7 @@ export const timelineTableColumns = ({
|
||||
),
|
||||
},
|
||||
{
|
||||
title: (
|
||||
<LabelFilter setFilters={setFilters} filters={filters} labels={labels} />
|
||||
),
|
||||
title: 'LABELS',
|
||||
dataIndex: 'labels',
|
||||
render: (labels): JSX.Element => (
|
||||
<div className="alert-rule-labels">
|
||||
@@ -119,15 +49,27 @@ export const timelineTableColumns = ({
|
||||
title: 'ACTIONS',
|
||||
width: 140,
|
||||
align: 'right',
|
||||
render: (record): JSX.Element => (
|
||||
<ConditionalAlertPopover
|
||||
relatedTracesLink={record.relatedTracesLink}
|
||||
relatedLogsLink={record.relatedLogsLink}
|
||||
>
|
||||
<Button type="text" ghost>
|
||||
<Ellipsis className="dropdown-icon" size="md" />
|
||||
</Button>
|
||||
</ConditionalAlertPopover>
|
||||
),
|
||||
render: (_, record): JSX.Element => {
|
||||
if (!record.relatedTracesLink && !record.relatedLogsLink) {
|
||||
return (
|
||||
<Tooltip title="No links available for this item">
|
||||
<Button type="text" ghost disabled>
|
||||
<Ellipsis className="dropdown-icon" size="md" />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<ConditionalAlertPopover
|
||||
relatedTracesLink={record.relatedTracesLink ?? ''}
|
||||
relatedLogsLink={record.relatedLogsLink ?? ''}
|
||||
>
|
||||
<Button type="text" ghost>
|
||||
<Ellipsis className="dropdown-icon" size="md" />
|
||||
</Button>
|
||||
</ConditionalAlertPopover>
|
||||
);
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import {
|
||||
Options,
|
||||
parseAsInteger,
|
||||
parseAsStringLiteral,
|
||||
useQueryState,
|
||||
UseQueryStateReturn,
|
||||
} from 'nuqs';
|
||||
import { TIMELINE_TABLE_PAGE_SIZE } from 'container/AlertHistory/constants';
|
||||
|
||||
const defaultNuqsOptions: Options = {
|
||||
history: 'push',
|
||||
};
|
||||
|
||||
export const TIMELINE_TABLE_PARAMS = {
|
||||
PAGE: 'page',
|
||||
ORDER: 'order',
|
||||
} as const;
|
||||
|
||||
const ORDER_VALUES = ['asc', 'desc'] as const;
|
||||
export type OrderDirection = (typeof ORDER_VALUES)[number];
|
||||
|
||||
export const useTimelineTablePage = (): UseQueryStateReturn<number, number> =>
|
||||
useQueryState(
|
||||
TIMELINE_TABLE_PARAMS.PAGE,
|
||||
parseAsInteger.withDefault(1).withOptions(defaultNuqsOptions),
|
||||
);
|
||||
|
||||
export const useTimelineTableOrder = (): UseQueryStateReturn<
|
||||
OrderDirection,
|
||||
OrderDirection
|
||||
> =>
|
||||
useQueryState(
|
||||
TIMELINE_TABLE_PARAMS.ORDER,
|
||||
parseAsStringLiteral(ORDER_VALUES)
|
||||
.withDefault('asc')
|
||||
.withOptions(defaultNuqsOptions),
|
||||
);
|
||||
|
||||
export function encodeCursor(page: number, limit: number): string | undefined {
|
||||
if (page <= 1) {
|
||||
return undefined;
|
||||
}
|
||||
const offset = (page - 1) * limit;
|
||||
// Backend uses base64.RawURLEncoding (URL-safe, no padding)
|
||||
return btoa(JSON.stringify({ offset, limit }))
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/, '');
|
||||
}
|
||||
|
||||
export function computeCursorForPage(page: number): string | undefined {
|
||||
return encodeCursor(page, TIMELINE_TABLE_PAGE_SIZE);
|
||||
}
|
||||
26
frontend/src/container/AlertHistory/Timeline/Table/utils.ts
Normal file
26
frontend/src/container/AlertHistory/Timeline/Table/utils.ts
Normal file
@@ -0,0 +1,26 @@
|
||||
import { TelemetrytypesFieldContextDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryKeyDataSuggestionsProps } from 'types/api/querySuggestions/types';
|
||||
|
||||
const fieldContextToSuggestionMap: Record<
|
||||
TelemetrytypesFieldContextDTO,
|
||||
QueryKeyDataSuggestionsProps['fieldContext']
|
||||
> = {
|
||||
[TelemetrytypesFieldContextDTO.resource]: 'resource',
|
||||
[TelemetrytypesFieldContextDTO.span]: 'span',
|
||||
[TelemetrytypesFieldContextDTO.attribute]: 'attribute',
|
||||
// no maps for the following values on suggestion context
|
||||
[TelemetrytypesFieldContextDTO.body]: undefined,
|
||||
[TelemetrytypesFieldContextDTO.metric]: undefined,
|
||||
[TelemetrytypesFieldContextDTO.log]: undefined,
|
||||
[TelemetrytypesFieldContextDTO['']]: undefined,
|
||||
};
|
||||
|
||||
export function fieldContextToSuggestionContext(
|
||||
fc: TelemetrytypesFieldContextDTO | undefined,
|
||||
): QueryKeyDataSuggestionsProps['fieldContext'] {
|
||||
if (fc === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return fieldContextToSuggestionMap[fc];
|
||||
}
|
||||
19
frontend/src/container/AlertHistory/utils/labelAdapters.ts
Normal file
19
frontend/src/container/AlertHistory/utils/labelAdapters.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
import type { Querybuildertypesv5LabelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type { Labels } from 'types/api/alerts/def';
|
||||
|
||||
export function labelsArrayToObject(
|
||||
labels: Querybuildertypesv5LabelDTO[] | null | undefined,
|
||||
): Labels {
|
||||
if (!labels) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return labels.reduce<Labels>((acc, label) => {
|
||||
const key = label.key?.name ?? '';
|
||||
const value = String(label.value ?? '');
|
||||
if (key) {
|
||||
acc[key] = value;
|
||||
}
|
||||
return acc;
|
||||
}, {});
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { sortByMeanDesc } from '../sortByMeanDesc';
|
||||
|
||||
interface Item {
|
||||
name: string;
|
||||
values: (number | null)[];
|
||||
}
|
||||
|
||||
const item = (name: string, values: (number | null)[]): Item => ({
|
||||
name,
|
||||
values,
|
||||
});
|
||||
|
||||
const sorted = (items: Item[]): string[] =>
|
||||
sortByMeanDesc(items, {
|
||||
getValues: (entry) => entry.values,
|
||||
getKey: (entry) => entry.name,
|
||||
}).map((entry) => entry.name);
|
||||
|
||||
describe('sortByMeanDesc', () => {
|
||||
it('orders items by descending mean', () => {
|
||||
expect(
|
||||
sorted([item('a', [1, 1]), item('b', [10, 20]), item('c', [5, 5])]),
|
||||
).toStrictEqual(['b', 'c', 'a']);
|
||||
});
|
||||
|
||||
it('sinks items with no finite values to the bottom', () => {
|
||||
expect(
|
||||
sorted([item('a', []), item('b', [NaN, Infinity]), item('c', [1])]),
|
||||
).toStrictEqual(['c', 'a', 'b']);
|
||||
});
|
||||
|
||||
it('ignores non-finite and null values when averaging', () => {
|
||||
// Mean over the finite values only is 10, so NaN must not poison it to last place.
|
||||
expect(
|
||||
sorted([item('a', [2, 2]), item('b', [10, NaN]), item('c', [4, null])]),
|
||||
).toStrictEqual(['b', 'c', 'a']);
|
||||
});
|
||||
|
||||
it('produces the same order whichever order the items arrive in', () => {
|
||||
const a = item('a', [5]);
|
||||
const b = item('b', [5]);
|
||||
const c = item('c', [9]);
|
||||
|
||||
expect(sorted([a, b, c])).toStrictEqual(sorted([c, b, a]));
|
||||
expect(sorted([b, a, c])).toStrictEqual(['c', 'a', 'b']);
|
||||
});
|
||||
|
||||
it('tiebreaks equal means on the key', () => {
|
||||
expect(sorted([item('b', [1]), item('a', [1])])).toStrictEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it('tiebreaks on the key for items that have no finite values either', () => {
|
||||
expect(sorted([item('b', []), item('a', [NaN])])).toStrictEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it('does not mutate the input array', () => {
|
||||
const items = [item('a', [1]), item('b', [9])];
|
||||
|
||||
expect(sorted(items)).toStrictEqual(['b', 'a']);
|
||||
expect(items.map((entry) => entry.name)).toStrictEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it('returns an empty array for no items', () => {
|
||||
expect(sorted([])).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
type MeanInput = number | null | undefined;
|
||||
|
||||
function finiteMean(values: Iterable<MeanInput>): number | null {
|
||||
let sum = 0;
|
||||
let count = 0;
|
||||
for (const value of values) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
sum += value;
|
||||
count += 1;
|
||||
}
|
||||
}
|
||||
return count > 0 ? sum / count : null;
|
||||
}
|
||||
|
||||
export interface SortByMeanDescOptions<T> {
|
||||
/** Numeric values of an item; non-finite entries are ignored. */
|
||||
getValues: (item: T) => Iterable<MeanInput>;
|
||||
/** Stable identity of an item, used to break ties on equal means. */
|
||||
getKey: (item: T) => string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Orders series by descending mean, on a copy (V1 parity: `utils/getSortedSeriesData`). The wire
|
||||
* order can't stand in for it: the backend returns series in Go map-iteration order.
|
||||
*
|
||||
* Call this before building the uPlot config and aligned data — those two and click attribution
|
||||
* all index the list positionally, and uPlot draws a stacked bar's segments in series-index order.
|
||||
*/
|
||||
export function sortByMeanDesc<T>(
|
||||
items: T[],
|
||||
{ getValues, getKey }: SortByMeanDescOptions<T>,
|
||||
): T[] {
|
||||
return items
|
||||
.map((item) => ({ item, mean: finiteMean(getValues(item)) }))
|
||||
.sort((a, b) => {
|
||||
if (a.mean !== null && b.mean !== null && a.mean !== b.mean) {
|
||||
return b.mean - a.mean;
|
||||
}
|
||||
if ((a.mean === null) !== (b.mean === null)) {
|
||||
return a.mean === null ? 1 : -1;
|
||||
}
|
||||
return getKey(a.item).localeCompare(getKey(b.item));
|
||||
})
|
||||
.map(({ item }) => item);
|
||||
}
|
||||
@@ -15,6 +15,18 @@ jest.mock('@signozhq/ui/sonner', () => ({
|
||||
},
|
||||
}));
|
||||
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import {
|
||||
mockUseAuthZDenyAll,
|
||||
mockUseAuthZGrantAll,
|
||||
} from 'lib/authz/utils/authz-test-utils';
|
||||
|
||||
// Admin gating on the write controls flows through useAuthZ. Mock it directly
|
||||
// (synchronous) so the functional tests stay synchronous; the read-only block
|
||||
// below flips it to deny-all.
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
const mockedUseAuthZ = useAuthZ as jest.MockedFunction<typeof useAuthZ>;
|
||||
|
||||
import {
|
||||
GROUPS_ENDPOINT,
|
||||
makeGroupsResponse,
|
||||
@@ -102,6 +114,8 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
beforeEach(() => {
|
||||
// Reset URL state between tests — jsdom shares window.location across a file.
|
||||
window.history.pushState(null, '', '/');
|
||||
// Default to an admin; the read-only block overrides this.
|
||||
mockedUseAuthZ.mockImplementation(mockUseAuthZGrantAll);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -507,4 +521,55 @@ describe('AttributeMappingsTab (integration)', () => {
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
// The write APIs (create/update/delete group & mapper) are Admin-only on the
|
||||
// backend, so a non-admin gets a read-only view: the data renders, but every
|
||||
// write control is hidden.
|
||||
describe('read-only (non-admin)', () => {
|
||||
beforeEach(() => {
|
||||
mockedUseAuthZ.mockImplementation(mockUseAuthZDenyAll);
|
||||
});
|
||||
|
||||
it('hides the "Add a new group" button', async () => {
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
expect(screen.queryByTestId('add-group-row')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the group enable toggle and actions menu', async () => {
|
||||
setupGroups();
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
expect(
|
||||
screen.queryByTestId('group-enabled-group-1'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('group-actions-group-1'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders mappers read-only: no "Add mapping" button or row actions', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
setupGroups();
|
||||
setupMappers([makeMapper({ id: 'mapper-1', name: 'gen_ai.request.model' })]);
|
||||
render(<AttributeMappingsTabWithStore />);
|
||||
|
||||
await screen.findByTestId('group-name-group-1');
|
||||
await expandGroup(user);
|
||||
|
||||
// The mapper still renders...
|
||||
await screen.findByTestId('mapper-target-mapper-1');
|
||||
// ...but every write control is gone.
|
||||
expect(screen.queryByTestId('add-mapper-group-1')).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByTestId('mapper-enabled-mapper-1'),
|
||||
).not.toBeInTheDocument();
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Mapping actions' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Switch } from '@signozhq/ui/switch';
|
||||
|
||||
import { DraftGroup } from 'container/LLMObservability/AttributeMapping/types';
|
||||
import { useCanManageAttributeMapping } from 'container/LLMObservability/AttributeMapping/hooks/useCanManageAttributeMapping';
|
||||
import GroupActionsMenu from '../GroupActionsMenu/GroupActionsMenu';
|
||||
import styles from './GroupHeaderActions.module.scss';
|
||||
|
||||
@@ -16,7 +17,11 @@ function GroupHeaderActions({
|
||||
onToggle,
|
||||
onEdit,
|
||||
onRemove,
|
||||
}: GroupHeaderActionsProps): JSX.Element {
|
||||
}: GroupHeaderActionsProps): JSX.Element | null {
|
||||
const canManage = useCanManageAttributeMapping();
|
||||
if (!canManage) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<div
|
||||
className={styles.actions}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
Mapper,
|
||||
} from 'container/LLMObservability/AttributeMapping/types';
|
||||
import { AttributeMappingEditor } from 'container/LLMObservability/AttributeMapping/hooks/useAttributeMappingEditor';
|
||||
import { useCanManageAttributeMapping } from 'container/LLMObservability/AttributeMapping/hooks/useCanManageAttributeMapping';
|
||||
import { COLUMN_COUNT } from '../constants';
|
||||
import MapperRow from '../MapperRow/MapperRow';
|
||||
import MapperRowSkeleton from '../MapperRow/MapperRowSkeleton';
|
||||
@@ -39,6 +40,7 @@ function GroupMappers({
|
||||
onEditMapper,
|
||||
}: GroupMappersProps): JSX.Element {
|
||||
const { hydrateGroupMappers, removeMapper, toggleMapper } = editor;
|
||||
const canManage = useCanManageAttributeMapping();
|
||||
|
||||
const hasServerId = group.serverId !== null;
|
||||
const { data, isLoading, isError } = useListSpanMappers(
|
||||
@@ -144,16 +146,20 @@ function GroupMappers({
|
||||
/>
|
||||
));
|
||||
|
||||
// The add-mapping row trails every non-error state (including loading/empty).
|
||||
// The add-mapping row trails every non-error state (including loading/empty),
|
||||
// but only for users who can manage mappings — non-admins get a read-only view.
|
||||
let rows: JSX.Element[];
|
||||
if (isErrorMappers) {
|
||||
rows = [errorRow];
|
||||
} else if (isLoadingMappers && mapperCount === 0) {
|
||||
rows = [...skeletonRows, addMapperRow];
|
||||
rows = [...skeletonRows];
|
||||
} else if (mapperCount === 0) {
|
||||
rows = [emptyRow, addMapperRow];
|
||||
rows = [emptyRow];
|
||||
} else {
|
||||
rows = [...mapperRows, addMapperRow];
|
||||
rows = [...mapperRows];
|
||||
}
|
||||
if (canManage && !isErrorMappers) {
|
||||
rows.push(addMapperRow);
|
||||
}
|
||||
|
||||
return (
|
||||
|
||||
@@ -6,6 +6,7 @@ import cx from 'classnames';
|
||||
import { motion } from 'motion/react';
|
||||
|
||||
import { DraftMapper } from 'container/LLMObservability/AttributeMapping/types';
|
||||
import { useCanManageAttributeMapping } from 'container/LLMObservability/AttributeMapping/hooks/useCanManageAttributeMapping';
|
||||
import MapperActionsMenu from '../MapperActionsMenu/MapperActionsMenu';
|
||||
import styles from './MapperRow.module.scss';
|
||||
|
||||
@@ -30,6 +31,7 @@ function MapperRow({
|
||||
onRemove,
|
||||
onToggle,
|
||||
}: MapperRowProps): JSX.Element {
|
||||
const canManage = useCanManageAttributeMapping();
|
||||
const sources = mapper.sources ?? [];
|
||||
const visibleSources = sources.slice(0, MAX_VISIBLE_SOURCES);
|
||||
const remainingSources = sources.length - visibleSources.length;
|
||||
@@ -101,14 +103,16 @@ function MapperRow({
|
||||
)}
|
||||
</td>
|
||||
<td className={cx(styles.cell, styles.actionsCell)}>
|
||||
<div className={styles.rowActions}>
|
||||
<Switch
|
||||
value={mapper.enabled}
|
||||
onChange={(checked): void => onToggle(mapper.localId, checked)}
|
||||
testId={`mapper-enabled-${mapper.localId}`}
|
||||
/>
|
||||
<MapperActionsMenu mapper={mapper} onEdit={onEdit} onRemove={onRemove} />
|
||||
</div>
|
||||
{canManage && (
|
||||
<div className={styles.rowActions}>
|
||||
<Switch
|
||||
value={mapper.enabled}
|
||||
onChange={(checked): void => onToggle(mapper.localId, checked)}
|
||||
testId={`mapper-enabled-${mapper.localId}`}
|
||||
/>
|
||||
<MapperActionsMenu mapper={mapper} onEdit={onEdit} onRemove={onRemove} />
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
</motion.tr>
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
DraftMapper,
|
||||
} from 'container/LLMObservability/AttributeMapping/types';
|
||||
import { AttributeMappingEditor } from 'container/LLMObservability/AttributeMapping/hooks/useAttributeMappingEditor';
|
||||
import { useCanManageAttributeMapping } from 'container/LLMObservability/AttributeMapping/hooks/useCanManageAttributeMapping';
|
||||
import GroupHeader from './GroupHeader/GroupHeader';
|
||||
import GroupHeaderActions from './GroupHeaderActions/GroupHeaderActions';
|
||||
import GroupMappers from './GroupMappers/GroupMappers';
|
||||
@@ -33,6 +34,7 @@ function MappingsTable({
|
||||
const [expandedGroups, setExpandedGroups] = useState<string[]>([]);
|
||||
const [targetGroupId, setTargetGroupId] = useState<string | null>(null);
|
||||
const drawer = useMapperFormDrawer();
|
||||
const canManage = useCanManageAttributeMapping();
|
||||
|
||||
const { upsertMapper, removeMapper } = editor;
|
||||
|
||||
@@ -120,18 +122,20 @@ function MappingsTable({
|
||||
|
||||
return (
|
||||
<div className={styles.tableWrapper}>
|
||||
<div className={styles.toolbar}>
|
||||
<Button
|
||||
variant="link"
|
||||
color="primary"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={onAddGroup}
|
||||
testId="add-group-row"
|
||||
disabled={editor.isLoading}
|
||||
>
|
||||
Add a new group
|
||||
</Button>
|
||||
</div>
|
||||
{canManage && (
|
||||
<div className={styles.toolbar}>
|
||||
<Button
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<Plus size={14} />}
|
||||
onClick={onAddGroup}
|
||||
testId="add-group-row"
|
||||
disabled={editor.isLoading}
|
||||
>
|
||||
Add a new group
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isEmpty ? (
|
||||
<div className={styles.tableState} data-testid="mapper-groups-empty">
|
||||
|
||||
@@ -8,12 +8,18 @@ import AttributeMappingsTab from './AttributeMappingsTab/AttributeMappingsTab';
|
||||
import DiscardChangesDialog from './components/DiscardChangesDialog/DiscardChangesDialog';
|
||||
import GroupFormDrawer from './components/GroupFormDrawer/GroupFormDrawer';
|
||||
import styles from './LLMObservabilityAttributeMapping.module.scss';
|
||||
import TestTab from './TestTab/TestTab';
|
||||
import { useAttributeMappingEditor } from './hooks/useAttributeMappingEditor';
|
||||
import { useGroupFormDrawer } from './components/GroupFormDrawer/hooks/useGroupFormDrawer';
|
||||
import { useTestSpanMapper } from './TestTab/useTestSpanMapper';
|
||||
|
||||
const MAPPINGS_TAB_KEY = 'attribute-mappings';
|
||||
const TEST_TAB_KEY = 'test';
|
||||
|
||||
function LLMObservabilityAttributeMapping(): JSX.Element {
|
||||
const editor = useAttributeMappingEditor();
|
||||
const groupDrawer = useGroupFormDrawer();
|
||||
const spanTest = useTestSpanMapper(editor.snapshot, editor.groups);
|
||||
|
||||
const { discard } = editor;
|
||||
// Discarding wipes the whole working copy, so gate it behind a confirm
|
||||
@@ -31,7 +37,7 @@ function LLMObservabilityAttributeMapping(): JSX.Element {
|
||||
|
||||
const tabItems = [
|
||||
{
|
||||
key: 'attribute-mappings',
|
||||
key: MAPPINGS_TAB_KEY,
|
||||
label: 'Attribute Mappings',
|
||||
children: (
|
||||
<AttributeMappingsTab
|
||||
@@ -42,11 +48,9 @@ function LLMObservabilityAttributeMapping(): JSX.Element {
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'test',
|
||||
key: TEST_TAB_KEY,
|
||||
label: 'Test',
|
||||
disabled: true,
|
||||
disabledReason: 'Coming soon',
|
||||
children: null,
|
||||
children: <TestTab spanTest={spanTest} />,
|
||||
},
|
||||
];
|
||||
|
||||
@@ -71,7 +75,7 @@ function LLMObservabilityAttributeMapping(): JSX.Element {
|
||||
|
||||
<Tabs
|
||||
testId="attribute-mapping-tabs"
|
||||
defaultValue="attribute-mappings"
|
||||
defaultValue={MAPPINGS_TAB_KEY}
|
||||
items={tabItems}
|
||||
/>
|
||||
{groupDrawer.isOpen && (
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
.skeleton {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.line {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
.lineNumber {
|
||||
flex: 0 0 40px;
|
||||
padding-right: var(--padding-3);
|
||||
text-align: right;
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: var(--font-size-xs);
|
||||
color: var(--l3-foreground);
|
||||
opacity: 0.6;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.lineContent {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.bar {
|
||||
height: 8px;
|
||||
border-radius: var(--radius-1);
|
||||
background: var(--l2-border);
|
||||
animation: jsonSkeletonPulse 1.4s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.bar {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes jsonSkeletonPulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
50% {
|
||||
opacity: 0.45;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import styles from './JsonEditorSkeleton.module.scss';
|
||||
|
||||
interface SkeletonLine {
|
||||
indent: number;
|
||||
barWidths: number[];
|
||||
}
|
||||
|
||||
const SKELETON_LINES: SkeletonLine[] = [
|
||||
{ indent: 0, barWidths: [10] },
|
||||
{ indent: 1, barWidths: [90, 10] },
|
||||
{ indent: 2, barWidths: [155, 190] },
|
||||
{ indent: 2, barWidths: [135, 190] },
|
||||
{ indent: 2, barWidths: [150, 50] },
|
||||
{ indent: 2, barWidths: [180, 35] },
|
||||
{ indent: 2, barWidths: [185, 200] },
|
||||
{ indent: 1, barWidths: [14] },
|
||||
{ indent: 1, barWidths: [75, 10] },
|
||||
{ indent: 2, barWidths: [95, 90] },
|
||||
{ indent: 2, barWidths: [170, 85] },
|
||||
{ indent: 1, barWidths: [10] },
|
||||
{ indent: 0, barWidths: [10] },
|
||||
];
|
||||
|
||||
const INDENT_WIDTH_PX = 14;
|
||||
|
||||
function JsonEditorSkeleton(): JSX.Element {
|
||||
return (
|
||||
<div
|
||||
className={styles.skeleton}
|
||||
data-testid="json-editor-skeleton"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{SKELETON_LINES.map((line, lineIndex) => (
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
<div key={lineIndex} className={styles.line}>
|
||||
<span className={styles.lineNumber}>{lineIndex + 1}</span>
|
||||
<span
|
||||
className={styles.lineContent}
|
||||
style={{ paddingLeft: line.indent * INDENT_WIDTH_PX }}
|
||||
>
|
||||
{line.barWidths.map((width, barIndex) => (
|
||||
<span
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={barIndex}
|
||||
className={styles.bar}
|
||||
style={{ width }}
|
||||
/>
|
||||
))}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default JsonEditorSkeleton;
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import { SpantypesSpanMapperTestSpanDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { useMemo } from 'react';
|
||||
|
||||
import {
|
||||
AttrChangeStatus,
|
||||
AttrDiffEntry,
|
||||
diffAttributeMaps,
|
||||
formatAttributeValue,
|
||||
} from './testPayload';
|
||||
import styles from './TestTab.module.scss';
|
||||
import { TestTabAttributes, TestTabResource } from './useTestSpanMapper';
|
||||
|
||||
interface TestResultProps {
|
||||
index: number;
|
||||
span: SpantypesSpanMapperTestSpanDTO;
|
||||
inputAttributes: TestTabAttributes;
|
||||
inputResource: TestTabResource;
|
||||
}
|
||||
|
||||
const STATUS_BADGE: Partial<
|
||||
Record<
|
||||
AttrChangeStatus,
|
||||
{ color: 'success' | 'robin' | 'sienna'; label: string }
|
||||
>
|
||||
> = {
|
||||
added: { color: 'success', label: 'populated' },
|
||||
changed: { color: 'robin', label: 'remapped' },
|
||||
removed: { color: 'sienna', label: 'moved out' },
|
||||
};
|
||||
|
||||
const ROW_CLASS: Partial<Record<AttrChangeStatus, string>> = {
|
||||
added: styles.added,
|
||||
removed: styles.removed,
|
||||
};
|
||||
|
||||
interface ResultSection {
|
||||
key: string;
|
||||
title: string;
|
||||
entries: AttrDiffEntry[];
|
||||
}
|
||||
|
||||
function TestResult({
|
||||
index,
|
||||
span,
|
||||
inputAttributes,
|
||||
inputResource,
|
||||
}: TestResultProps): JSX.Element {
|
||||
const attributeEntries = useMemo(
|
||||
() => diffAttributeMaps(inputAttributes, span.attributes ?? {}),
|
||||
[inputAttributes, span.attributes],
|
||||
);
|
||||
const resourceEntries = useMemo(
|
||||
() => diffAttributeMaps(inputResource, span.resource ?? {}),
|
||||
[inputResource, span.resource],
|
||||
);
|
||||
|
||||
const sections: ResultSection[] = [
|
||||
{
|
||||
key: 'attributes',
|
||||
title: 'Resulting attributes',
|
||||
entries: attributeEntries,
|
||||
},
|
||||
];
|
||||
if (resourceEntries.length > 0) {
|
||||
sections.push({
|
||||
key: 'resource',
|
||||
title: 'Resulting resource',
|
||||
entries: resourceEntries,
|
||||
});
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.resultCard} data-testid={`test-result-${index}`}>
|
||||
{sections.map((section) => (
|
||||
<div
|
||||
key={section.key}
|
||||
className={styles.resultSection}
|
||||
data-testid={`test-result-${index}-${section.key}`}
|
||||
>
|
||||
<div className={styles.resultTitle}>{section.title}</div>
|
||||
|
||||
{section.entries.length === 0 ? (
|
||||
<div className={styles.resultEmpty}>No keys in this map.</div>
|
||||
) : (
|
||||
<div className={styles.attrRows}>
|
||||
{section.entries.map((entry) => {
|
||||
const badge = STATUS_BADGE[entry.status];
|
||||
return (
|
||||
<div
|
||||
key={entry.key}
|
||||
className={`${styles.attrRow} ${ROW_CLASS[entry.status] ?? ''}`}
|
||||
>
|
||||
<span className={styles.attrKey} title={entry.key}>
|
||||
{entry.key}
|
||||
</span>
|
||||
<span
|
||||
className={styles.attrValue}
|
||||
title={formatAttributeValue(entry.value)}
|
||||
>
|
||||
{formatAttributeValue(entry.value)}
|
||||
</span>
|
||||
{badge ? (
|
||||
<Badge color={badge.color} variant="outline">
|
||||
{badge.label}
|
||||
</Badge>
|
||||
) : (
|
||||
<span />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TestResult;
|
||||
@@ -0,0 +1,177 @@
|
||||
.testTab {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
margin-top: var(--spacing-6);
|
||||
}
|
||||
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: var(--spacing-6);
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.headerText {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-2);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.heading {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.description {
|
||||
margin: 0;
|
||||
font-size: var(--periscope-font-size-base);
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
|
||||
.body {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: var(--spacing-6);
|
||||
height: calc(100vh - 320px);
|
||||
min-height: 320px;
|
||||
}
|
||||
|
||||
.editor {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
overflow: hidden;
|
||||
}
|
||||
.validationCallout {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
// No top padding so results align with the editor's first line, which sits
|
||||
// flush against the top of its own panel.
|
||||
.resultsPanel {
|
||||
height: 100%;
|
||||
overflow-y: auto;
|
||||
padding: var(--padding-4);
|
||||
border: 1px solid var(--l2-border);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
// Pre-run empty state that fills the blank right half.
|
||||
.placeholder {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--spacing-2);
|
||||
height: 100%;
|
||||
text-align: center;
|
||||
color: var(--l3-foreground);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
}
|
||||
|
||||
.placeholderTitle {
|
||||
font-weight: var(--font-weight-semibold);
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
|
||||
.error {
|
||||
padding: var(--padding-3) var(--padding-4);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--callout-error-background);
|
||||
color: var(--callout-error-title);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
}
|
||||
|
||||
.results {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
}
|
||||
|
||||
.resultCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-6);
|
||||
border-radius: var(--radius-2);
|
||||
background: var(--l1-background);
|
||||
}
|
||||
|
||||
.resultSection {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
|
||||
.resultTitle {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-3);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.resultEmpty {
|
||||
color: var(--l3-foreground);
|
||||
font-size: var(--periscope-font-size-base);
|
||||
}
|
||||
|
||||
.attrRows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--spacing-2);
|
||||
}
|
||||
|
||||
.attrRow {
|
||||
display: grid;
|
||||
grid-template-columns: clamp(200px, 40%, 340px) minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
padding: var(--spacing-2) var(--padding-3);
|
||||
border-radius: var(--radius-2);
|
||||
font-family: 'Geist Mono', monospace;
|
||||
font-size: var(--font-size-xs);
|
||||
|
||||
&.added {
|
||||
background: var(--callout-success-background);
|
||||
}
|
||||
|
||||
&.removed {
|
||||
opacity: 0.65;
|
||||
|
||||
.attrKey,
|
||||
.attrValue {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.attrKey,
|
||||
.attrValue {
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.attrKey {
|
||||
font-weight: var(--font-weight-medium);
|
||||
}
|
||||
|
||||
.attrValue {
|
||||
color: var(--l3-foreground);
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
import MEditor from '@monaco-editor/react';
|
||||
import { Play, RotateCcw } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Callout } from '@signozhq/ui/callout';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
|
||||
import styles from './TestTab.module.scss';
|
||||
import JsonEditorSkeleton from './JsonEditorSkeleton';
|
||||
import TestResult from './TestResult';
|
||||
import {
|
||||
defineSignozJsonTheme,
|
||||
SIGNOZ_JSON_THEME_DARK,
|
||||
SIGNOZ_JSON_THEME_LIGHT,
|
||||
} from './jsonEditorTheme';
|
||||
import { UseTestSpanMapper } from './useTestSpanMapper';
|
||||
|
||||
interface TestTabProps {
|
||||
spanTest: UseTestSpanMapper;
|
||||
}
|
||||
|
||||
function TestTab({ spanTest }: TestTabProps): JSX.Element {
|
||||
const {
|
||||
input,
|
||||
setInput,
|
||||
run,
|
||||
resetToTemplate,
|
||||
isTemplateInput,
|
||||
isRunning,
|
||||
result,
|
||||
testedAttributes,
|
||||
testedResource,
|
||||
error,
|
||||
validationError,
|
||||
} = spanTest;
|
||||
const isDarkMode = useIsDarkMode();
|
||||
|
||||
function renderResults(): JSX.Element {
|
||||
if (error) {
|
||||
return (
|
||||
<div className={styles.error} role="alert" data-testid="test-error">
|
||||
{error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (result) {
|
||||
if (result.length === 0) {
|
||||
return (
|
||||
<div className={styles.resultEmpty} data-testid="test-results-empty">
|
||||
No spans returned. The mappers produced no output for this input.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={styles.results} data-testid="test-results">
|
||||
{result.map((span, index) => (
|
||||
<TestResult
|
||||
// eslint-disable-next-line react/no-array-index-key
|
||||
key={index}
|
||||
index={index}
|
||||
span={span}
|
||||
inputAttributes={testedAttributes ?? {}}
|
||||
inputResource={testedResource ?? {}}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div className={styles.placeholder} data-testid="test-results-placeholder">
|
||||
<span className={styles.placeholderTitle}>No results yet</span>
|
||||
<span>
|
||||
Run the test to see which target attributes your mappers populate.
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={styles.testTab} data-testid="test-tab">
|
||||
<div className={styles.header}>
|
||||
<div className={styles.headerText}>
|
||||
<h3 className={styles.heading}>Test with sample span</h3>
|
||||
<p className={styles.description}>
|
||||
Paste a JSON span object to see which target attributes get populated and
|
||||
which source key matched.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className={styles.headerActions}>
|
||||
<Button
|
||||
testId="reset-template-button"
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
prefix={<RotateCcw size={14} />}
|
||||
onClick={resetToTemplate}
|
||||
disabled={isTemplateInput}
|
||||
>
|
||||
Reset to Default Span
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
testId="run-test-button"
|
||||
variant="solid"
|
||||
color="primary"
|
||||
prefix={<Play size={14} />}
|
||||
onClick={run}
|
||||
loading={isRunning}
|
||||
disabled={isRunning || validationError !== null}
|
||||
>
|
||||
Run Test
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.body}>
|
||||
<div
|
||||
className={styles.editor}
|
||||
data-testid="test-span-input"
|
||||
aria-label="Sample span JSON"
|
||||
>
|
||||
<MEditor
|
||||
language="json"
|
||||
value={input}
|
||||
onChange={(value): void => setInput(value ?? '')}
|
||||
height="100%"
|
||||
loading={<JsonEditorSkeleton />}
|
||||
theme={isDarkMode ? SIGNOZ_JSON_THEME_DARK : SIGNOZ_JSON_THEME_LIGHT}
|
||||
beforeMount={defineSignozJsonTheme}
|
||||
options={{
|
||||
minimap: { enabled: false },
|
||||
fontSize: 12,
|
||||
lineNumbers: 'on',
|
||||
wordWrap: 'on',
|
||||
scrollBeyondLastLine: false,
|
||||
formatOnPaste: true,
|
||||
tabSize: 2,
|
||||
automaticLayout: true,
|
||||
scrollbar: { alwaysConsumeMouseWheel: false },
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className={styles.resultsPanel} data-testid="test-results-panel">
|
||||
{renderResults()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{validationError && (
|
||||
<Callout
|
||||
type="error"
|
||||
size="small"
|
||||
showIcon
|
||||
title={validationError}
|
||||
testId="test-input-error"
|
||||
className={styles.validationCallout}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default TestTab;
|
||||
@@ -0,0 +1,38 @@
|
||||
//TODO: This is a local theme for now, but ideally for the editor as well. Just like prettyViewer, we have a theme. We should have a theme for the editor as well.
|
||||
import { Monaco } from '@monaco-editor/react';
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
|
||||
export const SIGNOZ_JSON_THEME_DARK = 'signoz-attr-mapping-json-dark';
|
||||
export const SIGNOZ_JSON_THEME_LIGHT = 'signoz-attr-mapping-json-light';
|
||||
|
||||
const SHARED_THEME = {
|
||||
inherit: true,
|
||||
colors: {
|
||||
'editor.background': '#00000000', // transparent — inherit the panel bg
|
||||
},
|
||||
fontFamily: 'SF Mono, Geist Mono, Fira Code, monospace',
|
||||
fontSize: 12,
|
||||
fontWeight: 'normal',
|
||||
lineHeight: 18,
|
||||
letterSpacing: -0.06,
|
||||
};
|
||||
|
||||
export function defineSignozJsonTheme(monaco: Monaco): void {
|
||||
monaco.editor.defineTheme(SIGNOZ_JSON_THEME_DARK, {
|
||||
...SHARED_THEME,
|
||||
base: 'vs-dark',
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_ROBIN_400 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_VANILLA_400 },
|
||||
],
|
||||
});
|
||||
|
||||
monaco.editor.defineTheme(SIGNOZ_JSON_THEME_LIGHT, {
|
||||
...SHARED_THEME,
|
||||
base: 'vs',
|
||||
rules: [
|
||||
{ token: 'string.key.json', foreground: Color.BG_ROBIN_500 },
|
||||
{ token: 'string.value.json', foreground: Color.BG_INK_400 },
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import get from 'api/browser/localstorage/get';
|
||||
import remove from 'api/browser/localstorage/remove';
|
||||
import set from 'api/browser/localstorage/set';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
|
||||
import { parseSpanInput } from './testPayload';
|
||||
|
||||
export const SAMPLE_SPAN_JSON = `{
|
||||
"attributes": {
|
||||
"my_company.llm.input": "What is quantum computing?",
|
||||
"llm.input_messages": "What is quantum computing?",
|
||||
"gen_ai.request.model": "gpt-4",
|
||||
"gen_ai.usage.total_tokens": 1250,
|
||||
"gen_ai.content.completion": "Quantum computing leverages..."
|
||||
},
|
||||
"resource": {
|
||||
"service.name": "llm-gateway",
|
||||
"deployment.environment": "production"
|
||||
}
|
||||
}`;
|
||||
|
||||
function hasNoSpanData(input: string): boolean {
|
||||
let span;
|
||||
try {
|
||||
span = parseSpanInput(input);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
Object.keys(span.attributes ?? {}).length === 0 &&
|
||||
Object.keys(span.resource ?? {}).length === 0
|
||||
);
|
||||
}
|
||||
|
||||
export function getStoredSpanInput(): string {
|
||||
const stored = get(LOCALSTORAGE.LLM_ATTRIBUTE_MAPPING_TEST_SPAN);
|
||||
if (!stored?.trim() || hasNoSpanData(stored)) {
|
||||
return SAMPLE_SPAN_JSON;
|
||||
}
|
||||
return stored;
|
||||
}
|
||||
|
||||
export function setStoredSpanInput(value: string): void {
|
||||
if (!value.trim() || hasNoSpanData(value)) {
|
||||
remove(LOCALSTORAGE.LLM_ATTRIBUTE_MAPPING_TEST_SPAN);
|
||||
return;
|
||||
}
|
||||
set(LOCALSTORAGE.LLM_ATTRIBUTE_MAPPING_TEST_SPAN, value);
|
||||
}
|
||||
|
||||
export function clearStoredSpanInput(): void {
|
||||
remove(LOCALSTORAGE.LLM_ATTRIBUTE_MAPPING_TEST_SPAN);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import {
|
||||
SpantypesPostableSpanMapperTestDTO,
|
||||
SpantypesPostableSpanMapperTestGroupDTO,
|
||||
SpantypesSpanMapperTestSpanDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { isEqual } from 'lodash-es';
|
||||
|
||||
import { DraftGroup } from '../types';
|
||||
import {
|
||||
buildPostableGroup,
|
||||
buildPostableMapper,
|
||||
groupDraftFromNode,
|
||||
mapperDraftFromNode,
|
||||
} from '../utils';
|
||||
|
||||
function shouldSendMappers(
|
||||
snap: DraftGroup | undefined,
|
||||
group: DraftGroup,
|
||||
): boolean {
|
||||
if (!snap) {
|
||||
return true;
|
||||
}
|
||||
return !isEqual(snap.mappers, group.mappers);
|
||||
}
|
||||
|
||||
export function buildTestGroups(
|
||||
snapshot: DraftGroup[],
|
||||
draft: DraftGroup[],
|
||||
): SpantypesPostableSpanMapperTestGroupDTO[] {
|
||||
const snapById = new Map(
|
||||
snapshot
|
||||
.filter((group) => group.serverId)
|
||||
.map((group) => [group.serverId as string, group]),
|
||||
);
|
||||
|
||||
return draft.map((group) => {
|
||||
const base = buildPostableGroup(groupDraftFromNode(group));
|
||||
const snap = group.serverId ? snapById.get(group.serverId) : undefined;
|
||||
return {
|
||||
...base,
|
||||
mappers: shouldSendMappers(snap, group)
|
||||
? group.mappers.map((mapper) =>
|
||||
buildPostableMapper(mapperDraftFromNode(mapper)),
|
||||
)
|
||||
: null,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function isPlainObject(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function isSpanEnvelope(parsed: Record<string, unknown>): boolean {
|
||||
const keys = Object.keys(parsed);
|
||||
return (
|
||||
keys.length > 0 &&
|
||||
keys.every((key) => key === 'attributes' || key === 'resource') &&
|
||||
(isPlainObject(parsed.attributes) || isPlainObject(parsed.resource))
|
||||
);
|
||||
}
|
||||
|
||||
export function parseSpanInput(input: string): SpantypesSpanMapperTestSpanDTO {
|
||||
const trimmed = input.trim();
|
||||
if (!trimmed) {
|
||||
throw new Error('Paste a JSON span object to run the test.');
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(trimmed);
|
||||
} catch {
|
||||
throw new Error(
|
||||
'Invalid JSON — check for trailing commas or missing quotes.',
|
||||
);
|
||||
}
|
||||
|
||||
if (!isPlainObject(parsed)) {
|
||||
throw new Error('Span must be a JSON object of attribute key-value pairs.');
|
||||
}
|
||||
|
||||
if (isSpanEnvelope(parsed)) {
|
||||
return {
|
||||
attributes: isPlainObject(parsed.attributes) ? parsed.attributes : {},
|
||||
resource: isPlainObject(parsed.resource) ? parsed.resource : {},
|
||||
};
|
||||
}
|
||||
|
||||
return { attributes: parsed, resource: {} };
|
||||
}
|
||||
|
||||
export function buildTestRequest(
|
||||
snapshot: DraftGroup[],
|
||||
draft: DraftGroup[],
|
||||
input: string,
|
||||
): SpantypesPostableSpanMapperTestDTO {
|
||||
return {
|
||||
groups: buildTestGroups(snapshot, draft),
|
||||
spans: [parseSpanInput(input)],
|
||||
};
|
||||
}
|
||||
|
||||
export type AttrChangeStatus = 'added' | 'changed' | 'unchanged' | 'removed';
|
||||
|
||||
export interface AttrDiffEntry {
|
||||
key: string;
|
||||
value: unknown;
|
||||
status: AttrChangeStatus;
|
||||
}
|
||||
|
||||
// Renders a diff value for display: strings as-is, everything else JSON-encoded.
|
||||
export function formatAttributeValue(value: unknown): string {
|
||||
if (typeof value === 'string') {
|
||||
return value;
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
export function diffAttributeMaps(
|
||||
inputAttributes: Record<string, unknown>,
|
||||
resultAttributes: Record<string, unknown>,
|
||||
): AttrDiffEntry[] {
|
||||
const added: AttrDiffEntry[] = [];
|
||||
const changed: AttrDiffEntry[] = [];
|
||||
const unchanged: AttrDiffEntry[] = [];
|
||||
const removed: AttrDiffEntry[] = [];
|
||||
|
||||
Object.entries(resultAttributes).forEach(([key, value]) => {
|
||||
if (!(key in inputAttributes)) {
|
||||
added.push({ key, value, status: 'added' });
|
||||
} else if (!isEqual(inputAttributes[key], value)) {
|
||||
changed.push({ key, value, status: 'changed' });
|
||||
} else {
|
||||
unchanged.push({ key, value, status: 'unchanged' });
|
||||
}
|
||||
});
|
||||
|
||||
Object.entries(inputAttributes).forEach(([key, value]) => {
|
||||
if (!(key in resultAttributes)) {
|
||||
removed.push({ key, value, status: 'removed' });
|
||||
}
|
||||
});
|
||||
|
||||
return [...added, ...changed, ...unchanged, ...removed];
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
RenderErrorResponseDTO,
|
||||
SpantypesSpanMapperTestSpanDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { useTestSpanMappers } from 'api/generated/services/spanmapper';
|
||||
import { AxiosError } from 'axios';
|
||||
import { debounce } from 'lodash-es';
|
||||
|
||||
import { buildTestRequest, parseSpanInput } from './testPayload';
|
||||
import {
|
||||
clearStoredSpanInput,
|
||||
getStoredSpanInput,
|
||||
SAMPLE_SPAN_JSON,
|
||||
setStoredSpanInput,
|
||||
} from './spanInputStorage';
|
||||
import { DraftGroup } from '../types';
|
||||
|
||||
export type TestTabAttributes = Record<string, unknown>;
|
||||
export type TestTabResource = Record<string, unknown>;
|
||||
|
||||
const PERSIST_DEBOUNCE_MS = 500;
|
||||
|
||||
function apiErrorMessage(error: unknown): string {
|
||||
const axiosError = error as AxiosError<RenderErrorResponseDTO>;
|
||||
return (
|
||||
axiosError?.response?.data?.error?.message ??
|
||||
(error instanceof Error ? error.message : 'Test failed. Please try again.')
|
||||
);
|
||||
}
|
||||
|
||||
export interface UseTestSpanMapper {
|
||||
input: string;
|
||||
setInput: (value: string) => void;
|
||||
run: () => void;
|
||||
reset: () => void;
|
||||
resetToTemplate: () => void;
|
||||
isTemplateInput: boolean;
|
||||
isRunning: boolean;
|
||||
validationError: string | null;
|
||||
result: SpantypesSpanMapperTestSpanDTO[] | null;
|
||||
testedAttributes: TestTabAttributes | null;
|
||||
testedResource: TestTabResource | null;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
export function useTestSpanMapper(
|
||||
snapshot: DraftGroup[],
|
||||
draft: DraftGroup[],
|
||||
): UseTestSpanMapper {
|
||||
const [input, setInputValue] = useState<string>(getStoredSpanInput);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [result, setResult] = useState<SpantypesSpanMapperTestSpanDTO[] | null>(
|
||||
null,
|
||||
);
|
||||
const [testedAttributes, setTestedAttributes] =
|
||||
useState<TestTabAttributes | null>(null);
|
||||
const [testedResource, setTestedResource] = useState<TestTabResource | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
const { mutate, isLoading } = useTestSpanMappers();
|
||||
|
||||
const persistInput = useMemo(
|
||||
() => debounce(setStoredSpanInput, PERSIST_DEBOUNCE_MS),
|
||||
[],
|
||||
);
|
||||
|
||||
useEffect(
|
||||
() => (): void => {
|
||||
persistInput.flush();
|
||||
},
|
||||
[persistInput],
|
||||
);
|
||||
|
||||
const setInput = useCallback(
|
||||
(value: string): void => {
|
||||
setInputValue(value);
|
||||
persistInput(value);
|
||||
},
|
||||
[persistInput],
|
||||
);
|
||||
|
||||
const validationError = useMemo((): string | null => {
|
||||
try {
|
||||
parseSpanInput(input);
|
||||
return null;
|
||||
} catch (err) {
|
||||
return err instanceof Error ? err.message : 'Invalid span JSON.';
|
||||
}
|
||||
}, [input]);
|
||||
|
||||
const reset = useCallback((): void => {
|
||||
setError(null);
|
||||
setResult(null);
|
||||
setTestedAttributes(null);
|
||||
setTestedResource(null);
|
||||
}, []);
|
||||
|
||||
const resetToTemplate = useCallback((): void => {
|
||||
persistInput.cancel();
|
||||
clearStoredSpanInput();
|
||||
setInputValue(SAMPLE_SPAN_JSON);
|
||||
reset();
|
||||
}, [persistInput, reset]);
|
||||
|
||||
const isTemplateInput = input.trim() === SAMPLE_SPAN_JSON;
|
||||
|
||||
const run = useCallback((): void => {
|
||||
reset();
|
||||
|
||||
let body;
|
||||
try {
|
||||
body = buildTestRequest(snapshot, draft, input);
|
||||
} catch (parseError) {
|
||||
setError(apiErrorMessage(parseError));
|
||||
return;
|
||||
}
|
||||
|
||||
const submittedSpan = body.spans?.[0];
|
||||
const submittedAttributes = (submittedSpan?.attributes ??
|
||||
{}) as TestTabAttributes;
|
||||
const submittedResource = (submittedSpan?.resource ?? {}) as TestTabResource;
|
||||
|
||||
mutate(
|
||||
{ data: body },
|
||||
{
|
||||
onSuccess: (response) => {
|
||||
setTestedAttributes(submittedAttributes);
|
||||
setTestedResource(submittedResource);
|
||||
setResult(response.data?.spans ?? []);
|
||||
},
|
||||
onError: (mutationError) => {
|
||||
setResult(null);
|
||||
setError(apiErrorMessage(mutationError));
|
||||
},
|
||||
},
|
||||
);
|
||||
}, [snapshot, draft, input, mutate, reset]);
|
||||
|
||||
return {
|
||||
input,
|
||||
setInput,
|
||||
run,
|
||||
reset,
|
||||
resetToTemplate,
|
||||
isTemplateInput,
|
||||
isRunning: isLoading,
|
||||
validationError,
|
||||
result,
|
||||
testedAttributes,
|
||||
testedResource,
|
||||
error,
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,32 @@
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
import { mockUseAuthZGrantAll } from 'lib/authz/utils/authz-test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
// The header's Save/Discard and the group toggle are Admin-gated via useAuthZ;
|
||||
// render as an admin so those controls are present.
|
||||
jest.mock('lib/authz/hooks/useAuthZ/useAuthZ');
|
||||
const mockedUseAuthZ = useAuthZ as jest.MockedFunction<typeof useAuthZ>;
|
||||
|
||||
// Monaco can't run in jsdom — stand in a textarea so the span input is editable.
|
||||
jest.mock('@monaco-editor/react', () => ({
|
||||
__esModule: true,
|
||||
default: ({
|
||||
value,
|
||||
onChange,
|
||||
}: {
|
||||
value: string;
|
||||
onChange: (next?: string) => void;
|
||||
}): JSX.Element => (
|
||||
<textarea
|
||||
aria-label="span-json-editor"
|
||||
data-testid="span-json-editor"
|
||||
value={value}
|
||||
onChange={(event): void => onChange(event.target.value)}
|
||||
/>
|
||||
),
|
||||
}));
|
||||
|
||||
import LLMObservabilityAttributeMapping from '../LLMObservabilityAttributeMapping';
|
||||
import { GROUPS_ENDPOINT, makeGroupsResponse, mockGroups } from './fixtures';
|
||||
|
||||
@@ -16,6 +42,7 @@ describe('LLMObservabilityAttributeMapping', () => {
|
||||
beforeEach(() => {
|
||||
window.history.pushState(null, '', '/');
|
||||
setupGroups();
|
||||
mockedUseAuthZ.mockImplementation(mockUseAuthZGrantAll);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -86,6 +113,26 @@ describe('LLMObservabilityAttributeMapping', () => {
|
||||
expect(screen.queryByTestId('discard-changes-btn')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('keeps the sample span input when switching away from the test tab and back', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
const editor = await screen.findByTestId('span-json-editor');
|
||||
await user.clear(editor);
|
||||
await user.type(editor, '{{ "my.attr": 1 }');
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Attribute Mappings' }));
|
||||
await screen.findByTestId('attribute-mappings-tab');
|
||||
expect(screen.queryByTestId('span-json-editor')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByRole('tab', { name: 'Test' }));
|
||||
|
||||
await expect(screen.findByTestId('span-json-editor')).resolves.toHaveValue(
|
||||
'{ "my.attr": 1 }',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps staged changes when the discard prompt is dismissed', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(<LLMObservabilityAttributeMapping />);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
import { useCanManageAttributeMapping } from '../../hooks/useCanManageAttributeMapping';
|
||||
import styles from './AttributeMappingHeader.module.scss';
|
||||
|
||||
interface AttributeMappingHeaderProps {
|
||||
@@ -16,12 +17,13 @@ function AttributeMappingHeader({
|
||||
onDiscard,
|
||||
onSave,
|
||||
}: AttributeMappingHeaderProps): JSX.Element {
|
||||
const canManage = useCanManageAttributeMapping();
|
||||
return (
|
||||
<header className={styles.pageHeader}>
|
||||
<Typography.Text as="p" size="base" color="muted">
|
||||
Configure source-to-target attribute remapping for LLM traces
|
||||
</Typography.Text>
|
||||
{isDirty && (
|
||||
{canManage && isDirty && (
|
||||
<div className={styles.pageHeaderActions}>
|
||||
<span className={styles.unsavedChanges} data-testid="unsaved-changes">
|
||||
Unsaved changes
|
||||
|
||||
@@ -35,6 +35,7 @@ function clone(groups: DraftGroup[]): DraftGroup[] {
|
||||
|
||||
export interface AttributeMappingEditor {
|
||||
groups: DraftGroup[];
|
||||
snapshot: DraftGroup[];
|
||||
isLoading: boolean;
|
||||
isError: boolean;
|
||||
isDirty: boolean;
|
||||
@@ -304,6 +305,7 @@ export function useAttributeMappingEditor(): AttributeMappingEditor {
|
||||
|
||||
return {
|
||||
groups: draft ?? [],
|
||||
snapshot,
|
||||
isLoading: !ready || draft === null,
|
||||
isError: groupsQuery.isError,
|
||||
isDirty,
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
import { IsAdminPermission } from 'lib/authz/hooks/useAuthZ/legacy';
|
||||
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
|
||||
|
||||
const ADMIN_PERMISSION = [IsAdminPermission];
|
||||
|
||||
export function useCanManageAttributeMapping(): boolean {
|
||||
const { allowed } = useAuthZ(ADMIN_PERMISSION);
|
||||
return allowed;
|
||||
}
|
||||
@@ -756,10 +756,14 @@ function QueryBuilderSearchV2(
|
||||
|
||||
let operatorOptions;
|
||||
if (currentFilterItem?.key?.dataType) {
|
||||
operatorOptions = QUERY_BUILDER_OPERATORS_BY_TYPES[
|
||||
currentFilterItem.key
|
||||
.dataType as keyof typeof QUERY_BUILDER_OPERATORS_BY_TYPES
|
||||
].map((operator) => ({
|
||||
// Fallback to universal suggestions if no match found for currentFilter dataType
|
||||
const operatorsForDataType =
|
||||
QUERY_BUILDER_OPERATORS_BY_TYPES[
|
||||
currentFilterItem.key
|
||||
.dataType as keyof typeof QUERY_BUILDER_OPERATORS_BY_TYPES
|
||||
] ?? QUERY_BUILDER_OPERATORS_BY_TYPES.universal;
|
||||
|
||||
operatorOptions = operatorsForDataType.map((operator) => ({
|
||||
label: operator,
|
||||
value: operator,
|
||||
}));
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import {
|
||||
act,
|
||||
fireEvent,
|
||||
render,
|
||||
RenderResult,
|
||||
screen,
|
||||
} from '@testing-library/react';
|
||||
import { render, RenderResult, screen, within } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryBuilderFormValues,
|
||||
@@ -91,6 +86,9 @@ const renderWithContext = (props = {}): RenderResult => {
|
||||
);
|
||||
};
|
||||
|
||||
const getSearchCombobox = (): HTMLElement =>
|
||||
within(screen.getByTestId('qb-search-select')).getByRole('combobox');
|
||||
|
||||
// Constants to fix linter errors
|
||||
const TYPE_TAG = 'tag';
|
||||
const IS_COLUMN_FALSE = false;
|
||||
@@ -113,6 +111,14 @@ const mockAggregateKeysData = {
|
||||
isJSON: IS_JSON_FALSE,
|
||||
id: 'service.name--string--tag--false',
|
||||
},
|
||||
{
|
||||
key: 'unmapped.attribute',
|
||||
dataType: 'not-a-real-data-type' as unknown as DataTypes,
|
||||
type: TYPE_TAG,
|
||||
isColumn: IS_COLUMN_FALSE,
|
||||
isJSON: IS_JSON_FALSE,
|
||||
id: 'unmapped.attribute--String--tag--false',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
@@ -165,41 +171,28 @@ jest.mock('hooks/dashboard/useDashboardVariables', () => ({
|
||||
}));
|
||||
|
||||
describe('Suggestion Key -> Operator -> Value Flow', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
it('should complete full flow from key selection to value', async () => {
|
||||
const { container } = renderWithContext();
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
// Get the combobox input specifically
|
||||
const combobox = container.querySelector(
|
||||
'.query-builder-search-v2 .ant-select-selection-search-input',
|
||||
) as HTMLInputElement;
|
||||
const combobox = getSearchCombobox();
|
||||
|
||||
// 1. Focus and type to trigger key suggestions
|
||||
await act(async () => {
|
||||
fireEvent.focus(combobox);
|
||||
fireEvent.change(combobox, { target: { value: 'http.' } });
|
||||
});
|
||||
await user.click(combobox);
|
||||
await user.type(combobox, 'http.');
|
||||
|
||||
// Wait for dropdown to appear
|
||||
await screen.findByRole('listbox');
|
||||
|
||||
// 2. Select a key from suggestions
|
||||
const statusOption = await screen.findByText('http.status');
|
||||
await act(async () => {
|
||||
fireEvent.click(statusOption);
|
||||
});
|
||||
await user.click(await screen.findByText('http.status'));
|
||||
|
||||
// Should show operator suggestions
|
||||
expect(screen.getByText('=')).toBeInTheDocument();
|
||||
expect(screen.getByText('!=')).toBeInTheDocument();
|
||||
|
||||
// 3. Select an operator
|
||||
const equalsOption = screen.getByText('=');
|
||||
await act(async () => {
|
||||
fireEvent.click(equalsOption);
|
||||
});
|
||||
await user.click(screen.getByText('='));
|
||||
|
||||
// Should show value suggestions
|
||||
expect(screen.getByText('200')).toBeInTheDocument();
|
||||
@@ -207,10 +200,7 @@ describe('Suggestion Key -> Operator -> Value Flow', () => {
|
||||
expect(screen.getByText('500')).toBeInTheDocument();
|
||||
|
||||
// 4. Select a value
|
||||
const valueOption = screen.getByText('200');
|
||||
await act(async () => {
|
||||
fireEvent.click(valueOption);
|
||||
});
|
||||
await user.click(screen.getByText('200'));
|
||||
|
||||
// Verify final filter
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
@@ -227,39 +217,52 @@ describe('Suggestion Key -> Operator -> Value Flow', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('Dynamic Variable Suggestions', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
describe('Operator suggestions for data types missing from the operators map', () => {
|
||||
it('should fall back to universal operators for a non-canonical data type', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
const combobox = getSearchCombobox();
|
||||
|
||||
await user.click(combobox);
|
||||
await user.type(combobox, 'unmapped.');
|
||||
|
||||
await screen.findByRole('listbox');
|
||||
|
||||
await user.click(await screen.findByText('unmapped.attribute'));
|
||||
|
||||
expect(screen.getByText('=')).toBeInTheDocument();
|
||||
expect(screen.getByText('!=')).toBeInTheDocument();
|
||||
expect(screen.getByText('>')).toBeInTheDocument();
|
||||
expect(screen.getByText('<')).toBeInTheDocument();
|
||||
|
||||
expect(screen.queryByText('REGEX')).not.toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByText('='));
|
||||
|
||||
expect(combobox).toHaveDisplayValue(/unmapped\.attribute =/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Dynamic Variable Suggestions', () => {
|
||||
it('should suggest dynamic variable when key matches a variable attribute', async () => {
|
||||
const { container } = renderWithContext();
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderWithContext();
|
||||
|
||||
// Get the combobox input
|
||||
const combobox = container.querySelector(
|
||||
'.query-builder-search-v2 .ant-select-selection-search-input',
|
||||
) as HTMLInputElement;
|
||||
const combobox = getSearchCombobox();
|
||||
|
||||
// Focus and type to trigger key suggestions for service.name
|
||||
await act(async () => {
|
||||
fireEvent.focus(combobox);
|
||||
fireEvent.change(combobox, { target: { value: 'service.' } });
|
||||
});
|
||||
await user.click(combobox);
|
||||
await user.type(combobox, 'service.');
|
||||
|
||||
// Wait for dropdown to appear
|
||||
await screen.findByRole('listbox');
|
||||
|
||||
// Select service.name key from suggestions
|
||||
const serviceNameOption = await screen.findByText('service.name');
|
||||
await act(async () => {
|
||||
fireEvent.click(serviceNameOption);
|
||||
});
|
||||
await user.click(await screen.findByText('service.name'));
|
||||
|
||||
// Select equals operator
|
||||
await act(async () => {
|
||||
const equalsOption = screen.getByText('=');
|
||||
fireEvent.click(equalsOption);
|
||||
});
|
||||
await user.click(screen.getByText('='));
|
||||
|
||||
// Should show value suggestions including the dynamic variable
|
||||
// For 'service.name', we expect to see '$service' as the first suggestion
|
||||
@@ -271,9 +274,7 @@ describe('Dynamic Variable Suggestions', () => {
|
||||
expect(screen.getByText('404')).toBeInTheDocument();
|
||||
|
||||
// Select the variable suggestion
|
||||
await act(async () => {
|
||||
fireEvent.click(variableSuggestion);
|
||||
});
|
||||
await user.click(variableSuggestion);
|
||||
|
||||
// Verify the query was updated with the variable as value
|
||||
expect(mockOnChange).toHaveBeenCalledWith(
|
||||
|
||||
@@ -2,7 +2,9 @@ import { server } from 'mocks-server/server';
|
||||
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
|
||||
import { expandAllCards, renderCreateRolePage } from './testUtils';
|
||||
import { expandResourceCard, renderCreateRolePage } from './testUtils';
|
||||
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
beforeEach(() => {
|
||||
server.use(setupAuthzAdmin());
|
||||
@@ -123,7 +125,7 @@ describe('PermissionEditor', () => {
|
||||
describe('action toggles', () => {
|
||||
it('renders action toggles for each available action', async () => {
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
expect(
|
||||
@@ -142,7 +144,7 @@ describe('PermissionEditor', () => {
|
||||
|
||||
it('defaults all actions to None scope', async () => {
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -160,7 +162,7 @@ describe('PermissionEditor', () => {
|
||||
it('changes scope to All when clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -181,7 +183,7 @@ describe('PermissionEditor', () => {
|
||||
it('updates granted count when scope changed', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -200,7 +202,7 @@ describe('PermissionEditor', () => {
|
||||
it('shows item input selector when Only Selected is chosen', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -219,7 +221,7 @@ describe('PermissionEditor', () => {
|
||||
it('adds item when typed and Enter pressed', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -239,7 +241,7 @@ describe('PermissionEditor', () => {
|
||||
it('adds item when Add button clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -264,7 +266,7 @@ describe('PermissionEditor', () => {
|
||||
it('adds multiple items separated by comma', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -286,7 +288,7 @@ describe('PermissionEditor', () => {
|
||||
it('adds multiple items separated by space', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -308,7 +310,7 @@ describe('PermissionEditor', () => {
|
||||
it('does not add duplicate items', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -330,7 +332,7 @@ describe('PermissionEditor', () => {
|
||||
it('removes item when X clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -356,7 +358,7 @@ describe('PermissionEditor', () => {
|
||||
it('names each badge close button after the item it removes', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const readToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -385,7 +387,7 @@ describe('PermissionEditor', () => {
|
||||
it('exposes the full item value as a title so truncated badges stay readable', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const readToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -407,7 +409,7 @@ describe('PermissionEditor', () => {
|
||||
it('moves focus to the previous badge when closed with the keyboard', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const readToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -438,7 +440,7 @@ describe('PermissionEditor', () => {
|
||||
it('does not steal focus when a badge is closed with the mouse', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const readToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -471,7 +473,7 @@ describe('PermissionEditor', () => {
|
||||
it('shows Add button disabled when input is empty', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -491,7 +493,7 @@ describe('PermissionEditor', () => {
|
||||
it('shows confirm dialog when leaving Only Selected with items', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -515,7 +517,7 @@ describe('PermissionEditor', () => {
|
||||
it('clears items when confirmed', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -544,7 +546,7 @@ describe('PermissionEditor', () => {
|
||||
it('keeps items when cancelled', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -575,7 +577,7 @@ describe('PermissionEditor', () => {
|
||||
it('does not show dialog when leaving Only Selected with no items', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const createToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -594,7 +596,7 @@ describe('PermissionEditor', () => {
|
||||
describe('verbs without Only Selected option', () => {
|
||||
it('does not show Only Selected for list verb', async () => {
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const listToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -623,14 +625,16 @@ describe('PermissionEditor', () => {
|
||||
});
|
||||
|
||||
it('expands all cards when expand button clicked', async () => {
|
||||
const user = userEvent.setup();
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const header = within(apiKeyCard).getByTestId(
|
||||
'resource-card-header-factor-api-key',
|
||||
);
|
||||
expect(header).toHaveAttribute('aria-expanded', 'true');
|
||||
await user.click(screen.getByTestId('expand-all-button'));
|
||||
|
||||
const headers = screen.getAllByTestId(/^resource-card-header-/);
|
||||
expect(headers.length).toBeGreaterThan(1);
|
||||
headers.forEach((header) => {
|
||||
expect(header).toHaveAttribute('aria-expanded', 'true');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -2,7 +2,9 @@ import { server } from 'mocks-server/server';
|
||||
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { setupAuthzAdmin } from 'lib/authz/utils/authz-test-utils';
|
||||
|
||||
import { expandAllCards, renderCreateRolePage } from './testUtils';
|
||||
import { expandResourceCard, renderCreateRolePage } from './testUtils';
|
||||
|
||||
jest.setTimeout(15_000);
|
||||
|
||||
beforeEach(() => {
|
||||
server.use(setupAuthzAdmin());
|
||||
@@ -17,7 +19,7 @@ async function selectOnlySelected(
|
||||
resource = 'logs',
|
||||
): Promise<void> {
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard(resource);
|
||||
|
||||
const card = screen.getByTestId(`resource-card-${resource}`);
|
||||
const readToggle = within(card).getByTestId(`action-toggle-${resource}-read`);
|
||||
@@ -60,7 +62,7 @@ describe('PermissionEditor - TelemetrySelectorWizard', () => {
|
||||
|
||||
it('does not show wizard button for non-telemetry resources', async () => {
|
||||
await renderCreateRolePage();
|
||||
await expandAllCards();
|
||||
await expandResourceCard('factor-api-key');
|
||||
|
||||
const apiKeyCard = screen.getByTestId('resource-card-factor-api-key');
|
||||
const readToggle = within(apiKeyCard).getByTestId(
|
||||
@@ -71,7 +73,9 @@ describe('PermissionEditor - TelemetrySelectorWizard', () => {
|
||||
await user.click(await within(readToggle).findByText('Only selected'));
|
||||
|
||||
expect(
|
||||
screen.queryByTestId('telemetry-wizard-trigger-logs-read'),
|
||||
within(apiKeyCard).queryByTestId(
|
||||
'telemetry-wizard-trigger-factor-api-key-read',
|
||||
),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Route, Switch } from 'react-router-dom';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, within } from 'tests/test-utils';
|
||||
import { TooltipProvider } from '@signozhq/ui/tooltip';
|
||||
|
||||
import CreateEditRolePage from '../CreateEditRolePage';
|
||||
@@ -26,8 +26,10 @@ export async function renderCreateRolePage(): Promise<
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function expandAllCards(): Promise<void> {
|
||||
export async function expandResourceCard(resourceId: string): Promise<void> {
|
||||
const user = userEvent.setup();
|
||||
const expandButton = await screen.findByTestId('expand-all-button');
|
||||
await user.click(expandButton);
|
||||
const card = await screen.findByTestId(`resource-card-${resourceId}`);
|
||||
await user.click(
|
||||
within(card).getByTestId(`resource-card-header-${resourceId}`),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { Color } from '@signozhq/design-tokens';
|
||||
import { useIsDarkMode } from 'hooks/useDarkMode';
|
||||
import { BellOff, CircleCheck, CircleOff, Flame } from '@signozhq/icons';
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import './AlertState.styles.scss';
|
||||
|
||||
type AlertStateProps = {
|
||||
state: string;
|
||||
state: RuletypesAlertStateDTO | string;
|
||||
showLabel?: boolean;
|
||||
};
|
||||
|
||||
@@ -17,7 +18,7 @@ export default function AlertState({
|
||||
let label;
|
||||
const isDarkMode = useIsDarkMode();
|
||||
switch (state) {
|
||||
case 'nodata':
|
||||
case RuletypesAlertStateDTO.nodata:
|
||||
icon = (
|
||||
<CircleOff
|
||||
size={18}
|
||||
@@ -28,7 +29,7 @@ export default function AlertState({
|
||||
label = <span style={{ color: Color.BG_SIENNA_400 }}>No Data</span>;
|
||||
break;
|
||||
|
||||
case 'disabled':
|
||||
case RuletypesAlertStateDTO.disabled:
|
||||
icon = (
|
||||
<BellOff
|
||||
size={18}
|
||||
@@ -38,15 +39,16 @@ export default function AlertState({
|
||||
);
|
||||
label = <span style={{ color: Color.BG_VANILLA_400 }}>Muted</span>;
|
||||
break;
|
||||
case 'firing':
|
||||
|
||||
case RuletypesAlertStateDTO.firing:
|
||||
icon = (
|
||||
<Flame size={18} fill={Color.BG_CHERRY_500} color={Color.BG_CHERRY_500} />
|
||||
);
|
||||
label = <span style={{ color: Color.BG_CHERRY_500 }}>Firing</span>;
|
||||
break;
|
||||
|
||||
case 'normal':
|
||||
case 'inactive':
|
||||
case RuletypesAlertStateDTO.inactive:
|
||||
case 'normal': // legacy
|
||||
icon = (
|
||||
<CircleCheck
|
||||
size={18}
|
||||
|
||||
@@ -1,28 +1,34 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { useMutation, useQuery, useQueryClient } from 'react-query';
|
||||
import { generatePath, useLocation } from 'react-router-dom';
|
||||
import { useCallback, useEffect, useMemo, useRef } from 'react';
|
||||
import { useMutation, useQueryClient, useQuery } from 'react-query';
|
||||
import { generatePath } from 'react-router-dom';
|
||||
import { TablePaginationConfig, TableProps } from 'antd';
|
||||
import type { FilterValue, SorterResult } from 'antd/es/table/interface';
|
||||
import { patchRulePartial } from 'api/alerts/patchRulePartial';
|
||||
import ruleStats from 'api/alerts/ruleStats';
|
||||
import timelineGraph from 'api/alerts/timelineGraph';
|
||||
import timelineTable from 'api/alerts/timelineTable';
|
||||
import topContributors from 'api/alerts/topContributors';
|
||||
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
|
||||
import {
|
||||
createRule,
|
||||
deleteRuleByID,
|
||||
getGetRuleByIDQueryKey,
|
||||
getGetRuleHistoryTimelineQueryOptions,
|
||||
invalidateGetRuleByID,
|
||||
invalidateListRules,
|
||||
updateRuleByID,
|
||||
useGetRuleByID,
|
||||
useGetRuleHistoryOverallStatus,
|
||||
useGetRuleHistoryStats,
|
||||
useGetRuleHistoryTopContributors,
|
||||
useListRules,
|
||||
} from 'api/generated/services/rules';
|
||||
import type {
|
||||
GetRuleByID200,
|
||||
RenderErrorResponseDTO,
|
||||
RuletypesPostableRuleDTO,
|
||||
import {
|
||||
Querybuildertypesv5OrderDirectionDTO,
|
||||
RuletypesAlertStateDTO,
|
||||
type GetRuleByID200,
|
||||
type GetRuleHistoryOverallStatus200,
|
||||
type GetRuleHistoryStats200,
|
||||
type GetRuleHistoryTimeline200,
|
||||
type GetRuleHistoryTopContributors200,
|
||||
type RenderErrorResponseDTO,
|
||||
type RuletypesPostableRuleDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { AxiosError } from 'axios';
|
||||
import { TabRoutes } from 'components/RouteTab/types';
|
||||
@@ -31,35 +37,27 @@ import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import ROUTES from 'constants/routes';
|
||||
import AlertHistory from 'container/AlertHistory';
|
||||
import { TIMELINE_TABLE_PAGE_SIZE } from 'container/AlertHistory/constants';
|
||||
import {
|
||||
computeCursorForPage,
|
||||
useTimelineTableOrder,
|
||||
useTimelineTablePage,
|
||||
} from 'container/AlertHistory/Timeline/Table/useTimelineTableCursor';
|
||||
import { AlertDetailsTab, TimelineFilter } from 'container/AlertHistory/types';
|
||||
import { urlKey } from 'container/AllError/utils';
|
||||
import { DEFAULT_TIME_RANGE } from 'container/TopNav/DateTimeSelectionV2/constants';
|
||||
import { useNotifications } from 'hooks/useNotifications';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import createQueryParams from 'lib/createQueryParams';
|
||||
import GetMinMax from 'lib/getMinMax';
|
||||
import history from 'lib/history';
|
||||
import { History, Table } from '@signozhq/icons';
|
||||
import EditRules from 'pages/EditRules';
|
||||
import { OrderPreferenceItems } from 'pages/Logs/config';
|
||||
import BetaTag from 'periscope/components/BetaTag/BetaTag';
|
||||
import PaginationInfoText from 'periscope/components/PaginationInfoText/PaginationInfoText';
|
||||
import { useAlertRule } from 'providers/Alert';
|
||||
import { useErrorModal } from 'providers/ErrorModalProvider';
|
||||
import { ErrorResponse, SuccessResponse } from 'types/api';
|
||||
import { toPostableRuleDTOFromAlertDef } from 'types/api/alerts/convert';
|
||||
import {
|
||||
AlertDef,
|
||||
AlertRuleStatsPayload,
|
||||
AlertRuleTimelineGraphResponsePayload,
|
||||
AlertRuleTimelineTableResponse,
|
||||
AlertRuleTimelineTableResponsePayload,
|
||||
AlertRuleTopContributorsPayload,
|
||||
} from 'types/api/alerts/def';
|
||||
import { AlertDef, AlertRuleTimelineTableResponse } from 'types/api/alerts/def';
|
||||
import APIError from 'types/api/error';
|
||||
import { TagFilter } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { nanoToMilli } from 'utils/timeUtils';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
|
||||
export const useAlertHistoryQueryParams = (): {
|
||||
ruleId: string | null;
|
||||
@@ -201,10 +199,7 @@ type GetAlertRuleDetailsApiProps = {
|
||||
};
|
||||
|
||||
type GetAlertRuleDetailsStatsProps = GetAlertRuleDetailsApiProps & {
|
||||
data:
|
||||
| SuccessResponse<AlertRuleStatsPayload, unknown>
|
||||
| ErrorResponse
|
||||
| undefined;
|
||||
data: GetRuleHistoryStats200 | undefined;
|
||||
};
|
||||
|
||||
export const useGetAlertRuleDetailsStats =
|
||||
@@ -213,18 +208,15 @@ export const useGetAlertRuleDetailsStats =
|
||||
|
||||
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
|
||||
|
||||
const { isLoading, isRefetching, isError, data } = useQuery(
|
||||
[REACT_QUERY_KEY.ALERT_RULE_STATS, ruleId, startTime, endTime],
|
||||
const { isLoading, isRefetching, isError, data } = useGetRuleHistoryStats(
|
||||
{ id: ruleId || '' },
|
||||
{ start: startTime, end: endTime },
|
||||
{
|
||||
queryFn: () =>
|
||||
ruleStats({
|
||||
id: ruleId || '',
|
||||
start: startTime,
|
||||
end: endTime,
|
||||
}),
|
||||
enabled: isValidRuleId && !!startTime && !!endTime,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
query: {
|
||||
enabled: isValidRuleId && !!startTime && !!endTime,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
@@ -232,10 +224,7 @@ export const useGetAlertRuleDetailsStats =
|
||||
};
|
||||
|
||||
type GetAlertRuleDetailsTopContributorsProps = GetAlertRuleDetailsApiProps & {
|
||||
data:
|
||||
| SuccessResponse<AlertRuleTopContributorsPayload, unknown>
|
||||
| ErrorResponse
|
||||
| undefined;
|
||||
data: GetRuleHistoryTopContributors200 | undefined;
|
||||
};
|
||||
|
||||
export const useGetAlertRuleDetailsTopContributors =
|
||||
@@ -244,90 +233,128 @@ export const useGetAlertRuleDetailsTopContributors =
|
||||
|
||||
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
|
||||
|
||||
const { isLoading, isRefetching, isError, data } = useQuery(
|
||||
[REACT_QUERY_KEY.ALERT_RULE_TOP_CONTRIBUTORS, ruleId, startTime, endTime],
|
||||
{
|
||||
queryFn: () =>
|
||||
topContributors({
|
||||
id: ruleId || '',
|
||||
start: startTime,
|
||||
end: endTime,
|
||||
}),
|
||||
enabled: isValidRuleId,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
);
|
||||
const { isLoading, isRefetching, isError, data } =
|
||||
useGetRuleHistoryTopContributors(
|
||||
{ id: ruleId || '' },
|
||||
{ start: startTime, end: endTime },
|
||||
{
|
||||
query: {
|
||||
enabled: isValidRuleId && !!startTime && !!endTime,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return { isLoading, isRefetching, isError, data, isValidRuleId, ruleId };
|
||||
};
|
||||
|
||||
type GetAlertRuleDetailsTimelineTableProps = GetAlertRuleDetailsApiProps & {
|
||||
data:
|
||||
| SuccessResponse<AlertRuleTimelineTableResponsePayload, unknown>
|
||||
| ErrorResponse
|
||||
| undefined;
|
||||
data: GetRuleHistoryTimeline200 | undefined;
|
||||
error: AxiosError<RenderErrorResponseDTO> | null;
|
||||
refetch: () => void;
|
||||
cancel: () => void;
|
||||
};
|
||||
|
||||
export const useGetAlertRuleDetailsTimelineTable = ({
|
||||
filters,
|
||||
filterExpression,
|
||||
}: {
|
||||
filters: TagFilter;
|
||||
filterExpression: string;
|
||||
}): GetAlertRuleDetailsTimelineTableProps => {
|
||||
const queryClient = useQueryClient();
|
||||
const { ruleId, startTime, endTime, params } = useAlertHistoryQueryParams();
|
||||
const { updatedOrder, offset } = useMemo(
|
||||
() => ({
|
||||
updatedOrder: params.get(urlKey.order) ?? OrderPreferenceItems.ASC,
|
||||
offset: parseInt(params.get(urlKey.offset) ?? '0', 10),
|
||||
}),
|
||||
[params],
|
||||
const [page, setPage] = useTimelineTablePage();
|
||||
const [order] = useTimelineTableOrder();
|
||||
|
||||
const updatedOrder = useMemo(
|
||||
() =>
|
||||
order === 'asc'
|
||||
? Querybuildertypesv5OrderDirectionDTO.asc
|
||||
: Querybuildertypesv5OrderDirectionDTO.desc,
|
||||
[order],
|
||||
);
|
||||
|
||||
const timelineFilter = params.get('timelineFilter');
|
||||
|
||||
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
|
||||
const hasStartAndEnd = startTime !== null && endTime !== null;
|
||||
|
||||
const { isLoading, isRefetching, isError, data } = useQuery(
|
||||
[
|
||||
REACT_QUERY_KEY.ALERT_RULE_TIMELINE_TABLE,
|
||||
ruleId,
|
||||
startTime,
|
||||
endTime,
|
||||
timelineFilter,
|
||||
updatedOrder,
|
||||
offset,
|
||||
JSON.stringify(filters.items),
|
||||
],
|
||||
const stateFilter = useMemo(() => {
|
||||
if (!timelineFilter || timelineFilter === TimelineFilter.ALL) {
|
||||
return undefined;
|
||||
}
|
||||
return timelineFilter === TimelineFilter.FIRED
|
||||
? RuletypesAlertStateDTO.firing
|
||||
: RuletypesAlertStateDTO.inactive;
|
||||
}, [timelineFilter]);
|
||||
|
||||
const filtersKey = `${filterExpression}|${stateFilter ?? ''}|${startTime}|${endTime}`;
|
||||
const prevFiltersKeyRef = useRef(filtersKey);
|
||||
const filtersChanged = prevFiltersKeyRef.current !== filtersKey;
|
||||
const cursor = computeCursorForPage(filtersChanged ? 1 : page);
|
||||
|
||||
useEffect(() => {
|
||||
if (prevFiltersKeyRef.current !== filtersKey) {
|
||||
prevFiltersKeyRef.current = filtersKey;
|
||||
if (page > 1) {
|
||||
void setPage(1);
|
||||
}
|
||||
}
|
||||
}, [filtersKey, page, setPage]);
|
||||
|
||||
const queryParams = useMemo(
|
||||
() => ({
|
||||
start: startTime,
|
||||
end: endTime,
|
||||
limit: TIMELINE_TABLE_PAGE_SIZE,
|
||||
order: updatedOrder,
|
||||
cursor,
|
||||
filterExpression: filterExpression || undefined,
|
||||
state: stateFilter,
|
||||
}),
|
||||
[startTime, endTime, updatedOrder, cursor, filterExpression, stateFilter],
|
||||
);
|
||||
|
||||
const queryOptions = getGetRuleHistoryTimelineQueryOptions(
|
||||
{ id: ruleId || '' },
|
||||
queryParams,
|
||||
{
|
||||
queryFn: () =>
|
||||
timelineTable({
|
||||
id: ruleId || '',
|
||||
start: startTime,
|
||||
end: endTime,
|
||||
limit: TIMELINE_TABLE_PAGE_SIZE,
|
||||
order: updatedOrder,
|
||||
offset,
|
||||
filters,
|
||||
...(timelineFilter && timelineFilter !== TimelineFilter.ALL
|
||||
? {
|
||||
state: timelineFilter === TimelineFilter.FIRED ? 'firing' : 'normal',
|
||||
}
|
||||
: {}),
|
||||
}),
|
||||
enabled: isValidRuleId && hasStartAndEnd,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
query: {
|
||||
enabled: isValidRuleId,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return { isLoading, isRefetching, isError, data, isValidRuleId, ruleId };
|
||||
const { isLoading, isRefetching, isError, data, error, refetch } =
|
||||
useQuery(queryOptions);
|
||||
|
||||
const queryKeyRef = useRef(queryOptions.queryKey);
|
||||
queryKeyRef.current = queryOptions.queryKey;
|
||||
|
||||
const cancel = useCallback(() => {
|
||||
void queryClient.cancelQueries({ queryKey: queryKeyRef.current });
|
||||
}, [queryClient]);
|
||||
|
||||
return {
|
||||
isLoading,
|
||||
isRefetching,
|
||||
isError,
|
||||
data,
|
||||
error: error as AxiosError<RenderErrorResponseDTO> | null,
|
||||
isValidRuleId,
|
||||
ruleId,
|
||||
refetch,
|
||||
cancel,
|
||||
};
|
||||
};
|
||||
|
||||
export const useTimelineTable = ({
|
||||
totalItems,
|
||||
nextCursor,
|
||||
}: {
|
||||
totalItems: number;
|
||||
nextCursor?: string;
|
||||
}): {
|
||||
paginationConfig: TablePaginationConfig;
|
||||
onChangeHandler: (
|
||||
@@ -336,16 +363,13 @@ export const useTimelineTable = ({
|
||||
filters: any,
|
||||
extra: any,
|
||||
) => void;
|
||||
handleNextPage: () => void;
|
||||
handlePrevPage: () => void;
|
||||
hasNextPage: boolean;
|
||||
hasPrevPage: boolean;
|
||||
} => {
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
|
||||
const { pathname } = useLocation();
|
||||
|
||||
const { search } = useLocation();
|
||||
|
||||
const params = useMemo(() => new URLSearchParams(search), [search]);
|
||||
|
||||
const offset = params.get('offset') ?? '0';
|
||||
const [page, setPage] = useTimelineTablePage();
|
||||
const [, setOrder] = useTimelineTableOrder();
|
||||
|
||||
const onChangeHandler: TableProps<AlertRuleTimelineTableResponse>['onChange'] =
|
||||
useCallback(
|
||||
@@ -357,38 +381,52 @@ export const useTimelineTable = ({
|
||||
| SorterResult<AlertRuleTimelineTableResponse>,
|
||||
) => {
|
||||
if (!Array.isArray(sorter)) {
|
||||
const { pageSize = 0, current = 0 } = pagination;
|
||||
const { order } = sorter;
|
||||
const updatedOrder = order === 'ascend' ? 'asc' : 'desc';
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
|
||||
safeNavigate(
|
||||
`${pathname}?${createQueryParams({
|
||||
...Object.fromEntries(params),
|
||||
order: updatedOrder,
|
||||
offset: current * TIMELINE_TABLE_PAGE_SIZE - TIMELINE_TABLE_PAGE_SIZE,
|
||||
pageSize,
|
||||
})}`,
|
||||
);
|
||||
void Promise.all([setOrder(updatedOrder), setPage(1)]);
|
||||
}
|
||||
},
|
||||
[pathname, safeNavigate],
|
||||
[setOrder, setPage],
|
||||
);
|
||||
|
||||
const offsetInt = parseInt(offset, 10);
|
||||
const pageSize = params.get('pageSize') ?? String(TIMELINE_TABLE_PAGE_SIZE);
|
||||
const pageSizeInt = parseInt(pageSize, 10);
|
||||
const handleNextPage = useCallback(() => {
|
||||
if (!nextCursor) {
|
||||
return;
|
||||
}
|
||||
void setPage(page + 1);
|
||||
}, [nextCursor, page, setPage]);
|
||||
|
||||
const handlePrevPage = useCallback(() => {
|
||||
if (page <= 1) {
|
||||
return;
|
||||
}
|
||||
void setPage(page - 1);
|
||||
}, [page, setPage]);
|
||||
|
||||
const paginationConfig: TablePaginationConfig = {
|
||||
pageSize: pageSizeInt,
|
||||
showTotal: PaginationInfoText,
|
||||
current: offsetInt / TIMELINE_TABLE_PAGE_SIZE + 1,
|
||||
pageSize: TIMELINE_TABLE_PAGE_SIZE,
|
||||
showTotal: (total, [start, end]) => (
|
||||
<span>
|
||||
<Typography.Text size="small">
|
||||
{start} — {end}
|
||||
</Typography.Text>
|
||||
<Typography.Text size="small"> of {total}</Typography.Text>
|
||||
</span>
|
||||
),
|
||||
current: page,
|
||||
showSizeChanger: false,
|
||||
hideOnSinglePage: true,
|
||||
total: totalItems,
|
||||
};
|
||||
|
||||
return { paginationConfig, onChangeHandler };
|
||||
return {
|
||||
paginationConfig,
|
||||
onChangeHandler,
|
||||
handleNextPage,
|
||||
handlePrevPage,
|
||||
hasNextPage: !!nextCursor,
|
||||
hasPrevPage: page > 1,
|
||||
};
|
||||
};
|
||||
|
||||
export const useAlertRuleStatusToggle = ({
|
||||
@@ -581,10 +619,7 @@ export const useAlertRuleDelete = ({
|
||||
};
|
||||
|
||||
type GetAlertRuleDetailsTimelineGraphProps = GetAlertRuleDetailsApiProps & {
|
||||
data:
|
||||
| SuccessResponse<AlertRuleTimelineGraphResponsePayload, unknown>
|
||||
| ErrorResponse
|
||||
| undefined;
|
||||
data: GetRuleHistoryOverallStatus200 | undefined;
|
||||
};
|
||||
|
||||
export const useGetAlertRuleDetailsTimelineGraphData =
|
||||
@@ -594,20 +629,18 @@ export const useGetAlertRuleDetailsTimelineGraphData =
|
||||
const isValidRuleId = ruleId !== null && String(ruleId).length !== 0;
|
||||
const hasStartAndEnd = startTime !== null && endTime !== null;
|
||||
|
||||
const { isLoading, isRefetching, isError, data } = useQuery(
|
||||
[REACT_QUERY_KEY.ALERT_RULE_TIMELINE_GRAPH, ruleId, startTime, endTime],
|
||||
{
|
||||
queryFn: () =>
|
||||
timelineGraph({
|
||||
id: ruleId || '',
|
||||
start: startTime,
|
||||
end: endTime,
|
||||
}),
|
||||
enabled: isValidRuleId && hasStartAndEnd,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
);
|
||||
const { isLoading, isRefetching, isError, data } =
|
||||
useGetRuleHistoryOverallStatus(
|
||||
{ id: ruleId || '' },
|
||||
{ start: startTime, end: endTime },
|
||||
{
|
||||
query: {
|
||||
enabled: isValidRuleId && hasStartAndEnd,
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return { isLoading, isRefetching, isError, data, isValidRuleId, ruleId };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import {
|
||||
emptyVariableFormModel,
|
||||
type VariableFormModel,
|
||||
} from '../variableFormModel';
|
||||
import { dtoToFormModel, formModelToDto } from '../variableAdapters';
|
||||
|
||||
function model(overrides: Partial<VariableFormModel>): VariableFormModel {
|
||||
return { ...emptyVariableFormModel(), name: 'v', ...overrides };
|
||||
}
|
||||
|
||||
/** The list spec a saved variable carries, whatever its plugin. */
|
||||
function listSpec(m: VariableFormModel): {
|
||||
allowMultiple?: boolean;
|
||||
allowAllValue?: boolean;
|
||||
} {
|
||||
return formModelToDto(m).spec as {
|
||||
allowMultiple?: boolean;
|
||||
allowAllValue?: boolean;
|
||||
};
|
||||
}
|
||||
|
||||
describe('formModelToDto — the ALL flag needs multi-select', () => {
|
||||
it('keeps ALL for a multi-select dynamic variable', () => {
|
||||
expect(
|
||||
listSpec(
|
||||
model({
|
||||
type: 'DYNAMIC',
|
||||
dynamicAttribute: 'host.name',
|
||||
multiSelect: true,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ allowMultiple: true, allowAllValue: true });
|
||||
});
|
||||
|
||||
it('drops ALL for a single-select dynamic variable', () => {
|
||||
// The API rejects allowAllValue without allowMultiple, and this used to be forced
|
||||
// true for every dynamic variable — which blocked saving the whole dashboard.
|
||||
expect(
|
||||
listSpec(
|
||||
model({
|
||||
type: 'DYNAMIC',
|
||||
dynamicAttribute: 'host.name',
|
||||
multiSelect: false,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ allowMultiple: false, allowAllValue: false });
|
||||
});
|
||||
|
||||
it('drops ALL for a single-select query variable that still carries the flag', () => {
|
||||
expect(
|
||||
listSpec(
|
||||
model({
|
||||
type: 'QUERY',
|
||||
queryValue: 'SELECT 1',
|
||||
multiSelect: false,
|
||||
showAllOption: true,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ allowMultiple: false, allowAllValue: false });
|
||||
});
|
||||
|
||||
it('respects the toggle on a multi-select query variable', () => {
|
||||
expect(
|
||||
listSpec(
|
||||
model({
|
||||
type: 'QUERY',
|
||||
queryValue: 'SELECT 1',
|
||||
multiSelect: true,
|
||||
showAllOption: false,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ allowMultiple: true, allowAllValue: false });
|
||||
});
|
||||
|
||||
it('round-trips a single-select dynamic variable unchanged', () => {
|
||||
// What the dashboard in the report holds: saving it must not flip the flag.
|
||||
const dto = {
|
||||
kind: 'ListVariable',
|
||||
spec: {
|
||||
name: 'host.name',
|
||||
display: { name: 'host.name', description: '' },
|
||||
allowMultiple: false,
|
||||
allowAllValue: false,
|
||||
sort: 'alphabetical-asc',
|
||||
plugin: {
|
||||
kind: 'signoz/DynamicVariable',
|
||||
spec: { name: 'host.name', signal: 'all' },
|
||||
},
|
||||
},
|
||||
} as never;
|
||||
|
||||
expect(listSpec(dtoToFormModel(dto))).toMatchObject({
|
||||
allowMultiple: false,
|
||||
allowAllValue: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -133,9 +133,14 @@ export function formModelToDto(
|
||||
name: model.name,
|
||||
display,
|
||||
allowMultiple: model.multiSelect,
|
||||
// Dynamic variables always expose the aggregate "ALL" entry (matches V1,
|
||||
// which forced showALLOption true on save); other types respect the toggle.
|
||||
allowAllValue: model.type === 'DYNAMIC' ? true : model.showAllOption,
|
||||
// Dynamic variables always expose the aggregate "ALL" entry (matches V1, which
|
||||
// forced showALLOption true on save); other types respect the toggle. Either
|
||||
// way it needs multi-select — ALL is a set of values, and the API rejects the
|
||||
// flag without it, which used to make a single-select dynamic variable
|
||||
// unsaveable and blocked every other edit to the dashboard with it.
|
||||
allowAllValue:
|
||||
model.multiSelect &&
|
||||
(model.type === 'DYNAMIC' ? true : model.showAllOption),
|
||||
// model.sort is already a Perses sort token (`none` / `alphabetical-*`).
|
||||
sort: model.sort,
|
||||
defaultValue: model.defaultValue,
|
||||
|
||||
@@ -0,0 +1,164 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { useState } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider as ReduxProvider } from 'react-redux';
|
||||
import { MemoryRouter, Route, useHistory, useParams } from 'react-router-dom';
|
||||
import { CompatRouter } from 'react-router-dom-v5-compat';
|
||||
import { TooltipProvider } from '@signozhq/ui/tooltip';
|
||||
import {
|
||||
type DashboardtypesPanelDTO,
|
||||
TelemetrytypesSignalDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { QueryBuilderProvider } from 'providers/QueryBuilder';
|
||||
import configureStore from 'redux-mock-store';
|
||||
import appStore from 'store';
|
||||
|
||||
import { useOpenPanelEditor } from '../../hooks/useOpenPanelEditor';
|
||||
import { usePanelEditorQuerySync } from '../hooks/usePanelEditorQuerySync';
|
||||
import PanelEditorQueryBuilder from '../PanelEditorQueryBuilder/PanelEditorQueryBuilder';
|
||||
|
||||
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
|
||||
jest.mock('hooks/useSafeNavigate', () => {
|
||||
const { useHistory: useRouterHistory } =
|
||||
jest.requireActual('react-router-dom');
|
||||
return {
|
||||
useSafeNavigate: (): unknown => {
|
||||
const history = useRouterHistory();
|
||||
return {
|
||||
safeNavigate: (to: string): void => history.push(to),
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('../../store/useDashboardStore', () => ({
|
||||
useDashboardStore: (selector: (s: unknown) => unknown): unknown =>
|
||||
selector({ dashboardId: 'dash-1' }),
|
||||
}));
|
||||
|
||||
function makePromPanel(name: string, promql: string): DashboardtypesPanelDTO {
|
||||
return {
|
||||
kind: 'Panel',
|
||||
spec: {
|
||||
display: { name },
|
||||
plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },
|
||||
queries: [
|
||||
{
|
||||
kind: 'time_series',
|
||||
spec: {
|
||||
plugin: {
|
||||
kind: 'signoz/PromQLQuery',
|
||||
spec: { name: 'A', query: promql, legend: '', disabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
const PANELS: Record<string, DashboardtypesPanelDTO> = {
|
||||
A: makePromPanel('Panel A', 'up{job="alpha"}'),
|
||||
B: makePromPanel('Panel B', 'up{job="bravo"}'),
|
||||
};
|
||||
|
||||
const noop = (): void => {};
|
||||
|
||||
/** Stands in for the editor route: the same draft + builder sync `PanelEditorContainer` runs. */
|
||||
function EditorRoute(): JSX.Element {
|
||||
const { panelId } = useParams<{ panelId: string }>();
|
||||
const [panel] = useState(PANELS[panelId]);
|
||||
|
||||
usePanelEditorQuerySync({
|
||||
draft: panel,
|
||||
panelType: PANEL_TYPES.TIME_SERIES,
|
||||
setSpec: noop,
|
||||
refetch: noop,
|
||||
signal: TelemetrytypesSignalDTO.metrics,
|
||||
savedQueries: panel.spec.queries,
|
||||
});
|
||||
|
||||
return (
|
||||
<PanelEditorQueryBuilder
|
||||
panelKind="signoz/TimeSeriesPanel"
|
||||
signal={TelemetrytypesSignalDTO.metrics}
|
||||
isLoadingQueries={false}
|
||||
onStageRunQuery={noop}
|
||||
onCancelQuery={noop}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function Harness(): JSX.Element {
|
||||
const openPanelEditor = useOpenPanelEditor();
|
||||
const history = useHistory();
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="edit-a"
|
||||
onClick={(): void => openPanelEditor('A', { panel: PANELS.A })}
|
||||
>
|
||||
edit A
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="edit-b"
|
||||
onClick={(): void => openPanelEditor('B', { panel: PANELS.B })}
|
||||
>
|
||||
edit B
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="back"
|
||||
onClick={(): void => history.push('/dashboard/dash-1')}
|
||||
>
|
||||
back
|
||||
</button>
|
||||
<Route
|
||||
path="/dashboard/:dashboardId/panel/:panelId"
|
||||
component={EditorRoute}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const renderHarness = (): void => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/dashboard/dash-1']}>
|
||||
<CompatRouter>
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<ReduxProvider store={configureStore([])(appStore.getState())}>
|
||||
<TooltipProvider>
|
||||
<QueryBuilderProvider>
|
||||
<Harness />
|
||||
</QueryBuilderProvider>
|
||||
</TooltipProvider>
|
||||
</ReduxProvider>
|
||||
</QueryClientProvider>
|
||||
</CompatRouter>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('Panel editor route, PromQL panels', () => {
|
||||
it('opens on the edited panel query, not the previously edited one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('edit-a'));
|
||||
expect(screen.getByTestId('promql-query-input')).toHaveValue(
|
||||
'up{job="alpha"}',
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('back'));
|
||||
await user.click(screen.getByTestId('edit-b'));
|
||||
expect(screen.getByTestId('promql-query-input')).toHaveValue(
|
||||
'up{job="bravo"}',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -27,6 +27,7 @@ import { stepClickTimeRange } from '../../utils/drilldown/chartClickTimeRange';
|
||||
import { enrichChartClick } from '../../utils/drilldown/enrichChartClick';
|
||||
import { getBuilderQueries } from '../../utils/getBuilderQueries';
|
||||
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
|
||||
import { sortSeriesByMeanDesc } from '../../utils/sortSeriesByMean';
|
||||
|
||||
import { buildBarChartConfig } from './utils/buildConfig';
|
||||
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
@@ -70,7 +71,12 @@ function BarPanelRenderer({
|
||||
|
||||
const flatSeries = useMemo(
|
||||
() =>
|
||||
flattenTimeSeries(getTimeSeriesResults(data.response), data.legendMap ?? {}),
|
||||
sortSeriesByMeanDesc(
|
||||
flattenTimeSeries(
|
||||
getTimeSeriesResults(data.response),
|
||||
data.legendMap ?? {},
|
||||
),
|
||||
),
|
||||
[data.response, data.legendMap],
|
||||
);
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import { stepClickTimeRange } from '../../utils/drilldown/chartClickTimeRange';
|
||||
import { enrichChartClick } from '../../utils/drilldown/enrichChartClick';
|
||||
import { getBuilderQueries } from '../../utils/getBuilderQueries';
|
||||
import { getPanelTimeRange } from '../../utils/getPanelTimeRange';
|
||||
import { sortSeriesByMeanDesc } from '../../utils/sortSeriesByMean';
|
||||
|
||||
import { buildTimeSeriesConfig } from './utils/buildConfig';
|
||||
import { ChartClickData } from 'lib/uPlotV2/plugins/TooltipPlugin/types';
|
||||
@@ -71,7 +72,12 @@ function TimeSeriesPanelRenderer({
|
||||
|
||||
const flatSeries = useMemo(
|
||||
() =>
|
||||
flattenTimeSeries(getTimeSeriesResults(data.response), data.legendMap ?? {}),
|
||||
sortSeriesByMeanDesc(
|
||||
flattenTimeSeries(
|
||||
getTimeSeriesResults(data.response),
|
||||
data.legendMap ?? {},
|
||||
),
|
||||
),
|
||||
[data.response, data.legendMap],
|
||||
);
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
|
||||
import { sortSeriesByMeanDesc } from '../sortSeriesByMean';
|
||||
|
||||
function makeSeries(
|
||||
queryName: string,
|
||||
values: number[],
|
||||
overrides: Partial<PanelSeries> = {},
|
||||
): PanelSeries {
|
||||
return {
|
||||
queryName,
|
||||
legend: '',
|
||||
labels: {},
|
||||
kind: 'series',
|
||||
values: values.map((value, index) => ({
|
||||
timestamp: (index + 1) * 1_000,
|
||||
value,
|
||||
})),
|
||||
aggregation: { index: 0, alias: '' },
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const names = (series: PanelSeries[]): string[] =>
|
||||
series.map((item) => item.queryName);
|
||||
|
||||
describe('sortSeriesByMeanDesc', () => {
|
||||
it('orders series by descending mean', () => {
|
||||
const sorted = sortSeriesByMeanDesc([
|
||||
makeSeries('A', [1, 1]),
|
||||
makeSeries('B', [10, 20]),
|
||||
makeSeries('C', [5, 5]),
|
||||
]);
|
||||
|
||||
expect(names(sorted)).toStrictEqual(['B', 'C', 'A']);
|
||||
});
|
||||
|
||||
it('sinks series with no finite points to the bottom', () => {
|
||||
const sorted = sortSeriesByMeanDesc([
|
||||
makeSeries('A', []),
|
||||
makeSeries('B', [NaN, Infinity]),
|
||||
makeSeries('C', [1]),
|
||||
]);
|
||||
|
||||
expect(names(sorted)).toStrictEqual(['C', 'A', 'B']);
|
||||
});
|
||||
|
||||
it('ignores non-finite points when averaging', () => {
|
||||
const sorted = sortSeriesByMeanDesc([
|
||||
makeSeries('A', [2, 2]),
|
||||
// Mean over finite points only is 10, so NaN must not poison it to last place.
|
||||
makeSeries('B', [10, NaN]),
|
||||
]);
|
||||
|
||||
expect(names(sorted)).toStrictEqual(['B', 'A']);
|
||||
});
|
||||
|
||||
it('produces the same order regardless of input order', () => {
|
||||
const a = makeSeries('A', [5]);
|
||||
const b = makeSeries('B', [5]);
|
||||
const c = makeSeries('C', [9]);
|
||||
|
||||
expect(names(sortSeriesByMeanDesc([a, b, c]))).toStrictEqual(
|
||||
names(sortSeriesByMeanDesc([c, b, a])),
|
||||
);
|
||||
expect(names(sortSeriesByMeanDesc([b, a, c]))).toStrictEqual(['C', 'A', 'B']);
|
||||
});
|
||||
|
||||
it('tiebreaks equal means on labels when the query name matches', () => {
|
||||
const forward = sortSeriesByMeanDesc([
|
||||
makeSeries('A', [1], { labels: { host: 'b' } }),
|
||||
makeSeries('A', [1], { labels: { host: 'a' } }),
|
||||
]);
|
||||
const reversed = sortSeriesByMeanDesc([
|
||||
makeSeries('A', [1], { labels: { host: 'a' } }),
|
||||
makeSeries('A', [1], { labels: { host: 'b' } }),
|
||||
]);
|
||||
|
||||
expect(forward.map((item) => item.labels.host)).toStrictEqual(['a', 'b']);
|
||||
expect(reversed.map((item) => item.labels.host)).toStrictEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it('does not mutate the input array', () => {
|
||||
const input = [makeSeries('A', [1]), makeSeries('B', [9])];
|
||||
|
||||
const sorted = sortSeriesByMeanDesc(input);
|
||||
|
||||
expect(names(input)).toStrictEqual(['A', 'B']);
|
||||
expect(names(sorted)).toStrictEqual(['B', 'A']);
|
||||
});
|
||||
|
||||
it('returns an empty array for no series', () => {
|
||||
expect(sortSeriesByMeanDesc([])).toStrictEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { getPanelDefinition } from '../registry';
|
||||
import { PANEL_KIND_TO_PANEL_TYPE } from '../types/panelKind';
|
||||
import { fromPerses } from '../../queryV5/persesQueryAdapters';
|
||||
|
||||
/**
|
||||
* The panel's saved query as a builder `Query` — what the editor route and the View
|
||||
* modal put in `compositeQuery` when they open. Matches the seed
|
||||
* `usePanelEditorQuerySync` computes from the panel.
|
||||
*/
|
||||
export function getPanelBuilderQuery(panel: DashboardtypesPanelDTO): Query {
|
||||
const kind = panel.spec.plugin.kind;
|
||||
const [defaultSignal] = getPanelDefinition(kind).supportedSignals;
|
||||
// A query-less panel seeds from the kind's first supported signal — `fromPerses`'s
|
||||
// metrics default isn't authorable in every kind (e.g. List).
|
||||
if (panel.spec.queries.length === 0 && defaultSignal) {
|
||||
return initialQueriesMap[defaultSignal];
|
||||
}
|
||||
return fromPerses(panel.spec.queries, PANEL_KIND_TO_PANEL_TYPE[kind]);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import { sortByMeanDesc } from 'container/DashboardContainer/visualization/charts/utils/sortByMeanDesc';
|
||||
import type { PanelSeries } from 'pages/DashboardPageV2/DashboardContainer/queryV5/types';
|
||||
|
||||
function seriesKey(series: PanelSeries): string {
|
||||
const labels = Object.keys(series.labels)
|
||||
.sort()
|
||||
.map((name) => `${name}=${series.labels[name]}`)
|
||||
.join(',');
|
||||
return `${series.queryName}|${series.aggregation.index}|${series.kind}|${labels}`;
|
||||
}
|
||||
|
||||
/** `sortByMeanDesc` over flattened V5 series; call it before building the config and chart data. */
|
||||
export function sortSeriesByMeanDesc(series: PanelSeries[]): PanelSeries[] {
|
||||
return sortByMeanDesc(series, {
|
||||
getValues: (item) => item.values.map((point) => point.value),
|
||||
getKey: seriesKey,
|
||||
});
|
||||
}
|
||||
@@ -240,7 +240,10 @@ describe('usePanelActionItems', () => {
|
||||
(i) => 'key' in i && i.key === 'edit-panel',
|
||||
);
|
||||
(edit as { onClick: () => void }).onClick();
|
||||
expect(mockOpenEditor).toHaveBeenCalledWith('panel-1');
|
||||
// The panel rides along so its saved query lands in the editor URL.
|
||||
expect(mockOpenEditor).toHaveBeenCalledWith('panel-1', {
|
||||
panel: mockPanel,
|
||||
});
|
||||
});
|
||||
|
||||
it('"Move to section" offers a single "Dashboard (root)" target', () => {
|
||||
@@ -394,7 +397,9 @@ describe('usePanelActionItems', () => {
|
||||
(i) => 'key' in i && i.key === 'view-panel',
|
||||
);
|
||||
(view as { onClick: () => void }).onClick();
|
||||
expect(mockOpenView).toHaveBeenCalledWith('panel-1');
|
||||
// The panel goes along so the opener can seed the shared query builder before
|
||||
// the modal mounts (otherwise it renders the previously-viewed panel's query).
|
||||
expect(mockOpenView).toHaveBeenCalledWith('panel-1', baseArgs.panel);
|
||||
});
|
||||
|
||||
it('create-alert seeds an alert from this panel', () => {
|
||||
|
||||
@@ -130,7 +130,7 @@ export function usePanelActionItems({
|
||||
key: 'view-panel',
|
||||
label: 'View',
|
||||
icon: <Fullscreen size={14} />,
|
||||
onClick: (): void => openView(panelId),
|
||||
onClick: (): void => openView(panelId, panel),
|
||||
});
|
||||
}
|
||||
if (canEdit && canEditWidget && panelCapabilities.edit) {
|
||||
@@ -139,7 +139,7 @@ export function usePanelActionItems({
|
||||
label: label('Edit panel'),
|
||||
icon: <PenLine size={14} />,
|
||||
disabled: isLocked,
|
||||
onClick: (): void => openPanelEditor(panelId),
|
||||
onClick: (): void => openPanelEditor(panelId, { panel }),
|
||||
});
|
||||
}
|
||||
if (canEdit && canEditWidget && panelCapabilities.clone) {
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { ReactElement } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider as ReduxProvider } from 'react-redux';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { CompatRouter } from 'react-router-dom-v5-compat';
|
||||
import { TooltipProvider } from '@signozhq/ui/tooltip';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryBuilderProvider } from 'providers/QueryBuilder';
|
||||
import configureStore from 'redux-mock-store';
|
||||
import appStore from 'store';
|
||||
|
||||
import ViewPanelModal from '../ViewPanelModal/ViewPanelModal';
|
||||
import { useViewPanel } from '../hooks/useViewPanel';
|
||||
|
||||
// CodeMirror (the where-clause editor) needs real DOM measurement APIs.
|
||||
beforeAll(() => {
|
||||
const rect = {
|
||||
width: 100,
|
||||
height: 20,
|
||||
top: 0,
|
||||
left: 0,
|
||||
right: 100,
|
||||
bottom: 20,
|
||||
x: 0,
|
||||
y: 0,
|
||||
toJSON: (): unknown => rect,
|
||||
} as DOMRect;
|
||||
const rects = { length: 1, item: (): DOMRect => rect, 0: rect };
|
||||
document.createRange = (): Range =>
|
||||
({
|
||||
getClientRects: (): unknown => rects,
|
||||
getBoundingClientRect: (): DOMRect => rect,
|
||||
setStart: (): void => {},
|
||||
setEnd: (): void => {},
|
||||
startContainer: document.body,
|
||||
endContainer: document.body,
|
||||
startOffset: 0,
|
||||
endOffset: 0,
|
||||
collapsed: true,
|
||||
commonAncestorContainer: document.body,
|
||||
}) as unknown as Range;
|
||||
Element.prototype.getBoundingClientRect = (): DOMRect => rect;
|
||||
});
|
||||
|
||||
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
|
||||
jest.mock('hooks/useSafeNavigate', () => {
|
||||
const { useHistory } = jest.requireActual('react-router-dom');
|
||||
return {
|
||||
useSafeNavigate: (): unknown => {
|
||||
const history = useHistory();
|
||||
return {
|
||||
safeNavigate: (to: string, opts?: { replace?: boolean }): void => {
|
||||
if (opts?.replace) {
|
||||
history.replace(to);
|
||||
} else {
|
||||
history.push(to);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock('api/querySuggestions/getKeySuggestions', () => ({
|
||||
getKeySuggestions: jest
|
||||
.fn()
|
||||
.mockResolvedValue({ data: { data: { keys: {} } } }),
|
||||
}));
|
||||
jest.mock('api/querySuggestions/getValueSuggestion', () => ({
|
||||
getValueSuggestions: jest.fn().mockResolvedValue({
|
||||
data: { data: { values: { stringValues: [], numberValues: [] } } },
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery',
|
||||
() => ({
|
||||
usePanelQuery: (): unknown => ({
|
||||
data: undefined,
|
||||
isFetching: false,
|
||||
isPreviousData: false,
|
||||
error: null,
|
||||
refetch: jest.fn(),
|
||||
cancelQuery: jest.fn(),
|
||||
pagination: undefined,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',
|
||||
() => ({
|
||||
useDashboardStore: (selector: (s: unknown) => unknown): unknown =>
|
||||
selector({ dashboardId: 'dash-1' }),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/PanelEditor/PreviewPane/PreviewPane',
|
||||
() =>
|
||||
function MockPreviewPane(): ReactElement {
|
||||
return <div data-testid="preview-pane" />;
|
||||
},
|
||||
);
|
||||
|
||||
jest.mock('../hooks/useDrilldown', () => ({
|
||||
useDrilldown: (): unknown => ({
|
||||
enableDrillDown: false,
|
||||
onPanelClick: jest.fn(),
|
||||
contextMenuProps: {
|
||||
coordinates: null,
|
||||
popoverPosition: null,
|
||||
items: null,
|
||||
onClose: jest.fn(),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../hooks/usePanelInteractions', () => ({
|
||||
usePanelInteractions: (): unknown => ({
|
||||
onDragSelect: jest.fn(),
|
||||
dashboardPreference: { syncMode: 0 },
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock(
|
||||
'../ViewPanelModal/ViewPanelModalHeader',
|
||||
() =>
|
||||
function MockViewPanelModalHeader(): ReactElement {
|
||||
return <div data-testid="view-panel-header" />;
|
||||
},
|
||||
);
|
||||
|
||||
function makePanel(
|
||||
name: string,
|
||||
extras: Record<string, unknown>,
|
||||
): DashboardtypesPanelDTO {
|
||||
return {
|
||||
kind: 'Panel',
|
||||
spec: {
|
||||
display: { name },
|
||||
plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },
|
||||
queries: [
|
||||
{
|
||||
kind: 'time_series',
|
||||
spec: {
|
||||
plugin: {
|
||||
kind: 'signoz/BuilderQuery',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'logs',
|
||||
disabled: false,
|
||||
filter: { expression: "service = 'x'" },
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
...extras,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
const PANELS: Record<string, DashboardtypesPanelDTO> = {
|
||||
plain: makePanel('Plain panel', {}),
|
||||
grouped: makePanel('Grouped panel', {
|
||||
groupBy: [{ name: 'host.name', fieldDataType: 'string' }],
|
||||
having: { expression: 'count() > 5' },
|
||||
}),
|
||||
};
|
||||
|
||||
function Harness(): JSX.Element {
|
||||
const { expandedPanelId, openView, closeView } = useViewPanel();
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-plain"
|
||||
onClick={(): void => openView('plain', PANELS.plain)}
|
||||
>
|
||||
open plain
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-grouped"
|
||||
onClick={(): void => openView('grouped', PANELS.grouped)}
|
||||
>
|
||||
open grouped
|
||||
</button>
|
||||
<button type="button" data-testid="close" onClick={closeView}>
|
||||
close
|
||||
</button>
|
||||
<ViewPanelModal
|
||||
open={!!expandedPanelId}
|
||||
panel={expandedPanelId ? PANELS[expandedPanelId] : undefined}
|
||||
panelId={expandedPanelId ?? undefined}
|
||||
onClose={closeView}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const renderHarness = (): void => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/dashboard/dash-1']}>
|
||||
<CompatRouter>
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<ReduxProvider store={configureStore([])(appStore.getState())}>
|
||||
<TooltipProvider>
|
||||
<QueryBuilderProvider>
|
||||
<Harness />
|
||||
</QueryBuilderProvider>
|
||||
</TooltipProvider>
|
||||
</ReduxProvider>
|
||||
</QueryClientProvider>
|
||||
</CompatRouter>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
};
|
||||
|
||||
// QueryAddOns picks which rows are visible once on mount and never re-seeds, so unlike
|
||||
// the field values these never recover from a context swap that lands after mount.
|
||||
describe('View modal, builder add-on rows', () => {
|
||||
it('shows the opened panel add-ons, not the previous panel ones', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-grouped'));
|
||||
expect(screen.getByTestId('group-by-content')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('having-content')).toBeInTheDocument();
|
||||
|
||||
await user.click(screen.getByTestId('close'));
|
||||
await user.click(screen.getByTestId('open-plain'));
|
||||
expect(screen.queryByTestId('group-by-content')).not.toBeInTheDocument();
|
||||
expect(screen.queryByTestId('having-content')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows add-ons the opened panel has after a panel without them', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-plain'));
|
||||
await user.click(screen.getByTestId('close'));
|
||||
await user.click(screen.getByTestId('open-grouped'));
|
||||
|
||||
expect(screen.getByTestId('group-by-content')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('having-content')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import type { ReactElement } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
// eslint-disable-next-line no-restricted-imports
|
||||
import { Provider as ReduxProvider } from 'react-redux';
|
||||
import { MemoryRouter } from 'react-router-dom';
|
||||
import { CompatRouter } from 'react-router-dom-v5-compat';
|
||||
import { TooltipProvider } from '@signozhq/ui/tooltip';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryBuilderProvider } from 'providers/QueryBuilder';
|
||||
import configureStore from 'redux-mock-store';
|
||||
import appStore from 'store';
|
||||
|
||||
import ViewPanelModal from '../ViewPanelModal/ViewPanelModal';
|
||||
import { useViewPanel } from '../hooks/useViewPanel';
|
||||
|
||||
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
|
||||
jest.mock('hooks/useSafeNavigate', () => {
|
||||
const { useHistory } = jest.requireActual('react-router-dom');
|
||||
return {
|
||||
useSafeNavigate: (): unknown => {
|
||||
const history = useHistory();
|
||||
return {
|
||||
safeNavigate: (to: string, opts?: { replace?: boolean }): void => {
|
||||
if (opts?.replace) {
|
||||
history.replace(to);
|
||||
} else {
|
||||
history.push(to);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery',
|
||||
() => ({
|
||||
usePanelQuery: (): unknown => ({
|
||||
data: undefined,
|
||||
isFetching: false,
|
||||
isPreviousData: false,
|
||||
error: null,
|
||||
refetch: jest.fn(),
|
||||
cancelQuery: jest.fn(),
|
||||
pagination: undefined,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',
|
||||
() => ({
|
||||
useDashboardStore: (selector: (s: unknown) => unknown): unknown =>
|
||||
selector({ dashboardId: 'dash-1' }),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/PanelEditor/PreviewPane/PreviewPane',
|
||||
() =>
|
||||
function MockPreviewPane(): ReactElement {
|
||||
return <div data-testid="preview-pane" />;
|
||||
},
|
||||
);
|
||||
|
||||
jest.mock('../hooks/useDrilldown', () => ({
|
||||
useDrilldown: (): unknown => ({
|
||||
enableDrillDown: false,
|
||||
onPanelClick: jest.fn(),
|
||||
contextMenuProps: {
|
||||
coordinates: null,
|
||||
popoverPosition: null,
|
||||
items: null,
|
||||
onClose: jest.fn(),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../hooks/usePanelInteractions', () => ({
|
||||
usePanelInteractions: (): unknown => ({
|
||||
onDragSelect: jest.fn(),
|
||||
dashboardPreference: { syncMode: 0 },
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock(
|
||||
'../ViewPanelModal/ViewPanelModalHeader',
|
||||
() =>
|
||||
function MockViewPanelModalHeader(): ReactElement {
|
||||
return <div data-testid="view-panel-header" />;
|
||||
},
|
||||
);
|
||||
|
||||
function makePromPanel(name: string, promql: string): DashboardtypesPanelDTO {
|
||||
return {
|
||||
kind: 'Panel',
|
||||
spec: {
|
||||
display: { name },
|
||||
plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },
|
||||
queries: [
|
||||
{
|
||||
kind: 'time_series',
|
||||
spec: {
|
||||
plugin: {
|
||||
kind: 'signoz/PromQLQuery',
|
||||
spec: { name: 'A', query: promql, legend: '', disabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
const PANELS: Record<string, DashboardtypesPanelDTO> = {
|
||||
A: makePromPanel('Panel A', 'up{job="alpha"}'),
|
||||
B: makePromPanel('Panel B', 'up{job="bravo"}'),
|
||||
};
|
||||
|
||||
function Harness(): JSX.Element {
|
||||
const { expandedPanelId, openView, closeView } = useViewPanel();
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-a"
|
||||
onClick={(): void => openView('A', PANELS.A)}
|
||||
>
|
||||
open A
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-b"
|
||||
onClick={(): void => openView('B', PANELS.B)}
|
||||
>
|
||||
open B
|
||||
</button>
|
||||
<button type="button" data-testid="close" onClick={closeView}>
|
||||
close
|
||||
</button>
|
||||
<ViewPanelModal
|
||||
open={!!expandedPanelId}
|
||||
panel={expandedPanelId ? PANELS[expandedPanelId] : undefined}
|
||||
panelId={expandedPanelId ?? undefined}
|
||||
onClose={closeView}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const renderHarness = (): void => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/dashboard/dash-1']}>
|
||||
<CompatRouter>
|
||||
<QueryClientProvider client={new QueryClient()}>
|
||||
<ReduxProvider store={configureStore([])(appStore.getState())}>
|
||||
<TooltipProvider>
|
||||
<QueryBuilderProvider>
|
||||
<Harness />
|
||||
</QueryBuilderProvider>
|
||||
</TooltipProvider>
|
||||
</ReduxProvider>
|
||||
</QueryClientProvider>
|
||||
</CompatRouter>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('View modal, PromQL panels', () => {
|
||||
it('shows the opened panel query, not the previously viewed one', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0, delay: null });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-a'));
|
||||
expect(screen.getByTestId('promql-query-input')).toHaveValue(
|
||||
'up{job="alpha"}',
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('close'));
|
||||
await user.click(screen.getByTestId('open-b'));
|
||||
expect(screen.getByTestId('promql-query-input')).toHaveValue(
|
||||
'up{job="bravo"}',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,285 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
import { MemoryRouter, useLocation } from 'react-router-dom';
|
||||
import { CompatRouter } from 'react-router-dom-v5-compat';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { fromPerses } from 'pages/DashboardPageV2/DashboardContainer/queryV5/persesQueryAdapters';
|
||||
import { QueryBuilderProvider } from 'providers/QueryBuilder';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { useViewPanelMode } from '../ViewPanelModal/useViewPanelMode';
|
||||
import { useViewPanel } from '../hooks/useViewPanel';
|
||||
|
||||
// jest.config maps the real hook to a no-op mock; this suite needs real navigation.
|
||||
jest.mock('hooks/useSafeNavigate', () => {
|
||||
const { useHistory } = jest.requireActual('react-router-dom');
|
||||
return {
|
||||
useSafeNavigate: (): unknown => {
|
||||
const history = useHistory();
|
||||
return {
|
||||
safeNavigate: (to: string, opts?: { replace?: boolean }): void => {
|
||||
if (opts?.replace) {
|
||||
history.replace(to);
|
||||
} else {
|
||||
history.push(to);
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/hooks/usePanelQuery',
|
||||
() => ({
|
||||
usePanelQuery: (): unknown => ({
|
||||
data: undefined,
|
||||
isFetching: false,
|
||||
isPreviousData: false,
|
||||
error: null,
|
||||
refetch: jest.fn(),
|
||||
cancelQuery: jest.fn(),
|
||||
pagination: undefined,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
|
||||
jest.mock(
|
||||
'pages/DashboardPageV2/DashboardContainer/store/useDashboardStore',
|
||||
() => ({
|
||||
useDashboardStore: (selector: (s: unknown) => unknown): unknown =>
|
||||
selector({ dashboardId: 'dash-1' }),
|
||||
}),
|
||||
);
|
||||
|
||||
function makePanel(name: string, expression: string): DashboardtypesPanelDTO {
|
||||
return {
|
||||
kind: 'Panel',
|
||||
spec: {
|
||||
display: { name },
|
||||
plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },
|
||||
queries: [
|
||||
{
|
||||
kind: 'time_series',
|
||||
spec: {
|
||||
plugin: {
|
||||
kind: 'signoz/BuilderQuery',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'logs',
|
||||
disabled: false,
|
||||
filter: { expression },
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
const PANELS: Record<string, DashboardtypesPanelDTO> = {
|
||||
A: makePanel('Panel A', "service = 'alpha'"),
|
||||
B: makePanel('Panel B', "service = 'bravo'"),
|
||||
};
|
||||
|
||||
const panelOf = (json: string): string => {
|
||||
if (json.includes('alpha')) {
|
||||
return 'A';
|
||||
}
|
||||
if (json.includes('bravo')) {
|
||||
return 'B';
|
||||
}
|
||||
return 'none';
|
||||
};
|
||||
|
||||
/** Every render of the open modal, so a single stale frame can't hide. */
|
||||
const renders: { current: string; draft: string; filterItems: number }[] = [];
|
||||
|
||||
const stagedIds: (string | undefined)[] = [];
|
||||
|
||||
function ModalBody({ panelId }: { panelId: string }): JSX.Element {
|
||||
const { currentQuery } = useQueryBuilder();
|
||||
const { draft } = useViewPanelMode({
|
||||
panel: PANELS[panelId],
|
||||
panelId,
|
||||
time: { startMs: 0, endMs: 1000 },
|
||||
});
|
||||
renders.push({
|
||||
current: panelOf(JSON.stringify(currentQuery)),
|
||||
draft: panelOf(JSON.stringify(draft.spec.queries)),
|
||||
filterItems: currentQuery.builder.queryData[0]?.filters?.items.length ?? 0,
|
||||
});
|
||||
return <div data-testid="modal-body" />;
|
||||
}
|
||||
|
||||
function SearchProbe(): JSX.Element {
|
||||
return <div data-testid="search">{useLocation().search}</div>;
|
||||
}
|
||||
|
||||
function StagedQueryProbe(): null {
|
||||
const { stagedQuery } = useQueryBuilder();
|
||||
if (stagedIds.at(-1) !== stagedQuery?.id) {
|
||||
stagedIds.push(stagedQuery?.id);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const drilldownQuery = (base: Query): Query => ({
|
||||
...base,
|
||||
builder: {
|
||||
...base.builder,
|
||||
queryData: base.builder.queryData.map((q) => ({
|
||||
...q,
|
||||
filter: { expression: "service = 'bravo' AND host = 'h1'" },
|
||||
})),
|
||||
},
|
||||
});
|
||||
|
||||
function Harness(): JSX.Element {
|
||||
const { expandedPanelId, openView, openViewWithQuery, closeView } =
|
||||
useViewPanel();
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-a"
|
||||
onClick={(): void => openView('A', PANELS.A)}
|
||||
>
|
||||
open A
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="open-b"
|
||||
onClick={(): void => openView('B', PANELS.B)}
|
||||
>
|
||||
open B
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="drilldown-b"
|
||||
onClick={(): void =>
|
||||
openViewWithQuery(
|
||||
'B',
|
||||
drilldownQuery(
|
||||
fromPerses(PANELS.B.spec.queries, PANEL_TYPES.TIME_SERIES),
|
||||
),
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
)
|
||||
}
|
||||
>
|
||||
drilldown B
|
||||
</button>
|
||||
<button type="button" data-testid="close" onClick={closeView}>
|
||||
close
|
||||
</button>
|
||||
<StagedQueryProbe />
|
||||
<SearchProbe />
|
||||
{expandedPanelId && <ModalBody panelId={expandedPanelId} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const renderHarness = (): void => {
|
||||
render(
|
||||
<MemoryRouter initialEntries={['/dashboard/dash-1']}>
|
||||
<CompatRouter>
|
||||
<QueryBuilderProvider>
|
||||
<Harness />
|
||||
</QueryBuilderProvider>
|
||||
</CompatRouter>
|
||||
</MemoryRouter>,
|
||||
);
|
||||
};
|
||||
|
||||
describe('useViewPanel', () => {
|
||||
beforeEach(() => {
|
||||
renders.length = 0;
|
||||
stagedIds.length = 0;
|
||||
});
|
||||
|
||||
// The builder context is global and outlives the modal; its fields seed themselves
|
||||
// on mount, so a late swap leaves them on the previously-viewed panel.
|
||||
it('seeds the builder with the opened panel before the modal renders', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-a'));
|
||||
await user.click(screen.getByTestId('close'));
|
||||
|
||||
renders.length = 0;
|
||||
await user.click(screen.getByTestId('open-b'));
|
||||
|
||||
expect(renders.length).toBeGreaterThan(0);
|
||||
expect(renders.every((r) => r.current === 'B')).toBe(true);
|
||||
});
|
||||
|
||||
it("carries the opened panel's query in the URL", async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-b'));
|
||||
|
||||
const search = new URLSearchParams(
|
||||
screen.getByTestId('search').textContent ?? '',
|
||||
);
|
||||
expect(search.get(QueryParams.expandedWidgetId)).toBe('B');
|
||||
const carried = search.get(QueryParams.compositeQuery);
|
||||
expect(panelOf(decodeURIComponent(carried as string))).toBe('B');
|
||||
expect(search.get(QueryParams.graphType)).toBeNull();
|
||||
});
|
||||
|
||||
// The edit session commits any staged query on mount, so a staged query left over
|
||||
// from the previous panel would make this panel's preview fetch the old query.
|
||||
it('never lets the previous panel query reach the new panel draft', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-a'));
|
||||
await user.click(screen.getByTestId('close'));
|
||||
|
||||
renders.length = 0;
|
||||
await user.click(screen.getByTestId('open-b'));
|
||||
|
||||
expect(renders.every((r) => r.draft === 'B')).toBe(true);
|
||||
});
|
||||
|
||||
// The drilldown URL carries the query's own id, so a staged query with that id makes
|
||||
// the provider skip hydration — losing the normalisation that fills `filters.items`.
|
||||
it('still lets the provider hydrate a drilldown query from the URL', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-a'));
|
||||
await user.click(screen.getByTestId('close'));
|
||||
|
||||
renders.length = 0;
|
||||
await user.click(screen.getByTestId('drilldown-b'));
|
||||
|
||||
expect(renders.every((r) => r.current === 'B')).toBe(true);
|
||||
expect(renders.at(-1)?.filterItems).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
// `useSyncTimeOnStagedQueryChange` (dashboard toolbar) re-anchors global time when one
|
||||
// non-null staged id replaces another, refetching every panel behind the modal.
|
||||
it.each([['open-b'], ['drilldown-b']])(
|
||||
'never swaps one staged query for another (%s)',
|
||||
async (trigger) => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
renderHarness();
|
||||
|
||||
await user.click(screen.getByTestId('open-a'));
|
||||
await user.click(screen.getByTestId('close'));
|
||||
await user.click(screen.getByTestId(trigger));
|
||||
|
||||
const swapsWithoutNull = stagedIds.some(
|
||||
(id, i) => i > 0 && id !== undefined && stagedIds[i - 1] !== undefined,
|
||||
);
|
||||
expect(swapsWithoutNull).toBe(false);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -1,11 +1,14 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useLocation } from 'react-router-dom';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import type { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
import useUrlQuery from 'hooks/useUrlQuery';
|
||||
import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';
|
||||
import { getPanelBuilderQuery } from 'pages/DashboardPageV2/DashboardContainer/Panels/utils/getPanelBuilderQuery';
|
||||
import type { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { clearViewPanelHandoff } from '../ViewPanelModal/viewPanelHandoffStore';
|
||||
@@ -13,8 +16,8 @@ import { clearViewPanelHandoff } from '../ViewPanelModal/viewPanelHandoffStore';
|
||||
export interface UseViewPanelApi {
|
||||
/** Panel id currently expanded in the View modal; null when none is open. */
|
||||
expandedPanelId: string | null;
|
||||
/** Open the View modal on the saved panel (clears any leftover in-modal query/kind). */
|
||||
openView: (panelId: string) => void;
|
||||
/** Open the View modal on the saved panel, its query carried in `compositeQuery`. */
|
||||
openView: (panelId: string, panel: DashboardtypesPanelDTO) => void;
|
||||
/**
|
||||
* Open the View modal pre-seeded with a drilldown query + kind, persisted in the URL so it
|
||||
* survives refresh (V1 parity); the modal hydrates its draft from these on mount.
|
||||
@@ -30,30 +33,38 @@ export interface UseViewPanelApi {
|
||||
|
||||
/**
|
||||
* Drives the panel View modal off the URL (V1 parity): `expandedWidgetId` holds the open
|
||||
* panel, and a drilldown additionally seeds `compositeQuery` + `graphType`. URL-backed state
|
||||
* is shareable, survives refresh, and the browser back-button closes it.
|
||||
* panel and `compositeQuery` the query it opens on, which a drilldown retargets along with
|
||||
* `graphType`. URL-backed state is shareable, survives refresh, and browser Back closes it.
|
||||
*/
|
||||
export function useViewPanel(): UseViewPanelApi {
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const { pathname } = useLocation();
|
||||
const urlQuery = useUrlQuery();
|
||||
const { resetQuery } = useQueryBuilder();
|
||||
|
||||
const expandedPanelId = urlQuery.get(QueryParams.expandedWidgetId);
|
||||
|
||||
const openView = useCallback(
|
||||
(panelId: string): void => {
|
||||
(panelId: string, panel: DashboardtypesPanelDTO): void => {
|
||||
// Copy before mutating: useUrlQuery returns a memoized instance.
|
||||
const next = new URLSearchParams(urlQuery);
|
||||
next.set(QueryParams.expandedWidgetId, panelId);
|
||||
// Drop leftover in-modal query/kind + the editor's handoff so a plain View opens
|
||||
// on the saved panel, not stale state the modal would otherwise hydrate from.
|
||||
next.delete(QueryParams.compositeQuery);
|
||||
// Only a drilldown retargets the panel type.
|
||||
next.delete(QueryParams.graphType);
|
||||
clearViewPanelHandoff();
|
||||
const query = getPanelBuilderQuery(panel);
|
||||
next.set(
|
||||
QueryParams.compositeQuery,
|
||||
encodeURIComponent(JSON.stringify(query)),
|
||||
);
|
||||
// The provider applies the URL in an effect, a tick after the builder's fields have
|
||||
// mounted and read the query they keep. `resetQuery` — not `initQueryBuilderData`:
|
||||
// swapping one staged id for another re-anchors global time and refetches the grid.
|
||||
resetQuery(query);
|
||||
void logEvent(DashboardDetailEvents.PanelViewed, { panelId });
|
||||
safeNavigate(`${pathname}?${next.toString()}`);
|
||||
},
|
||||
[pathname, safeNavigate, urlQuery],
|
||||
[pathname, safeNavigate, urlQuery, resetQuery],
|
||||
);
|
||||
|
||||
const openViewWithQuery = useCallback(
|
||||
@@ -63,6 +74,10 @@ export function useViewPanel(): UseViewPanelApi {
|
||||
next.set(QueryParams.graphType, panelType);
|
||||
// A grid drilldown opens on the saved panel, never a stale editor handoff.
|
||||
clearViewPanelHandoff();
|
||||
// As in `openView`. Clearing the staged query matters twice over here: the URL
|
||||
// below carries this query's own id, and a staged query with a matching id
|
||||
// makes the provider skip the hydration that normalises legacy filter fields.
|
||||
resetQuery(query);
|
||||
// Same encoding the query builder uses (see `useGetCompositeQueryParam`): the URL
|
||||
// value is `encodeURIComponent(JSON.stringify(query))`, decoded once on read.
|
||||
next.set(
|
||||
@@ -71,7 +86,7 @@ export function useViewPanel(): UseViewPanelApi {
|
||||
);
|
||||
safeNavigate(`${pathname}?${next.toString()}`);
|
||||
},
|
||||
[pathname, safeNavigate, urlQuery],
|
||||
[pathname, safeNavigate, urlQuery, resetQuery],
|
||||
);
|
||||
|
||||
const closeView = useCallback((): void => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import { TOOLTIP_SCROLL_CONTENT_CLASS } from 'components/TooltipScrollArea/Toolt
|
||||
|
||||
import HiddenVariablesTooltip from './components/HiddenVariablesTooltip/HiddenVariablesTooltip';
|
||||
import { useVariableSelection } from './hooks/useVariableSelection';
|
||||
import { resolveDefaultSelection } from './utils/resolveVariableSelection';
|
||||
import VariableSelector from './components/VariableSelector/VariableSelector';
|
||||
import styles from './VariablesBar.module.scss';
|
||||
|
||||
@@ -96,12 +97,10 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
|
||||
variable={variable}
|
||||
variables={variables}
|
||||
selections={selection}
|
||||
selection={
|
||||
selection[variable.name] ?? {
|
||||
value: variable.multiSelect ? [] : '',
|
||||
allSelected: false,
|
||||
}
|
||||
}
|
||||
// Until the seed commits a selection, stand in the same default it will
|
||||
// commit, through the one resolver — an empty stand-in reads as "nothing
|
||||
// selected" to a control that snapshots it on mount.
|
||||
selection={selection[variable.name] ?? resolveDefaultSelection(variable)}
|
||||
onChange={(next): void => setSelection(variable.name, next)}
|
||||
onAutoSelect={(next): void => autoSelect(variable.name, next)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import userEvent from '@testing-library/user-event';
|
||||
|
||||
import type { VariableSelection } from '../selectionTypes';
|
||||
import TextSelector from '../components/selectors/TextSelector';
|
||||
|
||||
jest.mock('api/common/logEvent', () => ({
|
||||
__esModule: true,
|
||||
default: jest.fn(),
|
||||
}));
|
||||
|
||||
function renderSelector(
|
||||
selection: VariableSelection,
|
||||
onChange = jest.fn(),
|
||||
): { rerender: (selection: VariableSelection) => void; onChange: jest.Mock } {
|
||||
const { rerender } = render(
|
||||
<TextSelector
|
||||
selection={selection}
|
||||
defaultValue="flower"
|
||||
onChange={onChange}
|
||||
testId="variable-input-service"
|
||||
/>,
|
||||
);
|
||||
return {
|
||||
onChange,
|
||||
rerender: (next): void =>
|
||||
rerender(
|
||||
<TextSelector
|
||||
selection={next}
|
||||
defaultValue="flower"
|
||||
onChange={onChange}
|
||||
testId="variable-input-service"
|
||||
/>,
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function input(): HTMLInputElement {
|
||||
return screen.getByTestId('variable-input-service') as HTMLInputElement;
|
||||
}
|
||||
|
||||
describe('TextSelector', () => {
|
||||
it('shows the value the seed commits after mount', () => {
|
||||
// The bar mounts before the seed resolves the definition's default, so the first
|
||||
// render sees nothing selected. The box must follow the value once it lands.
|
||||
const { rerender } = renderSelector({ value: '', allSelected: false });
|
||||
|
||||
rerender({ value: 'flower', allSelected: false });
|
||||
|
||||
expect(input().value).toBe('flower');
|
||||
});
|
||||
|
||||
it('follows a selection replaced from outside (share link, reset)', () => {
|
||||
const { rerender } = renderSelector({ value: 'flower', allSelected: false });
|
||||
|
||||
rerender({ value: 'rose', allSelected: false });
|
||||
|
||||
expect(input().value).toBe('rose');
|
||||
});
|
||||
|
||||
it('keeps what the user types until they commit it', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { onChange } = renderSelector({ value: 'flower', allSelected: false });
|
||||
|
||||
await user.clear(input());
|
||||
await user.type(input(), 'tulip');
|
||||
|
||||
// Still local — a keystroke must not cascade to dependent panels.
|
||||
expect(input().value).toBe('tulip');
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
|
||||
await user.tab();
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
value: 'tulip',
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('restores the default when emptied', async () => {
|
||||
const user = userEvent.setup();
|
||||
const { onChange } = renderSelector({ value: 'tulip', allSelected: false });
|
||||
|
||||
await user.clear(input());
|
||||
await user.tab();
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
value: 'flower',
|
||||
allSelected: false,
|
||||
});
|
||||
expect(input().value).toBe('flower');
|
||||
});
|
||||
});
|
||||
@@ -87,4 +87,99 @@ describe('ValueSelector', () => {
|
||||
|
||||
expect(screen.getByText('ALL')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
describe('an ALL selection whose options are still loading', () => {
|
||||
it('reads ALL, not the "Select value" placeholder', () => {
|
||||
// Options arrive after the selection is known (first fetch, or a dynamic ALL,
|
||||
// which carries no values at all) — the control must not read as unselected.
|
||||
renderSelector({ value: null, allSelected: true }, [], true);
|
||||
|
||||
expect(
|
||||
document.querySelector('.ant-select-selection-placeholder'),
|
||||
).toHaveTextContent('ALL');
|
||||
});
|
||||
|
||||
it('still shows concrete values while options load', () => {
|
||||
renderSelector(
|
||||
{ value: ['checkout-service-prod'], allSelected: false },
|
||||
[],
|
||||
true,
|
||||
);
|
||||
|
||||
expect(
|
||||
document.querySelector('.ant-select-selection-placeholder'),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearing', () => {
|
||||
function clearIcon(): Element | null {
|
||||
return document.querySelector('.ant-select-clear');
|
||||
}
|
||||
|
||||
async function openDropdown(): Promise<void> {
|
||||
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
|
||||
const control = screen.getByTestId('variable-select-env');
|
||||
await user.click(control.querySelector('input') as HTMLInputElement);
|
||||
}
|
||||
|
||||
it('offers no clear icon while the list is closed', () => {
|
||||
renderSelector({ value: VALUES, allSelected: false }, OPTIONS);
|
||||
|
||||
expect(clearIcon()).toBeNull();
|
||||
});
|
||||
|
||||
it('offers it once the list is open', async () => {
|
||||
renderSelector({ value: VALUES, allSelected: false }, OPTIONS);
|
||||
|
||||
await openDropdown();
|
||||
|
||||
expect(clearIcon()).not.toBeNull();
|
||||
});
|
||||
|
||||
it('offers no clear icon while every option is selected', async () => {
|
||||
// ALL is every option, so there is nothing to clear — and the shared control
|
||||
// refuses to empty an ALL selection, which would leave the icon inert.
|
||||
renderSelector({ value: OPTIONS, allSelected: true }, OPTIONS);
|
||||
|
||||
await openDropdown();
|
||||
|
||||
expect(clearIcon()).toBeNull();
|
||||
});
|
||||
|
||||
it('empties the list and commits nothing until it closes', async () => {
|
||||
const onChange = jest.fn();
|
||||
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
|
||||
render(
|
||||
<TooltipProvider>
|
||||
<ValueSelector
|
||||
options={OPTIONS}
|
||||
variableType="query"
|
||||
multiSelect
|
||||
showAllOption
|
||||
selection={{ value: VALUES, allSelected: false }}
|
||||
onChange={onChange}
|
||||
emptyFallback={{ value: [OPTIONS[0]], allSelected: false }}
|
||||
testId="variable-select-env"
|
||||
/>
|
||||
</TooltipProvider>,
|
||||
);
|
||||
|
||||
await openDropdown();
|
||||
await user.click(clearIcon() as Element);
|
||||
|
||||
expect(document.querySelectorAll('.ant-select-selection-item')).toHaveLength(
|
||||
0,
|
||||
);
|
||||
expect(onChange).not.toHaveBeenCalled();
|
||||
|
||||
// Closing fills in whatever the variable should hold.
|
||||
await user.keyboard('{Escape}');
|
||||
|
||||
expect(onChange).toHaveBeenCalledWith({
|
||||
value: [OPTIONS[0]],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -61,6 +61,47 @@ describe('useAutoSelect', () => {
|
||||
expect(next).toBeUndefined();
|
||||
});
|
||||
|
||||
it('selects ALL for an ALL-enabled multi-select with nothing selected', () => {
|
||||
const next = run(
|
||||
model({ type: 'QUERY', multiSelect: true, showAllOption: true }),
|
||||
['a', 'b'],
|
||||
{ value: [], allSelected: false },
|
||||
);
|
||||
expect(next).toStrictEqual({ value: ['a', 'b'], allSelected: true });
|
||||
});
|
||||
|
||||
it('falls back to ALL, not the first option, when every selected value is gone', () => {
|
||||
const next = run(
|
||||
model({ type: 'QUERY', multiSelect: true, showAllOption: true }),
|
||||
['x', 'y'],
|
||||
{ value: ['a', 'b'], allSelected: false },
|
||||
);
|
||||
expect(next).toStrictEqual({ value: ['x', 'y'], allSelected: true });
|
||||
});
|
||||
|
||||
it('selects the ALL sentinel for an empty ALL-enabled dynamic multi-select', () => {
|
||||
const next = run(
|
||||
model({ type: 'DYNAMIC', multiSelect: true, showAllOption: true }),
|
||||
['a', 'b'],
|
||||
{ value: [], allSelected: false },
|
||||
);
|
||||
expect(next).toStrictEqual({ value: null, allSelected: true });
|
||||
});
|
||||
|
||||
it('still honours a configured default over ALL', () => {
|
||||
const next = run(
|
||||
model({
|
||||
type: 'QUERY',
|
||||
multiSelect: true,
|
||||
showAllOption: true,
|
||||
defaultValue: 'b',
|
||||
}),
|
||||
['a', 'b'],
|
||||
{ value: [], allSelected: false },
|
||||
);
|
||||
expect(next).toStrictEqual({ value: ['b'], allSelected: false });
|
||||
});
|
||||
|
||||
it('keeps the still-valid subset of a multi-select when options re-scope', () => {
|
||||
const next = run(
|
||||
model({ type: 'QUERY', multiSelect: true }),
|
||||
|
||||
@@ -97,6 +97,125 @@ describe('useSeedVariableSelection', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('prefers the configured default over a stored empty text value', () => {
|
||||
// Persisted from a session where the box was never filled — the default the
|
||||
// definition carries must win, or the variable reads as unset forever.
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setVariableValues('d1', { env: { value: '', allSelected: false } });
|
||||
const dash = dashboard('d1', [
|
||||
model({ name: 'env', type: 'TEXT', textValue: 'prod' }),
|
||||
]);
|
||||
|
||||
renderHook(() => useSeedVariableSelection(dash));
|
||||
|
||||
expect(seededValue('d1', 'env')).toStrictEqual({
|
||||
value: 'prod',
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('defaults an ALL-enabled multi-select to ALL over a stored empty array', () => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setVariableValues('d1', { env: { value: [], allSelected: false } });
|
||||
const dash = dashboard('d1', [
|
||||
model({
|
||||
name: 'env',
|
||||
type: 'CUSTOM',
|
||||
customValue: 'a,b',
|
||||
multiSelect: true,
|
||||
showAllOption: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
renderHook(() => useSeedVariableSelection(dash));
|
||||
|
||||
// Custom options need no request, so ALL is materialized here rather than left as
|
||||
// a flag for the post-fetch reconcile to expand.
|
||||
expect(seededValue('d1', 'env')).toStrictEqual({
|
||||
value: ['a', 'b'],
|
||||
allSelected: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('materializes ALL for a custom variable so nothing has to reconcile it later', () => {
|
||||
const dash = dashboard('d1', [
|
||||
model({
|
||||
name: 'env',
|
||||
type: 'CUSTOM',
|
||||
customValue: 'a,b,c',
|
||||
multiSelect: true,
|
||||
showAllOption: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
renderHook(() => useSeedVariableSelection(dash));
|
||||
|
||||
expect(seededValue('d1', 'env')).toStrictEqual({
|
||||
value: ['a', 'b', 'c'],
|
||||
allSelected: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('drops values a custom variable no longer offers, at seed time', () => {
|
||||
useDashboardStore.getState().setVariableValues('d1', {
|
||||
env: { value: ['a', 'gone'], allSelected: false },
|
||||
});
|
||||
const dash = dashboard('d1', [
|
||||
model({
|
||||
name: 'env',
|
||||
type: 'CUSTOM',
|
||||
customValue: 'a,b',
|
||||
multiSelect: true,
|
||||
}),
|
||||
]);
|
||||
|
||||
renderHook(() => useSeedVariableSelection(dash));
|
||||
|
||||
expect(seededValue('d1', 'env')).toStrictEqual({
|
||||
value: ['a'],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps a stored ALL selection that has not materialized yet', () => {
|
||||
useDashboardStore
|
||||
.getState()
|
||||
.setVariableValues('d1', { env: { value: null, allSelected: true } });
|
||||
const dash = dashboard('d1', [
|
||||
model({
|
||||
name: 'env',
|
||||
type: 'QUERY',
|
||||
multiSelect: true,
|
||||
showAllOption: true,
|
||||
defaultValue: 'b',
|
||||
}),
|
||||
]);
|
||||
|
||||
renderHook(() => useSeedVariableSelection(dash));
|
||||
|
||||
expect(seededValue('d1', 'env')).toStrictEqual({
|
||||
value: null,
|
||||
allSelected: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not rewrite the store when the effect re-runs with the same values', () => {
|
||||
// A dashboard refetch or any spec edit hands back an equal-but-new variables array,
|
||||
// re-running the seed. Writing an identical map would re-render every subscriber.
|
||||
const variable = model({ name: 'env', type: 'TEXT', textValue: 'prod' });
|
||||
const { rerender } = renderHook(
|
||||
({ dash }) => useSeedVariableSelection(dash),
|
||||
{ initialProps: { dash: dashboard('d1', [variable]) } },
|
||||
);
|
||||
const afterSeed = useDashboardStore.getState().variableValues;
|
||||
|
||||
rerender({ dash: dashboard('d1', [{ ...variable }]) });
|
||||
|
||||
expect(useDashboardStore.getState().variableValues).toBe(afterSeed);
|
||||
});
|
||||
|
||||
it('initializes the fetch context with idle states for every variable', () => {
|
||||
const dash = dashboard('d1', [
|
||||
model({ name: 'env', type: 'TEXT' }),
|
||||
|
||||
@@ -0,0 +1,152 @@
|
||||
import { act, renderHook } from '@testing-library/react';
|
||||
import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';
|
||||
|
||||
import {
|
||||
emptyVariableFormModel,
|
||||
type VariableFormModel,
|
||||
} from '../../DashboardSettings/Variables/variableFormModel';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { useVariableSelection } from '../hooks/useVariableSelection';
|
||||
|
||||
jest.mock('nuqs', () => ({
|
||||
parseAsJson: (): unknown => ({ withOptions: (): unknown => ({}) }),
|
||||
useQueryState: (): unknown => [null, jest.fn()],
|
||||
}));
|
||||
|
||||
jest.mock('react-redux', () => ({
|
||||
useSelector: (selector: (state: unknown) => unknown): unknown =>
|
||||
selector({
|
||||
globalTime: { minTime: 1, maxTime: 2, selectedTime: '5m' },
|
||||
}),
|
||||
}));
|
||||
|
||||
jest.mock('../../DashboardSettings/Variables/variableAdapters', () => ({
|
||||
dtoToFormModel: (dto: unknown): unknown => dto,
|
||||
}));
|
||||
|
||||
function model(overrides: Partial<VariableFormModel>): VariableFormModel {
|
||||
return { ...emptyVariableFormModel(), ...overrides };
|
||||
}
|
||||
|
||||
// env → svc, so a cascade off `env` is observable as a cycle bump on `svc`.
|
||||
const env = model({
|
||||
name: 'env',
|
||||
type: 'QUERY',
|
||||
multiSelect: true,
|
||||
queryValue: 'SELECT env',
|
||||
});
|
||||
const svc = model({
|
||||
name: 'svc',
|
||||
type: 'QUERY',
|
||||
queryValue: 'SELECT svc WHERE env = $env',
|
||||
});
|
||||
|
||||
const dashboard = {
|
||||
id: 'd1',
|
||||
spec: { variables: [env, svc] },
|
||||
} as unknown as DashboardtypesGettableDashboardV2DTO;
|
||||
|
||||
function svcCycleId(): number {
|
||||
return useDashboardStore.getState().variableCycleIds.svc ?? 0;
|
||||
}
|
||||
|
||||
describe('useVariableSelection — setSelection', () => {
|
||||
beforeEach(() => {
|
||||
useDashboardStore.setState({
|
||||
variableValues: {},
|
||||
variableFetchStates: {},
|
||||
variableLastUpdated: {},
|
||||
variableCycleIds: {},
|
||||
variableResolvedEmpty: {},
|
||||
variableFetchContext: null,
|
||||
lastFetchAllKey: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not re-cascade when the picked value is the one already held', () => {
|
||||
const { result } = renderHook(() => useVariableSelection(dashboard));
|
||||
|
||||
act(() => {
|
||||
result.current.setSelection('env', {
|
||||
value: ['a', 'b'],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
const afterFirstPick = svcCycleId();
|
||||
|
||||
// Same values, then the same set in a different order: neither is a change, so
|
||||
// the dependent must not be re-fetched.
|
||||
act(() => {
|
||||
result.current.setSelection('env', {
|
||||
value: ['a', 'b'],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
act(() => {
|
||||
result.current.setSelection('env', {
|
||||
value: ['b', 'a'],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
|
||||
expect(svcCycleId()).toBe(afterFirstPick);
|
||||
});
|
||||
|
||||
it('ignores an auto-fill that the store already satisfies', async () => {
|
||||
const { result } = renderHook(() => useVariableSelection(dashboard));
|
||||
act(() => {
|
||||
result.current.setSelection('env', { value: ['a'], allSelected: false });
|
||||
});
|
||||
const before = svcCycleId();
|
||||
|
||||
// What a selector's first-render reconcile produces before the seed commits: a
|
||||
// value the store then resolves to on its own.
|
||||
await act(async () => {
|
||||
result.current.autoSelect('env', { value: ['a'], allSelected: false });
|
||||
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
|
||||
});
|
||||
|
||||
expect(svcCycleId()).toBe(before);
|
||||
});
|
||||
|
||||
it('still applies an auto-fill that changes the value', async () => {
|
||||
const { result } = renderHook(() => useVariableSelection(dashboard));
|
||||
act(() => {
|
||||
result.current.setSelection('env', { value: ['a'], allSelected: false });
|
||||
});
|
||||
const before = svcCycleId();
|
||||
|
||||
await act(async () => {
|
||||
result.current.autoSelect('env', { value: ['a', 'b'], allSelected: false });
|
||||
await new Promise((resolve) => requestAnimationFrame(() => resolve(null)));
|
||||
});
|
||||
|
||||
expect(useDashboardStore.getState().variableValues.d1?.env).toStrictEqual({
|
||||
value: ['a', 'b'],
|
||||
allSelected: false,
|
||||
});
|
||||
expect(svcCycleId()).toBe(before + 1);
|
||||
});
|
||||
|
||||
it('still cascades a genuine change', () => {
|
||||
const { result } = renderHook(() => useVariableSelection(dashboard));
|
||||
|
||||
act(() => {
|
||||
result.current.setSelection('env', { value: ['a'], allSelected: false });
|
||||
});
|
||||
const before = svcCycleId();
|
||||
|
||||
act(() => {
|
||||
result.current.setSelection('env', {
|
||||
value: ['a', 'c'],
|
||||
allSelected: false,
|
||||
});
|
||||
});
|
||||
|
||||
expect(useDashboardStore.getState().variableValues.d1?.env).toStrictEqual({
|
||||
value: ['a', 'c'],
|
||||
allSelected: false,
|
||||
});
|
||||
expect(svcCycleId()).toBe(before + 1);
|
||||
});
|
||||
});
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
VariableSelection,
|
||||
VariableSelectionMap,
|
||||
} from '../../selectionTypes';
|
||||
import { textDefault } from '../../utils/resolveVariableSelection';
|
||||
import { computeVariableDependencies } from '../../utils/variableDependencies';
|
||||
import TextSelector from '../selectors/TextSelector';
|
||||
import VariableValueControl from '../selectors/VariableValueControl';
|
||||
@@ -65,7 +66,7 @@ function VariableSelector({
|
||||
variable.type === 'TEXT' ? (
|
||||
<TextSelector
|
||||
selection={selection}
|
||||
defaultValue={variable.textValue}
|
||||
defaultValue={textDefault(variable)}
|
||||
onChange={onChange}
|
||||
testId={`variable-input-${variable.name}`}
|
||||
/>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import type { InputRef } from 'antd';
|
||||
// eslint-disable-next-line signoz/no-antd-components -- match V1 textbox behaviour (commit on blur/Enter, borderless)
|
||||
import { Input } from 'antd';
|
||||
@@ -31,6 +31,17 @@ function TextSelector({
|
||||
typeof selection.value === 'string' ? selection.value : (defaultValue ?? ''),
|
||||
);
|
||||
|
||||
// The committed value can land after this input mounts — the seed resolves the
|
||||
// definition's default one tick later, and a share link or a reset can replace it
|
||||
// at any point. Without following it the box would keep showing its first render
|
||||
// (empty, since nothing is seeded yet) until the user focused and blurred it.
|
||||
// Typing never touches the selection, so an edit in progress cannot be interrupted.
|
||||
useEffect(() => {
|
||||
setValue(
|
||||
typeof selection.value === 'string' ? selection.value : (defaultValue ?? ''),
|
||||
);
|
||||
}, [selection.value, defaultValue]);
|
||||
|
||||
const commit = useCallback(
|
||||
(next: string): void => {
|
||||
void logEvent(
|
||||
|
||||
@@ -54,11 +54,26 @@ function ValueSelector({
|
||||
[selection, options],
|
||||
);
|
||||
|
||||
// That "all" path needs the options, so an ALL selection whose options have not
|
||||
// arrived yet has nothing to render and the control would read "Select value"
|
||||
// while it spins — as if nothing were selected. Say ALL in that slot instead: the
|
||||
// selection is known, only its options are pending. Display only, so it can never
|
||||
// be committed as a value.
|
||||
const isAllPendingOptions = selection.allSelected && options.length === 0;
|
||||
|
||||
// Buffer edits while the dropdown is open; the committed selection is shown
|
||||
// when closed. This defers the dependent cascade to a single commit-on-close.
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [draft, setDraft] = useState<string[]>(committedValues);
|
||||
|
||||
// ALL is every option, so there is nothing to clear — and the shared control refuses
|
||||
// to empty an ALL selection anyway, which would leave the icon inert. Unchecking ALL
|
||||
// in the list is the way out of it.
|
||||
const draftIsAll =
|
||||
showAllOption &&
|
||||
options.length > 0 &&
|
||||
options.every((option) => draft.includes(option));
|
||||
|
||||
const commit = (values: string[]): void => {
|
||||
// CustomMultiSelect emits the full value set when ALL is picked.
|
||||
const isAll =
|
||||
@@ -94,8 +109,11 @@ function ValueSelector({
|
||||
errorMessage={errorMessage}
|
||||
onRetry={onRetry}
|
||||
showSearch
|
||||
allowClear
|
||||
placeholder="Select value"
|
||||
// Clearing belongs to the open list: on the closed control the icon would
|
||||
// appear on hover, in a row of variable pills, for an action whose result is
|
||||
// not visible.
|
||||
allowClear={isOpen && !draftIsAll}
|
||||
placeholder={isAllPendingOptions ? 'ALL' : 'Select value'}
|
||||
maxTagCount={1}
|
||||
maxTagTextLength={10}
|
||||
maxTagPlaceholder={(omitted): JSX.Element => (
|
||||
@@ -129,12 +147,10 @@ function ValueSelector({
|
||||
void logEvent(DashboardDetailEvents.VariableMultiSelectCleared, {
|
||||
variableType,
|
||||
});
|
||||
// Empties the list, committing nothing. Closing resolves an empty draft
|
||||
// to whatever the variable should hold — its configured default, else ALL
|
||||
// where it offers one, else the first option.
|
||||
setDraft([]);
|
||||
// A clear on the closed control falls back to the default immediately;
|
||||
// while open it just empties the draft (committed on close).
|
||||
if (!isOpen) {
|
||||
onChange(emptyFallback);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -6,7 +6,13 @@ import { dtoToFormModel } from '../../DashboardSettings/Variables/variableAdapte
|
||||
import type { VariableFormModel } from '../../DashboardSettings/Variables/variableFormModel';
|
||||
import { selectVariableValues } from '../../store/slices/variableSelectionSlice';
|
||||
import { useDashboardStore } from '../../store/useDashboardStore';
|
||||
import { resolveDefaultSelection } from '../utils/resolveVariableSelection';
|
||||
import { knownVariableOptions } from '../utils/knownVariableOptions';
|
||||
import {
|
||||
areSelectionsEqual,
|
||||
reconcileWithOptions,
|
||||
resolveDefaultSelection,
|
||||
} from '../utils/resolveVariableSelection';
|
||||
import { hasUsableValue } from '../utils/selectionUtils';
|
||||
import type {
|
||||
SelectedVariableValue,
|
||||
VariableSelection,
|
||||
@@ -18,6 +24,44 @@ import {
|
||||
} from '../utils/variableDependencies';
|
||||
import { ALL_SELECTED, variablesUrlParser } from '../utils/variablesUrlState';
|
||||
|
||||
function isStoredSelectionSet(
|
||||
stored: VariableSelection,
|
||||
model: VariableFormModel,
|
||||
): boolean {
|
||||
return !!stored.allSelected || hasUsableValue(stored, model.type);
|
||||
}
|
||||
|
||||
/** Whether the seeded map matches, entry for entry, what the store already holds. */
|
||||
function isSameSelection(
|
||||
seeded: VariableSelectionMap,
|
||||
current: VariableSelectionMap,
|
||||
): boolean {
|
||||
const names = Object.keys(seeded);
|
||||
return (
|
||||
names.length === Object.keys(current).length &&
|
||||
names.every(
|
||||
(name) => !!current[name] && areSelectionsEqual(seeded[name], current[name]),
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* A seeded value taken as far as it can go: for a variable whose options need no
|
||||
* request, resolve against them now — ALL becomes the concrete array, values the list
|
||||
* no longer offers are dropped. Left alone otherwise; the post-fetch reconcile does it
|
||||
* once the options arrive.
|
||||
*/
|
||||
function resolveAgainstKnownOptions(
|
||||
value: VariableSelection,
|
||||
model: VariableFormModel,
|
||||
): VariableSelection {
|
||||
const options = knownVariableOptions(model);
|
||||
if (options.length === 0) {
|
||||
return value;
|
||||
}
|
||||
return reconcileWithOptions(model, value, options) ?? value;
|
||||
}
|
||||
|
||||
// The `__ALL__` sentinel only means "ALL" for variables that support it — a
|
||||
// legitimate value of "__ALL__" (e.g. a text var) is taken literally.
|
||||
function fromUrlValue(
|
||||
@@ -70,22 +114,31 @@ export function useSeedVariableSelection(
|
||||
variables.forEach((variable) => {
|
||||
const urlValue = urlValues?.[variable.name];
|
||||
const stored = selection[variable.name];
|
||||
const seed = (value: VariableSelection): void => {
|
||||
seeded[variable.name] = resolveAgainstKnownOptions(value, variable);
|
||||
};
|
||||
if (urlValue !== undefined) {
|
||||
const fromUrl = fromUrlValue(urlValue, variable);
|
||||
// When the URL carries only the ALL sentinel but the store already holds
|
||||
// the materialized full-option array, reuse it — avoids the re-fetch +
|
||||
// re-materialize round-trip (and its dependent-refetch cascade) on load.
|
||||
seeded[variable.name] =
|
||||
seed(
|
||||
fromUrl.allSelected && stored?.allSelected && Array.isArray(stored.value)
|
||||
? stored
|
||||
: fromUrl;
|
||||
} else if (stored) {
|
||||
seeded[variable.name] = stored;
|
||||
: fromUrl,
|
||||
);
|
||||
} else if (stored && isStoredSelectionSet(stored, variable)) {
|
||||
seed(stored);
|
||||
} else {
|
||||
seeded[variable.name] = resolveDefaultSelection(variable);
|
||||
seed(resolveDefaultSelection(variable));
|
||||
}
|
||||
});
|
||||
setVariableValues(dashboardId, seeded);
|
||||
// This runs again whenever the spec's variable array changes identity — a refetch
|
||||
// or any spec edit — and writing an identical map would re-render every selection
|
||||
// subscriber for nothing.
|
||||
if (!isSameSelection(seeded, selection)) {
|
||||
setVariableValues(dashboardId, seeded);
|
||||
}
|
||||
|
||||
// Read-once: a share link's `?variables=` seeds the store, then the param is
|
||||
// dropped so the store is the sole source of truth. Selection changes never
|
||||
|
||||
@@ -1,14 +1,11 @@
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { commaValuesParser } from 'lib/dashboardVariables/customCommaValuesParser';
|
||||
import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';
|
||||
|
||||
import {
|
||||
sortValuesByOrder,
|
||||
VARIABLE_TYPE_EVENT_LABEL,
|
||||
} from '../../DashboardSettings/Variables/variableFormModel';
|
||||
import { VARIABLE_TYPE_EVENT_LABEL } from '../../DashboardSettings/Variables/variableFormModel';
|
||||
import type { VariableFormModel } from '../../DashboardSettings/Variables/variableFormModel';
|
||||
import type { VariableSelectionMap } from '../selectionTypes';
|
||||
import { knownVariableOptions } from '../utils/knownVariableOptions';
|
||||
import {
|
||||
useFetchedVariableOptions,
|
||||
type VariableOptions,
|
||||
@@ -30,14 +27,12 @@ export function useVariableOptions(
|
||||
): VariableOptions {
|
||||
const fetched = useFetchedVariableOptions(variable, variables, selections);
|
||||
|
||||
// Keyed on the fields the parse actually reads, not the model identity: a dashboard
|
||||
// refetch hands back an equal-but-new model, and a new options array would re-fire
|
||||
// the post-fetch reconcile for nothing.
|
||||
const customOptions = useMemo(
|
||||
() =>
|
||||
variable.type === 'CUSTOM'
|
||||
? sortValuesByOrder(
|
||||
commaValuesParser(variable.customValue),
|
||||
variable.sort,
|
||||
).map(String)
|
||||
: ([] as string[]),
|
||||
() => knownVariableOptions(variable),
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[variable.type, variable.customValue, variable.sort],
|
||||
);
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
VariableSelection,
|
||||
VariableSelectionMap,
|
||||
} from '../selectionTypes';
|
||||
import { areSelectionsEqual } from '../utils/resolveVariableSelection';
|
||||
import { useSeedVariableSelection } from './useSeedVariableSelection';
|
||||
|
||||
/**
|
||||
@@ -103,6 +104,10 @@ export function useVariableSelection(
|
||||
|
||||
const setSelection = useCallback(
|
||||
(name: string, next: VariableSelection): void => {
|
||||
const current = selectionRef.current[name];
|
||||
if (current && areSelectionsEqual(next, current)) {
|
||||
return;
|
||||
}
|
||||
setVariableValue(dashboardId, name, next);
|
||||
enqueueDescendants(name);
|
||||
},
|
||||
@@ -124,8 +129,19 @@ export function useVariableSelection(
|
||||
if (names.length === 0 || !dashboardId) {
|
||||
return;
|
||||
}
|
||||
setVariableValues(dashboardId, { ...selectionRef.current, ...fills });
|
||||
enqueueDescendantsBatch(names);
|
||||
// A fill can arrive already satisfied: a selector reconciles against the options
|
||||
// on its first render, before the seed has committed, and the seed then resolves
|
||||
// to the same value. Refresh only what actually moved, so a settled load ends
|
||||
// without a write or a dependent refetch.
|
||||
const current = selectionRef.current;
|
||||
const changed = names.filter(
|
||||
(name) => !current[name] || !areSelectionsEqual(fills[name], current[name]),
|
||||
);
|
||||
if (changed.length === 0) {
|
||||
return;
|
||||
}
|
||||
setVariableValues(dashboardId, { ...current, ...fills });
|
||||
enqueueDescendantsBatch(changed);
|
||||
}, [dashboardId, setVariableValues, enqueueDescendantsBatch]);
|
||||
|
||||
const autoSelect = useCallback(
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { commaValuesParser } from 'lib/dashboardVariables/customCommaValuesParser';
|
||||
|
||||
import { sortValuesByOrder } from '../../DashboardSettings/Variables/variableFormModel';
|
||||
import type { VariableFormModel } from '../../DashboardSettings/Variables/variableFormModel';
|
||||
|
||||
/**
|
||||
* The options of a variable whose list needs no request — a CUSTOM variable's comma
|
||||
* list. Empty for QUERY and DYNAMIC, whose options only exist once fetched, and for
|
||||
* TEXT, which has none.
|
||||
*
|
||||
* Knowing them up front lets the seed resolve such a variable's value completely
|
||||
* (materializing ALL, dropping values the list no longer offers) instead of leaving
|
||||
* that to the post-fetch reconcile, which would cost a second store write and a
|
||||
* refetch of everything downstream.
|
||||
*/
|
||||
export function knownVariableOptions(model: VariableFormModel): string[] {
|
||||
if (model.type !== 'CUSTOM') {
|
||||
return [];
|
||||
}
|
||||
return sortValuesByOrder(commaValuesParser(model.customValue), model.sort).map(
|
||||
String,
|
||||
);
|
||||
}
|
||||
@@ -37,7 +37,7 @@ function firstConfiguredDefault(model: VariableFormModel): string | undefined {
|
||||
}
|
||||
|
||||
/** A TEXT variable's default: its configured default, else its textValue (always a string). */
|
||||
function textDefault(model: VariableFormModel): string {
|
||||
export function textDefault(model: VariableFormModel): string {
|
||||
return firstConfiguredDefault(model) ?? model.textValue;
|
||||
}
|
||||
|
||||
@@ -53,15 +53,31 @@ function isAllDefault(
|
||||
);
|
||||
}
|
||||
|
||||
/** The configured default (or first option) as a fresh selection. */
|
||||
/**
|
||||
* The default selection for a variable with nothing usable selected: its configured
|
||||
* default, else ALL for an ALL-enabled multi-select, else the first option.
|
||||
*/
|
||||
function fillDefault(
|
||||
model: VariableFormModel,
|
||||
options: string[],
|
||||
): VariableSelection {
|
||||
const fallback = firstConfiguredDefault(model);
|
||||
const initial = fallback && options.includes(fallback) ? fallback : options[0];
|
||||
if (fallback && options.includes(fallback)) {
|
||||
return {
|
||||
value: model.multiSelect ? [fallback] : fallback,
|
||||
allSelected: false,
|
||||
};
|
||||
}
|
||||
|
||||
// No usable configured default: an ALL-enabled multi-select defaults to ALL, not
|
||||
// to an arbitrary first option — the same default the seed applies (keep in sync
|
||||
// with resolveDefaultSelection).
|
||||
if (model.multiSelect && model.showAllOption) {
|
||||
return materializeAll(model, options, null) ?? ALL_SELECTION;
|
||||
}
|
||||
|
||||
return {
|
||||
value: model.multiSelect ? [initial] : initial,
|
||||
value: model.multiSelect ? [options[0]] : options[0],
|
||||
allSelected: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { NANO_SECOND_MULTIPLIER } from 'store/globalTime';
|
||||
import { EQueryType } from 'types/common/dashboard';
|
||||
|
||||
import { useOpenPanelEditor } from '../useOpenPanelEditor';
|
||||
|
||||
@@ -81,6 +83,37 @@ describe('useOpenPanelEditor', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("carries the panel's saved query into the editor URL", () => {
|
||||
mockGlobalTime = { selectedTime: '6h', minTime: 0, maxTime: 0 };
|
||||
const panel = {
|
||||
kind: 'Panel',
|
||||
spec: {
|
||||
display: { name: 'Panel A' },
|
||||
plugin: { kind: 'signoz/TimeSeriesPanel', spec: {} },
|
||||
queries: [
|
||||
{
|
||||
kind: 'time_series',
|
||||
spec: {
|
||||
plugin: {
|
||||
kind: 'signoz/PromQLQuery',
|
||||
spec: { name: 'A', query: 'up{job="alpha"}', disabled: false },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
} as unknown as DashboardtypesPanelDTO;
|
||||
|
||||
const { result } = renderHook(() => useOpenPanelEditor());
|
||||
result.current('panel-9', { panel });
|
||||
|
||||
const [url] = mockSafeNavigate.mock.calls[0];
|
||||
const carried = new URLSearchParams(url.split('?')[1]).get('compositeQuery');
|
||||
const parsed = JSON.parse(decodeURIComponent(carried as string));
|
||||
expect(parsed.queryType).toBe(EQueryType.PROM);
|
||||
expect(parsed.promql[0].query).toBe('up{job="alpha"}');
|
||||
});
|
||||
|
||||
it('merges search with the time window (leading ? tolerated)', () => {
|
||||
mockGlobalTime = { selectedTime: '6h', minTime: 0, maxTime: 0 };
|
||||
const { result } = renderHook(() => useOpenPanelEditor());
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { useCallback } from 'react';
|
||||
import { generatePath } from 'react-router-dom';
|
||||
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { useSafeNavigate } from 'hooks/useSafeNavigate';
|
||||
|
||||
import type { PanelEditorHandoffState } from '../PanelEditor/panelEditorHandoff';
|
||||
import { getPanelBuilderQuery } from '../Panels/utils/getPanelBuilderQuery';
|
||||
import { useDashboardStore } from '../store/useDashboardStore';
|
||||
import { useTimeSearchParams } from './useTimeSearchParams';
|
||||
import logEvent from '@/api/common/logEvent';
|
||||
@@ -13,6 +17,8 @@ interface OpenPanelEditorOptions {
|
||||
handoffState?: PanelEditorHandoffState;
|
||||
/** Extra query merged into the editor URL (leading `?` optional). */
|
||||
search?: string;
|
||||
/** The panel being edited — its query rides in the URL as `compositeQuery`. */
|
||||
panel?: DashboardtypesPanelDTO;
|
||||
}
|
||||
|
||||
/** Opens the V2 panel editor, carrying the active time window in the URL. */
|
||||
@@ -23,6 +29,7 @@ export function useOpenPanelEditor(): (
|
||||
const { safeNavigate } = useSafeNavigate();
|
||||
const timeSearch = useTimeSearchParams();
|
||||
const dashboardId = useDashboardStore((s) => s.dashboardId);
|
||||
const { resetQuery } = useQueryBuilder();
|
||||
|
||||
return useCallback(
|
||||
(panelId: string, options?: OpenPanelEditorOptions): void => {
|
||||
@@ -39,12 +46,24 @@ export function useOpenPanelEditor(): (
|
||||
new URLSearchParams(timeSearch).forEach((value, key) => {
|
||||
params.set(key, value);
|
||||
});
|
||||
if (options?.panel) {
|
||||
const query = getPanelBuilderQuery(options.panel);
|
||||
// Single-encoded: `useGetCompositeQueryParam` decodes once on top of the decode
|
||||
// `URLSearchParams` already does.
|
||||
params.set(
|
||||
QueryParams.compositeQuery,
|
||||
encodeURIComponent(JSON.stringify(query)),
|
||||
);
|
||||
// The provider applies the URL in an effect, a tick after the builder's fields
|
||||
// have mounted and read the query they keep (PromQL inputs, add-on rows).
|
||||
resetQuery(query);
|
||||
}
|
||||
const search = params.toString();
|
||||
safeNavigate(
|
||||
search ? `${path}?${search}` : path,
|
||||
options?.handoffState ? { state: options.handoffState } : undefined,
|
||||
);
|
||||
},
|
||||
[safeNavigate, dashboardId, timeSearch],
|
||||
[safeNavigate, dashboardId, timeSearch, resetQuery],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AlertLabelsProps } from 'pages/AlertDetails/AlertHeader/AlertLabels/AlertLabels';
|
||||
import { RuletypesAlertStateDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { ICompositeMetricQuery } from 'types/api/alerts/compositeQuery';
|
||||
|
||||
// default match type for threshold
|
||||
@@ -73,10 +73,6 @@ export interface StatsTimeSeriesItem {
|
||||
value: string;
|
||||
}
|
||||
|
||||
export type AlertRuleStatsPayload = {
|
||||
data: AlertRuleStats;
|
||||
};
|
||||
|
||||
export interface AlertRuleTopContributors {
|
||||
fingerprint: number;
|
||||
labels: Labels;
|
||||
@@ -84,9 +80,6 @@ export interface AlertRuleTopContributors {
|
||||
relatedLogsLink: string;
|
||||
relatedTracesLink: string;
|
||||
}
|
||||
export type AlertRuleTopContributorsPayload = {
|
||||
data: AlertRuleTopContributors[];
|
||||
};
|
||||
|
||||
export interface AlertRuleTimelineTableResponse {
|
||||
ruleID: string;
|
||||
@@ -99,24 +92,12 @@ export interface AlertRuleTimelineTableResponse {
|
||||
labels: Labels;
|
||||
fingerprint: number;
|
||||
value: number;
|
||||
relatedTracesLink: string;
|
||||
relatedLogsLink: string;
|
||||
relatedLogsLink?: string;
|
||||
relatedTracesLink?: string;
|
||||
}
|
||||
export type AlertRuleTimelineTableResponsePayload = {
|
||||
data: {
|
||||
items: AlertRuleTimelineTableResponse[];
|
||||
total: number;
|
||||
labels: AlertLabelsProps['labels'];
|
||||
};
|
||||
};
|
||||
|
||||
type AlertState = 'firing' | 'normal' | 'nodata' | 'muted';
|
||||
|
||||
export interface AlertRuleTimelineGraphResponse {
|
||||
start: number;
|
||||
end: number;
|
||||
state: AlertState;
|
||||
state: RuletypesAlertStateDTO;
|
||||
}
|
||||
export type AlertRuleTimelineGraphResponsePayload = {
|
||||
data: AlertRuleTimelineGraphResponse[];
|
||||
};
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
import { AlertDef } from './def';
|
||||
|
||||
export interface RuleStatsProps {
|
||||
id: AlertDef['id'];
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { AlertDef } from './def';
|
||||
|
||||
export interface GetTimelineGraphRequestProps {
|
||||
id: AlertDef['id'];
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { TagFilter } from '../queryBuilder/queryBuilderData';
|
||||
import { AlertDef } from './def';
|
||||
|
||||
export interface GetTimelineTableRequestProps {
|
||||
id: AlertDef['id'];
|
||||
start: number;
|
||||
end: number;
|
||||
offset: number;
|
||||
limit: number;
|
||||
order: string;
|
||||
filters?: TagFilter;
|
||||
state?: string;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
import { AlertDef } from './def';
|
||||
|
||||
export interface TopContributorsProps {
|
||||
id: AlertDef['id'];
|
||||
start: number;
|
||||
end: number;
|
||||
}
|
||||
@@ -0,0 +1,956 @@
|
||||
{
|
||||
"schemaVersion": "v6",
|
||||
"image": "/assets/Logos/gcp-cloud-storage",
|
||||
"name": "",
|
||||
"generateName": true,
|
||||
"tags": [
|
||||
{
|
||||
"key": "tag",
|
||||
"value": "observability"
|
||||
}
|
||||
],
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "GCP Cloud Storage Overview",
|
||||
"description": "Dashboard for GCP Cloud Storage overview"
|
||||
},
|
||||
"variables": [
|
||||
{
|
||||
"kind": "ListVariable",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "project_id",
|
||||
"description": "GCP Project ID"
|
||||
},
|
||||
"allowAllValue": false,
|
||||
"allowMultiple": false,
|
||||
"customAllValue": "",
|
||||
"capturingRegexp": "",
|
||||
"sort": "none",
|
||||
"plugin": {
|
||||
"kind": "signoz/DynamicVariable",
|
||||
"spec": {
|
||||
"name": "project_id",
|
||||
"signal": "metrics"
|
||||
}
|
||||
},
|
||||
"name": "project_id"
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": "ListVariable",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "bucket_name",
|
||||
"description": "GCS bucket name"
|
||||
},
|
||||
"allowAllValue": true,
|
||||
"allowMultiple": true,
|
||||
"customAllValue": "",
|
||||
"capturingRegexp": "",
|
||||
"sort": "none",
|
||||
"plugin": {
|
||||
"kind": "signoz/DynamicVariable",
|
||||
"spec": {
|
||||
"name": "bucket_name",
|
||||
"signal": "metrics"
|
||||
}
|
||||
},
|
||||
"name": "bucket_name"
|
||||
}
|
||||
}
|
||||
],
|
||||
"panels": {
|
||||
"1f0a4d5b-6c2e-4a71-8b3d-9e5c07a41d20": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Bucket size",
|
||||
"description": "Total size of all objects in the bucket, grouped by storage class."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TablePanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time"
|
||||
},
|
||||
"formatting": {
|
||||
"columnUnits": {
|
||||
"A": "By"
|
||||
},
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "scalar",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/storage/v2/total_bytes",
|
||||
"temporality": "",
|
||||
"timeAggregation": "latest",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "last"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "storage_class",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "Size"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
},
|
||||
"29ed9824-21db-44c3-9537-12be458f5c20": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Total object bytes",
|
||||
"description": "Total size of all objects in the bucket, grouped by storage class and type."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TimeSeriesPanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time",
|
||||
"fillSpans": false
|
||||
},
|
||||
"formatting": {
|
||||
"unit": "By",
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"chartAppearance": {
|
||||
"lineInterpolation": "spline",
|
||||
"showPoints": false,
|
||||
"lineStyle": "solid",
|
||||
"fillMode": "none",
|
||||
"spanGaps": {
|
||||
"fillOnlyBelow": false,
|
||||
"fillLessThan": ""
|
||||
}
|
||||
},
|
||||
"axes": {
|
||||
"softMin": 0,
|
||||
"softMax": 0,
|
||||
"isLogScale": false
|
||||
},
|
||||
"legend": {
|
||||
"position": "right",
|
||||
"mode": "list",
|
||||
"customColors": null
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "time_series",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/storage/v2/total_bytes",
|
||||
"temporality": "",
|
||||
"timeAggregation": "latest",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "avg"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "storage_class",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "type",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "{{bucket_name}}/{{storage_class}}/{{type}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
},
|
||||
"cbc53174-5527-4bce-b32d-317403849e48": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Total object count",
|
||||
"description": "Total number of objects and multipart-uploads per bucket, grouped by storage class and type, where type can be live-object, noncurrent-object, soft-deleted-object or multipart-upload."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TimeSeriesPanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time",
|
||||
"fillSpans": false
|
||||
},
|
||||
"formatting": {
|
||||
"unit": "{count}",
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"chartAppearance": {
|
||||
"lineInterpolation": "spline",
|
||||
"showPoints": false,
|
||||
"lineStyle": "solid",
|
||||
"fillMode": "none",
|
||||
"spanGaps": {
|
||||
"fillOnlyBelow": false,
|
||||
"fillLessThan": ""
|
||||
}
|
||||
},
|
||||
"axes": {
|
||||
"softMin": 0,
|
||||
"softMax": 0,
|
||||
"isLogScale": false
|
||||
},
|
||||
"legend": {
|
||||
"position": "right",
|
||||
"mode": "list",
|
||||
"customColors": null
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "time_series",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/storage/v2/total_count",
|
||||
"temporality": "",
|
||||
"timeAggregation": "latest",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "avg"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "storage_class",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "type",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "{{bucket_name}}/{{storage_class}}/{{type}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
},
|
||||
"76e70ce5-47e4-4b5b-9715-49fa21c58b0c": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Deleted bytes",
|
||||
"description": "Rate of deleted bytes per bucket, grouped by storage class."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TimeSeriesPanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time",
|
||||
"fillSpans": false
|
||||
},
|
||||
"formatting": {
|
||||
"unit": "By/s",
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"chartAppearance": {
|
||||
"lineInterpolation": "spline",
|
||||
"showPoints": false,
|
||||
"lineStyle": "solid",
|
||||
"fillMode": "none",
|
||||
"spanGaps": {
|
||||
"fillOnlyBelow": false,
|
||||
"fillLessThan": ""
|
||||
}
|
||||
},
|
||||
"axes": {
|
||||
"softMin": 0,
|
||||
"softMax": 0,
|
||||
"isLogScale": false
|
||||
},
|
||||
"legend": {
|
||||
"position": "right",
|
||||
"mode": "list",
|
||||
"customColors": null
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "time_series",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/storage/v2/deleted_bytes",
|
||||
"temporality": "",
|
||||
"timeAggregation": "rate",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "sum"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "storage_class",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "{{bucket_name}}/{{storage_class}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
},
|
||||
"c5af2813-34ec-41a9-8d53-c9acd67f569f": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Request count",
|
||||
"description": "Rate of API calls, grouped by the API method name and response code."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TimeSeriesPanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time",
|
||||
"fillSpans": false
|
||||
},
|
||||
"formatting": {
|
||||
"unit": "{count}/s",
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"chartAppearance": {
|
||||
"lineInterpolation": "spline",
|
||||
"showPoints": false,
|
||||
"lineStyle": "solid",
|
||||
"fillMode": "none",
|
||||
"spanGaps": {
|
||||
"fillOnlyBelow": false,
|
||||
"fillLessThan": ""
|
||||
}
|
||||
},
|
||||
"axes": {
|
||||
"softMin": 0,
|
||||
"softMax": 0,
|
||||
"isLogScale": false
|
||||
},
|
||||
"legend": {
|
||||
"position": "right",
|
||||
"mode": "list",
|
||||
"customColors": null
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "time_series",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/api/request_count",
|
||||
"temporality": "",
|
||||
"timeAggregation": "rate",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "sum"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "method",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "response_code",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "{{bucket_name}}/{{method}} - {{response_code}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
},
|
||||
"70333210-68c3-4387-a6b7-afa2459d27dd": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Authentication count",
|
||||
"description": "Rate of HMAC/RSA signed requests, grouped by authentication method, API method name and response code."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TimeSeriesPanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time",
|
||||
"fillSpans": false
|
||||
},
|
||||
"formatting": {
|
||||
"unit": "{count}/s",
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"chartAppearance": {
|
||||
"lineInterpolation": "spline",
|
||||
"showPoints": false,
|
||||
"lineStyle": "solid",
|
||||
"fillMode": "none",
|
||||
"spanGaps": {
|
||||
"fillOnlyBelow": false,
|
||||
"fillLessThan": ""
|
||||
}
|
||||
},
|
||||
"axes": {
|
||||
"softMin": 0,
|
||||
"softMax": 0,
|
||||
"isLogScale": false
|
||||
},
|
||||
"legend": {
|
||||
"position": "right",
|
||||
"mode": "list",
|
||||
"customColors": null
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "time_series",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/authn/authentication_count",
|
||||
"temporality": "",
|
||||
"timeAggregation": "rate",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "sum"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "authentication_method",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "method",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "response_code",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "{{bucket_name}}/{{authentication_method}}/{{method}} - {{response_code}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
},
|
||||
"7a98084c-2cd3-4146-a831-f5382162ffe5": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Received bytes",
|
||||
"description": "Rate of bytes received over the network, grouped by the API method name and response code."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TimeSeriesPanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time",
|
||||
"fillSpans": false
|
||||
},
|
||||
"formatting": {
|
||||
"unit": "By/s",
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"chartAppearance": {
|
||||
"lineInterpolation": "spline",
|
||||
"showPoints": false,
|
||||
"lineStyle": "solid",
|
||||
"fillMode": "none",
|
||||
"spanGaps": {
|
||||
"fillOnlyBelow": false,
|
||||
"fillLessThan": ""
|
||||
}
|
||||
},
|
||||
"axes": {
|
||||
"softMin": 0,
|
||||
"softMax": 0,
|
||||
"isLogScale": false
|
||||
},
|
||||
"legend": {
|
||||
"position": "right",
|
||||
"mode": "list",
|
||||
"customColors": null
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "time_series",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/network/received_bytes_count",
|
||||
"temporality": "",
|
||||
"timeAggregation": "rate",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "sum"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "method",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "response_code",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "{{bucket_name}}/{{method}} - {{response_code}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
},
|
||||
"7138bf98-b41a-46d8-90ef-8e7470819cdf": {
|
||||
"kind": "Panel",
|
||||
"spec": {
|
||||
"display": {
|
||||
"name": "Sent bytes",
|
||||
"description": "Rate of bytes sent over the network, grouped by the API method name and response code."
|
||||
},
|
||||
"plugin": {
|
||||
"kind": "signoz/TimeSeriesPanel",
|
||||
"spec": {
|
||||
"visualization": {
|
||||
"timePreference": "global_time",
|
||||
"fillSpans": false
|
||||
},
|
||||
"formatting": {
|
||||
"unit": "By/s",
|
||||
"decimalPrecision": "2"
|
||||
},
|
||||
"chartAppearance": {
|
||||
"lineInterpolation": "spline",
|
||||
"showPoints": false,
|
||||
"lineStyle": "solid",
|
||||
"fillMode": "none",
|
||||
"spanGaps": {
|
||||
"fillOnlyBelow": false,
|
||||
"fillLessThan": ""
|
||||
}
|
||||
},
|
||||
"axes": {
|
||||
"softMin": 0,
|
||||
"softMax": 0,
|
||||
"isLogScale": false
|
||||
},
|
||||
"legend": {
|
||||
"position": "right",
|
||||
"mode": "list",
|
||||
"customColors": null
|
||||
},
|
||||
"thresholds": null
|
||||
}
|
||||
},
|
||||
"queries": [
|
||||
{
|
||||
"kind": "time_series",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"plugin": {
|
||||
"kind": "signoz/BuilderQuery",
|
||||
"spec": {
|
||||
"name": "A",
|
||||
"signal": "metrics",
|
||||
"source": "",
|
||||
"aggregations": [
|
||||
{
|
||||
"metricName": "storage.googleapis.com/network/sent_bytes_count",
|
||||
"temporality": "",
|
||||
"timeAggregation": "rate",
|
||||
"spaceAggregation": "sum",
|
||||
"reduceTo": "sum"
|
||||
}
|
||||
],
|
||||
"disabled": false,
|
||||
"filter": {
|
||||
"expression": "project_id = $project_id AND bucket_name in $bucket_name AND gcp.resource_type = 'gcs_bucket'"
|
||||
},
|
||||
"groupBy": [
|
||||
{
|
||||
"name": "bucket_name",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "method",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
},
|
||||
{
|
||||
"name": "response_code",
|
||||
"signal": "",
|
||||
"fieldContext": "attribute",
|
||||
"fieldDataType": "string"
|
||||
}
|
||||
],
|
||||
"order": [],
|
||||
"having": {
|
||||
"expression": ""
|
||||
},
|
||||
"functions": [],
|
||||
"legend": "{{bucket_name}}/{{method}} - {{response_code}}"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"links": []
|
||||
}
|
||||
}
|
||||
},
|
||||
"layouts": [
|
||||
{
|
||||
"kind": "Grid",
|
||||
"spec": {
|
||||
"items": [
|
||||
{
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/1f0a4d5b-6c2e-4a71-8b3d-9e5c07a41d20"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": "Grid",
|
||||
"spec": {
|
||||
"display": {
|
||||
"title": "Storage",
|
||||
"collapse": {
|
||||
"open": true
|
||||
}
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/29ed9824-21db-44c3-9537-12be458f5c20"
|
||||
}
|
||||
},
|
||||
{
|
||||
"x": 6,
|
||||
"y": 0,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/cbc53174-5527-4bce-b32d-317403849e48"
|
||||
}
|
||||
},
|
||||
{
|
||||
"x": 0,
|
||||
"y": 6,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/76e70ce5-47e4-4b5b-9715-49fa21c58b0c"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": "Grid",
|
||||
"spec": {
|
||||
"display": {
|
||||
"title": "API & Authentication",
|
||||
"collapse": {
|
||||
"open": true
|
||||
}
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/c5af2813-34ec-41a9-8d53-c9acd67f569f"
|
||||
}
|
||||
},
|
||||
{
|
||||
"x": 6,
|
||||
"y": 0,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/70333210-68c3-4387-a6b7-afa2459d27dd"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"kind": "Grid",
|
||||
"spec": {
|
||||
"display": {
|
||||
"title": "Network",
|
||||
"collapse": {
|
||||
"open": true
|
||||
}
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/7a98084c-2cd3-4146-a831-f5382162ffe5"
|
||||
}
|
||||
},
|
||||
{
|
||||
"x": 6,
|
||||
"y": 0,
|
||||
"width": 6,
|
||||
"height": 6,
|
||||
"content": {
|
||||
"$ref": "#/spec/panels/7138bf98-b41a-46d8-90ef-8e7470819cdf"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"duration": "",
|
||||
"refreshInterval": "",
|
||||
"links": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" viewBox="0 0 24 24"><defs><style>.cls-1{fill:#aecbfa;}.cls-2{fill:#669df6;}.cls-3{fill:#4285f4;}.cls-4{fill:#fff;}</style></defs><title>Icon_24px_CloudStorage_Color</title><g data-name="Product Icons"><rect class="cls-1" x="2" y="4" width="20" height="7"/><rect class="cls-2" x="20" y="4" width="2" height="7"/><polygon class="cls-3" points="22 4 20 4 20 11 22 4"/><rect class="cls-2" x="2" y="4" width="2" height="7"/><rect class="cls-4" x="6" y="7" width="6" height="1"/><rect class="cls-4" x="15" y="6" width="3" height="3" rx="1.5"/><rect class="cls-1" x="2" y="13" width="20" height="7"/><rect class="cls-2" x="20" y="13" width="2" height="7"/><polygon class="cls-3" points="22 13 20 13 20 20 22 13"/><rect class="cls-2" x="2" y="13" width="2" height="7"/><rect class="cls-4" x="6" y="16" width="6" height="1"/><rect class="cls-4" x="15" y="15" width="3" height="3" rx="1.5"/></g></svg>
|
||||
|
After Width: | Height: | Size: 958 B |
@@ -0,0 +1,70 @@
|
||||
{
|
||||
"id": "cloudstorage",
|
||||
"title": "GCP Cloud Storage",
|
||||
"icon": "file://icon.svg",
|
||||
"overview": "file://overview.md",
|
||||
"supportedSignals": {
|
||||
"metrics": true,
|
||||
"logs": true
|
||||
},
|
||||
"dataCollected": {
|
||||
"metrics": [
|
||||
{
|
||||
"name": "storage.googleapis.com/storage/v2/total_bytes",
|
||||
"unit": "Bytes",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "storage.googleapis.com/storage/v2/total_count",
|
||||
"unit": "Count",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "storage.googleapis.com/storage/v2/deleted_bytes",
|
||||
"unit": "Bytes",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "storage.googleapis.com/api/request_count",
|
||||
"unit": "Count",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "storage.googleapis.com/network/received_bytes_count",
|
||||
"unit": "Bytes",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "storage.googleapis.com/network/sent_bytes_count",
|
||||
"unit": "Bytes",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "storage.googleapis.com/authn/authentication_count",
|
||||
"unit": "Count",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
}
|
||||
],
|
||||
"logs": []
|
||||
},
|
||||
"telemetryCollectionStrategy": {
|
||||
"gcp": {}
|
||||
},
|
||||
"assets": {
|
||||
"dashboards": [
|
||||
{
|
||||
"id": "overview",
|
||||
"title": "GCP Cloud Storage Overview",
|
||||
"description": "Overview of GCP Cloud Storage metrics",
|
||||
"definition": "file://assets/dashboards/overview.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
### Monitor GCP Cloud Storage with SigNoz
|
||||
|
||||
Collect key GCP Cloud Storage metrics and view them with an out of the box dashboard.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" viewBox="0 0 24 24"><defs><style>.cls-1{fill:#4285f4;}.cls-1,.cls-2,.cls-4{fill-rule:evenodd;}.cls-2{fill:#669df6;}.cls-3,.cls-4{fill:#aecbfa;}</style></defs><title>Icon_24px_K8Engine_Color</title><g data-name="Product Icons"><g ><polygon class="cls-1" points="14.68 13.06 19.23 15.69 19.23 16.68 14.29 13.83 14.68 13.06"/><polygon class="cls-2" points="9.98 13.65 4.77 16.66 4.45 15.86 9.53 12.92 9.98 13.65"/><rect class="cls-3" x="11.55" y="3.29" width="0.86" height="5.78"/><path class="cls-4" d="M3.25,7V17L12,22l8.74-5V7L12,2Zm15.63,8.89L12,19.78,5.12,15.89V8.11L12,4.22l6.87,3.89v7.78Z"/><polygon class="cls-4" points="11.98 11.5 15.96 9.21 11.98 6.91 8.01 9.21 11.98 11.5"/><polygon class="cls-2" points="11.52 12.3 7.66 10.01 7.66 14.6 11.52 16.89 11.52 12.3"/><polygon class="cls-1" points="12.48 12.3 12.48 16.89 16.34 14.6 16.34 10.01 12.48 12.3"/></g></g></svg>
|
||||
|
After Width: | Height: | Size: 941 B |
@@ -0,0 +1,124 @@
|
||||
{
|
||||
"id": "gke",
|
||||
"title": "GCP Kubernetes Engine",
|
||||
"icon": "file://icon.svg",
|
||||
"overview": "file://overview.md",
|
||||
"supportedSignals": {
|
||||
"metrics": true,
|
||||
"logs": true
|
||||
},
|
||||
"dataCollected": {
|
||||
"metrics": [
|
||||
{
|
||||
"name": "kubernetes.io/container/cpu/limit_utilization",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/container/cpu/request_utilization",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/container/memory/limit_utilization",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/container/memory/request_utilization",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/container/restart_count",
|
||||
"unit": "Count",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/pod/latencies/pod_first_ready",
|
||||
"unit": "Seconds",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/pod/network/received_bytes_count",
|
||||
"unit": "Bytes",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/pod/network/sent_bytes_count",
|
||||
"unit": "Bytes",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/pod/volume/utilization",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/node/cpu/allocatable_utilization",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/node/memory/allocatable_utilization",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/node/ephemeral_storage/used_bytes",
|
||||
"unit": "Bytes",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/node/ephemeral_storage/allocatable_bytes",
|
||||
"unit": "Bytes",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/node/network/received_bytes_count",
|
||||
"unit": "Bytes",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/node/network/sent_bytes_count",
|
||||
"unit": "Bytes",
|
||||
"type": "Sum",
|
||||
"description": ""
|
||||
},
|
||||
{
|
||||
"name": "kubernetes.io/node/status_condition",
|
||||
"unit": "None",
|
||||
"type": "Gauge",
|
||||
"description": ""
|
||||
}
|
||||
],
|
||||
"logs": []
|
||||
},
|
||||
"telemetryCollectionStrategy": {
|
||||
"gcp": {}
|
||||
},
|
||||
"assets": {
|
||||
"dashboards": [
|
||||
{
|
||||
"id": "overview",
|
||||
"title": "GCP Kubernetes Engine Overview",
|
||||
"description": "Overview of GCP Kubernetes Engine metrics",
|
||||
"definition": "file://assets/dashboards/overview.json"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
### Monitor GCP Kubernetes Engine with SigNoz
|
||||
|
||||
Collect key GCP Kubernetes Engine metrics and view them with an out of the box dashboard.
|
||||
@@ -213,18 +213,18 @@ func (module *module) discoverModels(ctx context.Context, orgID valuer.UUID) ([]
|
||||
Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
|
||||
Name: "A",
|
||||
Signal: telemetrytypes.SignalTraces,
|
||||
Filter: &qbtypes.Filter{Expression: fmt.Sprintf("%s EXISTS", telemetrytypes.GenAIRequestModel)},
|
||||
Filter: &qbtypes.Filter{Expression: fmt.Sprintf("%s EXISTS", llmpricingruletypes.GenAIRequestModel)},
|
||||
Aggregations: []qbtypes.TraceAggregation{
|
||||
{Expression: "count()", Alias: "spanCount"},
|
||||
},
|
||||
GroupBy: []qbtypes.GroupByKey{
|
||||
{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{
|
||||
Name: telemetrytypes.GenAIRequestModel,
|
||||
Name: llmpricingruletypes.GenAIRequestModel,
|
||||
FieldContext: telemetrytypes.FieldContextSpan,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
}},
|
||||
{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{
|
||||
Name: telemetrytypes.GenAIProviderName,
|
||||
Name: llmpricingruletypes.GenAIProviderName,
|
||||
FieldContext: telemetrytypes.FieldContextSpan,
|
||||
FieldDataType: telemetrytypes.FieldDataTypeString,
|
||||
}},
|
||||
@@ -254,9 +254,9 @@ func (module *module) discoverModels(ctx context.Context, orgID valuer.UUID) ([]
|
||||
switch c.Type {
|
||||
case qbtypes.ColumnTypeGroup:
|
||||
switch c.Name {
|
||||
case telemetrytypes.GenAIRequestModel:
|
||||
case llmpricingruletypes.GenAIRequestModel:
|
||||
modelIdx = i
|
||||
case telemetrytypes.GenAIProviderName:
|
||||
case llmpricingruletypes.GenAIProviderName:
|
||||
providerIdx = i
|
||||
}
|
||||
case qbtypes.ColumnTypeAggregation:
|
||||
|
||||
@@ -485,9 +485,11 @@ func (s *store) buildFilterClause(ctx context.Context, orgID valuer.UUID, filter
|
||||
}
|
||||
|
||||
fieldKeys, _, err := s.telemetryMetadataStore.GetKeysMulti(ctx, orgID, selectors)
|
||||
if err != nil || len(fieldKeys) == 0 {
|
||||
if err != nil || fieldKeys == nil {
|
||||
fieldKeys = map[string][]*telemetrytypes.TelemetryFieldKey{}
|
||||
for _, sel := range selectors {
|
||||
}
|
||||
for _, sel := range selectors {
|
||||
if len(fieldKeys[sel.Name]) == 0 {
|
||||
fieldKeys[sel.Name] = []*telemetrytypes.TelemetryFieldKey{{
|
||||
Name: sel.Name,
|
||||
Signal: sel.Signal,
|
||||
|
||||
@@ -249,7 +249,7 @@ func (handler *handler) ReplaceVariables(rw http.ResponseWriter, req *http.Reque
|
||||
errs := []error{}
|
||||
|
||||
for idx, item := range queryRangeRequest.CompositeQuery.Queries {
|
||||
if item.Type == qbtypes.QueryTypeBuilder || item.Type == qbtypes.QueryTypeBuilderAI {
|
||||
if item.Type == qbtypes.QueryTypeBuilder {
|
||||
switch spec := item.Spec.(type) {
|
||||
case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:
|
||||
if spec.Filter != nil && spec.Filter.Expression != "" {
|
||||
|
||||
@@ -249,7 +249,6 @@ func (q *querier) buildPreviewProviders(
|
||||
func rendersStandaloneStatement(t qbtypes.QueryType) bool {
|
||||
switch t {
|
||||
case qbtypes.QueryTypeBuilder,
|
||||
qbtypes.QueryTypeBuilderAI,
|
||||
qbtypes.QueryTypePromQL,
|
||||
qbtypes.QueryTypeClickHouseSQL,
|
||||
qbtypes.QueryTypeTraceOperator:
|
||||
|
||||
@@ -52,7 +52,6 @@ type querier struct {
|
||||
metadataStore telemetrytypes.MetadataStore
|
||||
promEngine prometheus.Prometheus
|
||||
traceStmtBuilder qbtypes.StatementBuilder[qbtypes.TraceAggregation]
|
||||
aiTraceStmtBuilder qbtypes.StatementBuilder[qbtypes.TraceAggregation]
|
||||
logStmtBuilder qbtypes.StatementBuilder[qbtypes.LogAggregation]
|
||||
auditStmtBuilder qbtypes.StatementBuilder[qbtypes.LogAggregation]
|
||||
metricStmtBuilder qbtypes.StatementBuilder[qbtypes.MetricAggregation]
|
||||
@@ -72,7 +71,6 @@ func New(
|
||||
metadataStore telemetrytypes.MetadataStore,
|
||||
promEngine prometheus.Prometheus,
|
||||
traceStmtBuilder qbtypes.StatementBuilder[qbtypes.TraceAggregation],
|
||||
aiTraceStmtBuilder qbtypes.StatementBuilder[qbtypes.TraceAggregation],
|
||||
logStmtBuilder qbtypes.StatementBuilder[qbtypes.LogAggregation],
|
||||
auditStmtBuilder qbtypes.StatementBuilder[qbtypes.LogAggregation],
|
||||
metricStmtBuilder qbtypes.StatementBuilder[qbtypes.MetricAggregation],
|
||||
@@ -94,7 +92,6 @@ func New(
|
||||
metadataStore: metadataStore,
|
||||
promEngine: promEngine,
|
||||
traceStmtBuilder: traceStmtBuilder,
|
||||
aiTraceStmtBuilder: aiTraceStmtBuilder,
|
||||
logStmtBuilder: logStmtBuilder,
|
||||
auditStmtBuilder: auditStmtBuilder,
|
||||
metricStmtBuilder: metricStmtBuilder,
|
||||
@@ -245,16 +242,6 @@ func (q *querier) buildQueries(
|
||||
}
|
||||
queries[traceOpQuery.Name] = toq
|
||||
steps[traceOpQuery.Name] = traceOpQuery.StepInterval
|
||||
case qbtypes.QueryTypeBuilderAI:
|
||||
spec, ok := query.Spec.(qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation])
|
||||
if !ok {
|
||||
return nil, nil, errors.NewInvalidInputf(errors.CodeInvalidInput, "invalid AI builder query spec %T", query.Spec)
|
||||
}
|
||||
spec.ShiftBy = extractShiftFromBuilderQuery(spec)
|
||||
timeRange := adjustTimeRangeForShift(spec, qbtypes.TimeRange{From: req.Start, To: req.End}, req.RequestType)
|
||||
bq := newBuilderQuery(q.logger, q.telemetryStore, orgID, q.aiTraceStmtBuilder, spec, timeRange, req.RequestType, tmplVars, builderConfig{})
|
||||
queries[spec.Name] = bq
|
||||
steps[spec.Name] = spec.StepInterval
|
||||
case qbtypes.QueryTypeBuilder:
|
||||
switch spec := query.Spec.(type) {
|
||||
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:
|
||||
@@ -321,11 +308,6 @@ func (q *querier) populateQBEvent(event *qbtypes.QBEvent, queries []qbtypes.Quer
|
||||
case qbtypes.QueryBuilderQuery[qbtypes.MetricAggregation]:
|
||||
event.MetricsUsed = true
|
||||
}
|
||||
case qbtypes.QueryTypeBuilderAI:
|
||||
filter := query.GetFilter()
|
||||
event.FilterApplied = event.FilterApplied || (filter != nil && filter.Expression != "")
|
||||
event.GroupByApplied = event.GroupByApplied || len(query.GetGroupBy()) > 0
|
||||
event.TracesUsed = true
|
||||
case qbtypes.QueryTypePromQL:
|
||||
event.MetricsUsed = true
|
||||
case qbtypes.QueryTypeTraceOperator:
|
||||
@@ -888,9 +870,7 @@ func (q *querier) createRangedQuery(_ valuer.UUID, originalQuery qbtypes.Query,
|
||||
specCopy := qt.spec.Copy()
|
||||
specCopy.ShiftBy = extractShiftFromBuilderQuery(specCopy)
|
||||
adjustedTimeRange := adjustTimeRangeForShift(specCopy, timeRange, qt.kind)
|
||||
// Reuse the statement builder the original query was created with, so an AI
|
||||
// query keeps its AI builder without re-deriving it from the spec.
|
||||
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, qt.stmtBuilder, specCopy, adjustedTimeRange, qt.kind, qt.variables, builderConfig{})
|
||||
return newBuilderQuery(q.logger, q.telemetryStore, qt.orgID, q.traceStmtBuilder, specCopy, adjustedTimeRange, qt.kind, qt.variables, builderConfig{})
|
||||
|
||||
case *builderQuery[qbtypes.LogAggregation]:
|
||||
specCopy := qt.spec.Copy()
|
||||
@@ -1247,8 +1227,6 @@ func (q *querier) adjustStepInterval(queries []qbtypes.QueryEnvelope, start, end
|
||||
if qe.GetStepInterval().Seconds() == 0 {
|
||||
qe.SetStepInterval(secondsStep(metricRecommended))
|
||||
}
|
||||
case qbtypes.QueryTypeBuilderAI:
|
||||
clampStep(qe, traceLogRecommended, traceLogMin, &warnings)
|
||||
case qbtypes.QueryTypeTraceOperator:
|
||||
clampStep(qe, traceLogRecommended, traceLogMin, &warnings)
|
||||
}
|
||||
|
||||
@@ -49,7 +49,6 @@ func TestQueryRange_MetricTypeMissing(t *testing.T) {
|
||||
metadataStore,
|
||||
nil, // prometheus
|
||||
nil, // traceStmtBuilder
|
||||
nil, // aiTraceStmtBuilder
|
||||
nil, // logStmtBuilder
|
||||
nil, // auditStmtBuilder
|
||||
nil, // metricStmtBuilder
|
||||
@@ -122,7 +121,6 @@ func TestQueryRange_MetricTypeFromStore(t *testing.T) {
|
||||
metadataStore,
|
||||
nil, // prometheus
|
||||
nil, // traceStmtBuilder
|
||||
nil, // aiTraceStmtBuilder
|
||||
nil, // logStmtBuilder
|
||||
nil, // auditStmtBuilder
|
||||
&mockMetricStmtBuilder{},
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user