Compare commits

..

4 Commits

Author SHA1 Message Date
Gaurav Tewari
3fff4d14f2 test: type the mock and update tests 2026-10-30 03:04:30 +05:30
Gaurav Tewari
0d95d6ec83 refactor(saved-views): key saved view options by source page 2026-10-29 18:04:32 +05:30
Gaurav Tewari
44f11a1d84 refactor(options-menu): take source page instead of data source 2026-10-29 17:08:08 +05:30
Gaurav Tewari
7f3fbb3562 refactor(preferences): key preference slices by source page
Preferences belong to an explorer page, not a signal.
2026-10-29 17:08:02 +05:30
62 changed files with 712 additions and 2908 deletions

View File

@@ -11389,7 +11389,8 @@ components:
evaluation:
allOf:
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
description: The evaluation window, as a kind and spec.
description: The evaluation window, as a kind and spec. Required when schemaVersion
is v2alpha1; derived from evalWindow and frequency for v1.
frequency:
description: How often the rule is evaluated, as a Go duration such as 1m.
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
@@ -11405,7 +11406,8 @@ components:
notificationSettings:
allOf:
- $ref: '#/components/schemas/RuletypesNotificationSettings'
description: Grouping, re-notification and routing behaviour.
description: Grouping, re-notification and routing behaviour. Required when
schemaVersion is v2alpha1; derived from the v1 fields otherwise.
preferredChannels:
description: The displayName of each notification channel to notify, for
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
@@ -11418,30 +11420,26 @@ components:
- $ref: '#/components/schemas/RuletypesRuleType'
description: 'The evaluation strategy: threshold_rule compares against thresholds,
promql_rule evaluates a PromQL expression, anomaly_rule scores deviation
from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql
queries and is forced to promql_rule for promql queries.'
from seasonal history. Defaults to threshold_rule for builder queries
and is forced to promql_rule for promql queries.'
schemaVersion:
description: The rule payload schema.
enum:
- v2alpha1
description: 'The rule payload schema: v1 (the default when omitted) uses
the flat condition fields, v2alpha1 uses condition.thresholds, evaluation
and notificationSettings.'
type: string
source:
deprecated: true
description: The URL of the page the rule was created from. Informational;
it is not used for evaluation.
type: string
version:
deprecated: true
description: The query payload version. Nothing reads it.
description: The query payload version. Only v5 is accepted and it is filled
in when omitted.
type: string
required:
- alert
- alertType
- ruleType
- condition
- evaluation
- schemaVersion
- notificationSettings
type: object
RuletypesPostableRuleView:
properties:
@@ -11530,7 +11528,8 @@ components:
evaluation:
allOf:
- $ref: '#/components/schemas/RuletypesEvaluationEnvelope'
description: The evaluation window, as a kind and spec.
description: The evaluation window, as a kind and spec. Required when schemaVersion
is v2alpha1; derived from evalWindow and frequency for v1.
frequency:
description: How often the rule is evaluated, as a Go duration such as 1m.
Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set
@@ -11549,7 +11548,8 @@ components:
notificationSettings:
allOf:
- $ref: '#/components/schemas/RuletypesNotificationSettings'
description: Grouping, re-notification and routing behaviour.
description: Grouping, re-notification and routing behaviour. Required when
schemaVersion is v2alpha1; derived from the v1 fields otherwise.
preferredChannels:
description: The displayName of each notification channel to notify, for
schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries
@@ -11562,15 +11562,14 @@ components:
- $ref: '#/components/schemas/RuletypesRuleType'
description: 'The evaluation strategy: threshold_rule compares against thresholds,
promql_rule evaluates a PromQL expression, anomaly_rule scores deviation
from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql
queries and is forced to promql_rule for promql queries.'
from seasonal history. Defaults to threshold_rule for builder queries
and is forced to promql_rule for promql queries.'
schemaVersion:
description: The rule payload schema.
enum:
- v2alpha1
description: 'The rule payload schema: v1 (the default when omitted) uses
the flat condition fields, v2alpha1 uses condition.thresholds, evaluation
and notificationSettings.'
type: string
source:
deprecated: true
description: The URL of the page the rule was created from. Informational;
it is not used for evaluation.
type: string
@@ -11585,8 +11584,8 @@ components:
updatedBy:
type: string
version:
deprecated: true
description: The query payload version. Nothing reads it.
description: The query payload version. Only v5 is accepted and it is filled
in when omitted.
type: string
required:
- id
@@ -11595,9 +11594,6 @@ components:
- alertType
- ruleType
- condition
- evaluation
- schemaVersion
- notificationSettings
type: object
RuletypesRuleCondition:
properties:
@@ -11647,7 +11643,8 @@ components:
against, hourly, daily or weekly.'
selectedQueryName:
description: The name of the query whose result is evaluated, such as A
or F1. Must match a query in compositeQuery.
or F1. Must match a query in compositeQuery. When omitted, F1 is used
if present, otherwise the enabled query with the highest name.
type: string
target:
description: 'schemaVersion v1 only: the value compared against, in targetUnit.
@@ -11663,11 +11660,10 @@ components:
thresholds:
allOf:
- $ref: '#/components/schemas/RuletypesRuleThresholdData'
description: The thresholds to evaluate, as a kind and spec.
description: The thresholds to evaluate, as a kind and spec. Required when
schemaVersion is v2alpha1; derived from op, target and matchType for v1.
required:
- compositeQuery
- selectedQueryName
- thresholds
type: object
RuletypesRuleThresholdData:
discriminator:
@@ -25316,13 +25312,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -25357,36 +25353,22 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
target: 2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
evalWindow: 24h
frequency: 3h
labels:
severity: warning
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
preferredChannels:
- slack-ingestion
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -26282,13 +26264,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -26323,36 +26305,22 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
target: 2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
evalWindow: 24h
frequency: 3h
labels:
severity: warning
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
preferredChannels:
- slack-ingestion
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -27149,13 +27117,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -27190,36 +27158,22 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
target: 2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
evalWindow: 24h
frequency: 3h
labels:
severity: warning
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
preferredChannels:
- slack-ingestion
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL
@@ -28722,13 +28676,13 @@ paths:
schemaVersion: v2alpha1
version: v5
metric_anomaly:
description: Wraps a builder query in the `anomaly` function with
daily seasonality, so SigNoz compares each point against the forecast
for that time of day. The threshold is compared against the signed
anomaly score, so `below` with a target of -2 fires when an abrupt
drop holds for the entire window; `requireMinPoints` guards against
noisy intervals.
summary: Metric anomaly rule
description: Anomaly rules are not yet supported under schemaVersion
v2alpha1, so this example uses the v1 shape. Wraps a builder query
in the `anomaly` function with daily seasonality SigNoz compares
each point against the forecast for that time of day. Fires when
the anomaly score stays below the threshold for the entire window;
`requireMinPoints` guards against noisy intervals.
summary: Metric anomaly rule (v1 only)
value:
alert: Anomalous drop in ingested spans
alertType: METRIC_BASED_ALERT
@@ -28763,36 +28717,22 @@ paths:
stepInterval: 21600
type: builder_query
queryType: builder
matchType: all_the_times
op: below
requireMinPoints: true
requiredNumPoints: 3
seasonality: daily
selectedQueryName: A
thresholds:
kind: basic
spec:
- channels:
- slack-ingestion
matchType: all_the_times
name: warning
op: below
target: -2
target: 2
description: Detect an abrupt drop in span ingestion using a z-score
anomaly function
evaluation:
kind: rolling
spec:
evalWindow: 24h
frequency: 3h
evalWindow: 24h
frequency: 3h
labels:
severity: warning
notificationSettings:
renotify:
alertStates:
- firing
enabled: true
interval: 4h
preferredChannels:
- slack-ingestion
ruleType: anomaly_rule
schemaVersion: v2alpha1
version: v5
metric_promql:
description: PromQL expression instead of the builder. Dotted OTEL

View File

@@ -12584,12 +12584,6 @@ export type RuletypesPostableRuleDTOAnnotations = { [key: string]: string };
*/
export type RuletypesPostableRuleDTOLabels = { [key: string]: string };
/**
* The rule payload schema.
*/
export enum RuletypesPostableRuleDTOSchemaVersion {
v2alpha1 = 'v2alpha1',
}
export enum RuletypesSeasonalityDTO {
hourly = 'hourly',
daily = 'daily',
@@ -12666,9 +12660,9 @@ export interface RuletypesRuleConditionDTO {
seasonality?: RuletypesSeasonalityDTO;
/**
* @type string
* @description The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery.
* @description The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery. When omitted, F1 is used if present, otherwise the enabled query with the highest name.
*/
selectedQueryName: string;
selectedQueryName?: string;
/**
* @type number,null
* @format double
@@ -12681,9 +12675,9 @@ export interface RuletypesRuleConditionDTO {
*/
targetUnit?: string;
/**
* @description The thresholds to evaluate, as a kind and spec.
* @description The thresholds to evaluate, as a kind and spec. Required when schemaVersion is v2alpha1; derived from op, target and matchType for v1.
*/
thresholds: RuletypesRuleThresholdDataDTO;
thresholds?: RuletypesRuleThresholdDataDTO;
}
export interface RuletypesPostableRuleDTO {
@@ -12721,9 +12715,9 @@ export interface RuletypesPostableRuleDTO {
*/
evalWindow?: string;
/**
* @description The evaluation window, as a kind and spec.
* @description The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1.
*/
evaluation: RuletypesEvaluationEnvelopeDTO;
evaluation?: RuletypesEvaluationEnvelopeDTO;
/**
* @type string
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
@@ -12735,24 +12729,23 @@ export interface RuletypesPostableRuleDTO {
*/
labels?: RuletypesPostableRuleDTOLabels;
/**
* @description Grouping, re-notification and routing behaviour.
* @description Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise.
*/
notificationSettings: RuletypesNotificationSettingsDTO;
notificationSettings?: RuletypesNotificationSettingsDTO;
/**
* @type array
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
*/
preferredChannels?: string[];
/**
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries.
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder queries and is forced to promql_rule for promql queries.
*/
ruleType: RuletypesRuleTypeDTO;
/**
* @enum v2alpha1
* @type string
* @description The rule payload schema.
* @description The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings.
*/
schemaVersion: RuletypesPostableRuleDTOSchemaVersion;
schemaVersion?: string;
/**
* @type string
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
@@ -12760,7 +12753,7 @@ export interface RuletypesPostableRuleDTO {
source?: string;
/**
* @type string
* @description The query payload version. Nothing reads it.
* @description The query payload version. Only v5 is accepted and it is filled in when omitted.
*/
version?: string;
}
@@ -12783,12 +12776,6 @@ export type RuletypesRuleDTOAnnotations = { [key: string]: string };
*/
export type RuletypesRuleDTOLabels = { [key: string]: string };
/**
* The rule payload schema.
*/
export enum RuletypesRuleDTOSchemaVersion {
v2alpha1 = 'v2alpha1',
}
export interface RuletypesRuleDTO {
/**
* @type string
@@ -12833,9 +12820,9 @@ export interface RuletypesRuleDTO {
*/
evalWindow?: string;
/**
* @description The evaluation window, as a kind and spec.
* @description The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1.
*/
evaluation: RuletypesEvaluationEnvelopeDTO;
evaluation?: RuletypesEvaluationEnvelopeDTO;
/**
* @type string
* @description How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead.
@@ -12852,24 +12839,23 @@ export interface RuletypesRuleDTO {
*/
labels?: RuletypesRuleDTOLabels;
/**
* @description Grouping, re-notification and routing behaviour.
* @description Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise.
*/
notificationSettings: RuletypesNotificationSettingsDTO;
notificationSettings?: RuletypesNotificationSettingsDTO;
/**
* @type array
* @description The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels.
*/
preferredChannels?: string[];
/**
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries.
* @description The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder queries and is forced to promql_rule for promql queries.
*/
ruleType: RuletypesRuleTypeDTO;
/**
* @enum v2alpha1
* @type string
* @description The rule payload schema.
* @description The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings.
*/
schemaVersion: RuletypesRuleDTOSchemaVersion;
schemaVersion?: string;
/**
* @type string
* @description The URL of the page the rule was created from. Informational; it is not used for evaluation.
@@ -12890,7 +12876,7 @@ export interface RuletypesRuleDTO {
updatedBy?: string;
/**
* @type string
* @description The query payload version. Nothing reads it.
* @description The query payload version. Only v5 is accepted and it is filled in when omitted.
*/
version?: string;
}

View File

@@ -4,6 +4,7 @@ import { Button } from '@signozhq/ui/button';
import { Drawer, Tooltip } from 'antd';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { Typography } from '@signozhq/ui/typography';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import LogStateIndicator from 'components/Logs/LogStateIndicator/LogStateIndicator';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySearch';
@@ -147,7 +148,7 @@ function LogDetailInner({
const { options } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
});

View File

@@ -129,7 +129,6 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
onChange={handleChangeOperator}
operators={operators}
className="metrics-operators-select"
data-testid="metrics-time-aggregation"
/>
</div>
</div>
@@ -193,10 +192,7 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
AGGREGATE ACROSS TIME SERIES
</div>
</Tooltip>
<div
className="metrics-aggregation-section-content-item-value"
data-testid="metrics-space-aggregation"
>
<div className="metrics-aggregation-section-content-item-value">
<SpaceAggregationOptions
panelType={panelType}
key={`${panelType}${queryAggregation.spaceAggregation}${queryAggregation.timeAggregation}`}
@@ -233,10 +229,7 @@ const MetricsAggregateSection = memo(function MetricsAggregateSection({
<div className="metrics-space-aggregation-section">
<div className="metrics-aggregation-section-content">
<div className="metrics-aggregation-section-content-item">
<div
className="metrics-aggregation-section-content-item-value"
data-testid="metrics-space-aggregation"
>
<div className="metrics-aggregation-section-content-item-value">
<SpaceAggregationOptions
panelType={panelType}
key={`${panelType}${queryAggregation.spaceAggregation}${queryAggregation.timeAggregation}`}

View File

@@ -332,7 +332,6 @@ function HavingFilter({
value={input}
onChange={handleChange}
theme={isDarkMode ? copilot : githubLight}
data-testid="having-editor"
className="having-filter-select-editor"
width="100%"
extensions={[

View File

@@ -615,7 +615,6 @@ function QueryAggregationSelect({
setInput(value);
onChange?.(value);
}}
data-testid="query-aggregation-editor"
className={`query-aggregation-select-editor ${
validationError ? 'error' : ''
}`}

View File

@@ -1607,7 +1607,6 @@ function QuerySearch({
onChange={handleChange}
onUpdate={handleUpdate}
onCreateEditor={handleEditorCreate}
data-testid="query-where-clause-editor"
className={cx('query-where-clause-editor', {
isValid: validation.isValid === true,
hasErrors: validation.errors.length > 0,
@@ -1681,7 +1680,6 @@ function QuerySearch({
className={cx('query-status-container', {
hasErrors: validation.errors.length > 0,
})}
data-testid="query-validation-status"
>
<Popover
placement="bottomRight"

View File

@@ -183,7 +183,6 @@ export const QueryV2 = forwardRef(function QueryV2(
<div
className={cx('query-v2', { 'where-clause-view': showOnlyWhereClause })}
ref={ref}
data-testid={`query-${query.queryName}`}
>
<div className="qb-content-section">
{(!showOnlyWhereClause || showTraceOperator) && (
@@ -247,7 +246,6 @@ export const QueryV2 = forwardRef(function QueryV2(
{isMultiQueryAllowed && (
<Dropdown
items={queryActionItems}
testId="query-actions"
nativeButton={false}
align="end"
side="bottom"

View File

@@ -61,10 +61,7 @@ export default function TraceOperator({
);
return (
<div
className={cx('qb-trace-operator', !isRawQuery && 'non-list-view')}
data-testid="trace-operator"
>
<div className={cx('qb-trace-operator', !isRawQuery && 'non-list-view')}>
<div className="qb-trace-operator-container">
<div
className={cx(

View File

@@ -378,7 +378,6 @@ function TraceOperatorEditor({
theme={isDarkMode ? copilot : githubLight}
onChange={handleChange}
onUpdate={handleUpdate}
data-testid="trace-operator-editor"
className={cx('query-where-clause-editor', {
isValid: validation.isValid === true,
hasErrors: validation.errors.length > 0,

View File

@@ -2,6 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useLocation } from 'react-router-dom';
import { Switch } from '@signozhq/ui/switch';
import { Typography } from '@signozhq/ui/typography';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import FieldsSelector from 'components/FieldsSelector';
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
import { MAX_LOGS_LIST_SIZE } from 'constants/liveTail';
@@ -54,7 +55,7 @@ function LiveLogsContainer({
const { options, config } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
});

View File

@@ -5,6 +5,7 @@ import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
import { toast } from '@signozhq/ui/sonner';
import { Card } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import LogDetail from 'components/LogDetail';
import { VIEW_TYPES } from 'components/LogDetail/constants';
import ListLogView from 'components/Logs/ListLogView';
@@ -30,7 +31,7 @@ import { useIsDarkMode } from 'hooks/useDarkMode';
import { useEventSource } from 'providers/EventSource';
// interfaces
import { ILog } from 'types/api/logs/log';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import { StringOperators } from 'types/common/queryBuilder';
import loadingPlaneUrl from '@/assets/Icons/loading-plane.gif';
import { getAbsoluteUrl } from 'utils/basePath';
@@ -68,7 +69,7 @@ function LiveLogsList({
const { options, config } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: StringOperators.NOOP,
});

View File

@@ -1,6 +1,7 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Virtuoso } from 'react-virtuoso';
import { Button, Skeleton } from 'antd';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import RawLogView from 'components/Logs/RawLogView';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import { LOCALSTORAGE } from 'constants/localStorage';
@@ -16,7 +17,7 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import useUrlQuery from 'hooks/useUrlQuery';
import { ILog } from 'types/api/logs/log';
import { Query, TagFilter } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource, StringOperators } from 'types/common/queryBuilder';
import { StringOperators } from 'types/common/queryBuilder';
import { withBasePath } from 'utils/basePath';
import { useContextLogData } from './useContextLogData';
@@ -45,7 +46,7 @@ function ContextLogRenderer({
const { options } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
});

View File

@@ -5,6 +5,7 @@ import { Virtuoso, VirtuosoHandle } from 'react-virtuoso';
import { toast } from '@signozhq/ui/sonner';
import { Card } from 'antd';
import logEvent from 'api/common/logEvent';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import LogDetail from 'components/LogDetail';
import { VIEW_TYPES } from 'components/LogDetail/constants';
@@ -77,7 +78,7 @@ function LogsExplorerList({
const { options, config } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator:
currentStagedQueryData?.aggregateOperator || StringOperators.NOOP,
});

View File

@@ -1,6 +1,7 @@
import { ReactNode, useState } from 'react';
import { Switch } from '@signozhq/ui/switch';
import { Typography } from '@signozhq/ui/typography';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
import FieldsSelector from 'components/FieldsSelector';
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
@@ -28,7 +29,7 @@ function LogsActionsContainer({
}): JSX.Element {
const { options, config } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: listQuery?.aggregateOperator || StringOperators.NOOP,
});

View File

@@ -1,11 +1,20 @@
import { useQueries } from 'react-query';
import { renderHook } from '@testing-library/react';
import { createElement, ReactNode } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import type { NotificationInstance } from 'antd/es/notification/interface';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { useGetQueryKeySuggestions } from 'hooks/querySuggestions/useGetQueryKeySuggestions';
import { useNotifications } from 'hooks/useNotifications';
import useUrlQueryData from 'hooks/useUrlQueryData';
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
import { DataSource } from 'types/common/queryBuilder';
import {
FormattingOptions,
PreferenceContextValue,
PreferenceSlice,
} from 'providers/preferences/types';
import { renderHook } from 'tests/test-utils';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { FontSize } from '../types';
import useOptionsMenu from '../useOptionsMenu';
// Mock all dependencies
@@ -13,104 +22,118 @@ jest.mock('hooks/useNotifications');
jest.mock('providers/preferences/context/PreferenceContextProvider');
jest.mock('hooks/useUrlQueryData');
jest.mock('hooks/querySuggestions/useGetQueryKeySuggestions');
jest.mock('react-query', () => ({
...jest.requireActual('react-query'),
useQueries: jest.fn(),
}));
const mockUseNotifications = jest.mocked(useNotifications);
const mockUsePreferenceContext = jest.mocked(usePreferenceContext);
const mockUseUrlQueryData = jest.mocked(useUrlQueryData);
const mockUseGetQueryKeySuggestions = jest.mocked(useGetQueryKeySuggestions);
type KeySuggestionsResult = ReturnType<typeof useGetQueryKeySuggestions>;
// The hook reads only `data.data.data.keys` and `isFetching`.
const keySuggestions = (
attributeKeys: Record<string, string>[],
): KeySuggestionsResult =>
({
data: { data: { data: { complete: true, keys: { attributeKeys } } } },
isFetching: false,
}) as unknown as KeySuggestionsResult;
const wrapper = ({ children }: { children: ReactNode }): JSX.Element =>
createElement(QueryClientProvider, { client: new QueryClient() }, children);
const toIds = (columns: TelemetryFieldKey[]): string[] =>
columns.map((column) => `${column.fieldContext}:${column.name}`);
describe('useOptionsMenu', () => {
const mockNotifications = { error: jest.fn(), success: jest.fn() };
const mockUpdateColumns = jest.fn();
const mockUpdateFormatting = jest.fn();
const mockRedirectWithQuery = jest.fn();
const mockNotifications = {
error: jest.fn() as jest.MockedFunction<NotificationInstance['error']>,
success: jest.fn() as jest.MockedFunction<NotificationInstance['success']>,
} as Partial<NotificationInstance> as NotificationInstance;
const mockUpdateColumns = jest.fn() as jest.MockedFunction<
PreferenceSlice['updateColumns']
>;
const mockUpdateFormatting = jest.fn() as jest.MockedFunction<
PreferenceSlice['updateFormatting']
>;
const mockRedirectWithQuery = jest.fn() as jest.MockedFunction<
(newQueryData: unknown) => void
>;
const slice = (
columns: TelemetryFieldKey[],
formatting: FormattingOptions,
): PreferenceSlice => ({
preferences: { columns, formatting },
loading: false,
error: null,
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
});
const rawFormatting: FormattingOptions = {
format: 'raw',
maxLines: 1,
fontSize: FontSize.SMALL,
};
beforeEach(() => {
jest.clearAllMocks();
(useNotifications as jest.Mock).mockReturnValue({
mockUseNotifications.mockReturnValue({
notifications: mockNotifications,
});
(usePreferenceContext as jest.Mock).mockReturnValue({
traces: {
preferences: {
columns: [],
formatting: {
format: 'raw',
maxLines: 1,
fontSize: 'small',
},
},
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
},
logs: {
preferences: {
columns: [],
formatting: {
format: 'raw',
maxLines: 1,
fontSize: 'small',
},
},
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
},
});
mockUsePreferenceContext.mockReturnValue({
[SavedviewtypesSourceDTO.traces]: slice([], rawFormatting),
[SavedviewtypesSourceDTO.logs]: slice([], rawFormatting),
} satisfies PreferenceContextValue);
(useUrlQueryData as jest.Mock).mockReturnValue({
mockUseUrlQueryData.mockReturnValue({
query: null,
queryData: undefined,
redirectWithQuery: mockRedirectWithQuery,
});
(useQueries as jest.Mock).mockReturnValue([]);
});
it('does not show isRoot or isEntryPoint in column options when dataSource is TRACES', () => {
it('does not show isRoot or isEntryPoint in column options when sourcePage is traces', () => {
// Mock the query key suggestions to return data including isRoot and isEntryPoint
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
data: {
data: {
data: {
keys: {
attributeKeys: [
{
name: 'isRoot',
signal: 'traces',
fieldDataType: 'bool',
fieldContext: '',
},
{
name: 'isEntryPoint',
signal: 'traces',
fieldDataType: 'bool',
fieldContext: '',
},
{
name: 'duration',
signal: 'traces',
fieldDataType: 'float64',
fieldContext: '',
},
{
name: 'serviceName',
signal: 'traces',
fieldDataType: 'string',
fieldContext: '',
},
],
},
},
mockUseGetQueryKeySuggestions.mockReturnValue(
keySuggestions([
{
name: 'isRoot',
signal: 'traces',
fieldDataType: 'bool',
fieldContext: '',
},
},
isFetching: false,
});
{
name: 'isEntryPoint',
signal: 'traces',
fieldDataType: 'bool',
fieldContext: '',
},
{
name: 'duration',
signal: 'traces',
fieldDataType: 'float64',
fieldContext: '',
},
{
name: 'serviceName',
signal: 'traces',
fieldDataType: 'string',
fieldContext: '',
},
]),
);
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.TRACES,
aggregateOperator: 'count',
}),
const { result } = renderHook(
() =>
useOptionsMenu({
sourcePage: SavedviewtypesSourceDTO.traces,
aggregateOperator: 'count',
}),
{ wrapper },
);
// Get the column options from the config
@@ -127,98 +150,38 @@ describe('useOptionsMenu', () => {
expect(optionNames).toContain('serviceName');
});
it('does not show body in column options when dataSource is METRICS', () => {
it('shows body in column options when sourcePage is logs', () => {
// Mock the query key suggestions to return data including body
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
data: {
data: {
data: {
keys: {
attributeKeys: [
{
name: 'body',
signal: 'logs',
fieldDataType: 'string',
fieldContext: '',
},
{
name: 'status',
signal: 'metrics',
fieldDataType: 'int64',
fieldContext: '',
},
{
name: 'value',
signal: 'metrics',
fieldDataType: 'float64',
fieldContext: '',
},
],
},
},
mockUseGetQueryKeySuggestions.mockReturnValue(
keySuggestions([
{
name: 'body',
signal: 'logs',
fieldDataType: 'string',
fieldContext: '',
},
},
isFetching: false,
});
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.METRICS,
aggregateOperator: 'count',
}),
{
name: 'level',
signal: 'logs',
fieldDataType: 'string',
fieldContext: '',
},
{
name: 'timestamp',
signal: 'logs',
fieldDataType: 'int64',
fieldContext: '',
},
]),
);
// Get the column options from the config
const columnOptions = result.current.config.addColumn?.options ?? [];
const optionNames = columnOptions.map((option) => option.label);
// body should NOT be in the options
expect(optionNames).not.toContain('body');
// Other attributes should be present
expect(optionNames).toContain('status');
expect(optionNames).toContain('value');
});
it('does not show body in column options when dataSource is LOGS', () => {
// Mock the query key suggestions to return data including body
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
data: {
data: {
data: {
keys: {
attributeKeys: [
{
name: 'body',
signal: 'logs',
fieldDataType: 'string',
fieldContext: '',
},
{
name: 'level',
signal: 'logs',
fieldDataType: 'string',
fieldContext: '',
},
{
name: 'timestamp',
signal: 'logs',
fieldDataType: 'int64',
fieldContext: '',
},
],
},
},
},
},
isFetching: false,
});
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.LOGS,
aggregateOperator: 'count',
}),
const { result } = renderHook(
() =>
useOptionsMenu({
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: 'count',
}),
{ wrapper },
);
// Get the column options from the config
@@ -234,15 +197,15 @@ describe('useOptionsMenu', () => {
});
describe('reorderSelectColumns / handleRemoveSelectedColumn — composite ID lookup', () => {
const baseFormatting = {
const baseFormatting: FormattingOptions = {
format: 'table',
maxLines: 1,
fontSize: 'small',
fontSize: FontSize.SMALL,
};
// Two entries share the same `name` but differ in `fieldContext` — the
// exact case composite IDs are meant to disambiguate.
const seedColumns = [
const seedColumns: TelemetryFieldKey[] = [
{
name: 'body',
fieldContext: 'log',
@@ -264,36 +227,26 @@ describe('useOptionsMenu', () => {
{
name: 'timestamp',
fieldContext: 'log',
fieldDataType: '',
signal: 'logs',
},
];
beforeEach(() => {
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
data: { data: { data: { keys: {} } } },
isFetching: false,
});
(usePreferenceContext as jest.Mock).mockReturnValue({
traces: {
preferences: { columns: [], formatting: baseFormatting },
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
},
logs: {
preferences: { columns: seedColumns, formatting: baseFormatting },
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
},
});
mockUseGetQueryKeySuggestions.mockReturnValue(keySuggestions([]));
mockUsePreferenceContext.mockReturnValue({
[SavedviewtypesSourceDTO.traces]: slice([], baseFormatting),
[SavedviewtypesSourceDTO.logs]: slice(seedColumns, baseFormatting),
} satisfies PreferenceContextValue);
});
it('reorders by composite IDs — preserves both same-name variants distinctly', () => {
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.LOGS,
aggregateOperator: 'count',
}),
const { result } = renderHook(
() =>
useOptionsMenu({
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: 'count',
}),
{ wrapper },
);
// New order: [attribute:service.name, log:body, resource:service.name, log:timestamp]
@@ -306,12 +259,7 @@ describe('useOptionsMenu', () => {
expect(mockUpdateColumns).toHaveBeenCalledTimes(1);
const reordered = mockUpdateColumns.mock.calls[0][0];
expect(
reordered.map(
(c: { name: string; fieldContext: string }) =>
`${c.fieldContext}:${c.name}`,
),
).toStrictEqual([
expect(toIds(reordered)).toStrictEqual([
'attribute:service.name',
'log:body',
'resource:service.name',
@@ -320,11 +268,13 @@ describe('useOptionsMenu', () => {
});
it('reorder ignores ids that are not columns (e.g. state-indicator) and skips unknown ids', () => {
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.LOGS,
aggregateOperator: 'count',
}),
const { result } = renderHook(
() =>
useOptionsMenu({
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: 'count',
}),
{ wrapper },
);
result.current.config.addColumn?.onReorder([
@@ -338,12 +288,7 @@ describe('useOptionsMenu', () => {
const reordered = mockUpdateColumns.mock.calls[0][0];
// state-indicator + unknown.composite filtered; rest preserved in given order.
expect(
reordered.map(
(c: { name: string; fieldContext: string }) =>
`${c.fieldContext}:${c.name}`,
),
).toStrictEqual([
expect(toIds(reordered)).toStrictEqual([
'log:timestamp',
'log:body',
'resource:service.name',
@@ -352,11 +297,13 @@ describe('useOptionsMenu', () => {
});
it('removes only the variant whose composite ID matches', () => {
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.LOGS,
aggregateOperator: 'count',
}),
const { result } = renderHook(
() =>
useOptionsMenu({
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: 'count',
}),
{ wrapper },
);
// Removing 'resource:service.name' should drop ONLY the resource variant.
@@ -364,20 +311,21 @@ describe('useOptionsMenu', () => {
expect(mockUpdateColumns).toHaveBeenCalledTimes(1);
const remaining = mockUpdateColumns.mock.calls[0][0];
expect(
remaining.map(
(c: { name: string; fieldContext: string }) =>
`${c.fieldContext}:${c.name}`,
),
).toStrictEqual(['log:body', 'attribute:service.name', 'log:timestamp']);
expect(toIds(remaining)).toStrictEqual([
'log:body',
'attribute:service.name',
'log:timestamp',
]);
});
it('removing by a non-matching composite ID is a no-op (filter returns the full list)', () => {
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.LOGS,
aggregateOperator: 'count',
}),
const { result } = renderHook(
() =>
useOptionsMenu({
sourcePage: SavedviewtypesSourceDTO.logs,
aggregateOperator: 'count',
}),
{ wrapper },
);
result.current.config.addColumn?.onRemove('unknown.composite');
@@ -390,35 +338,34 @@ describe('useOptionsMenu', () => {
describe('fieldsSelector.value drops legacy columns without a name', () => {
it('excludes entries missing name while keeping valid columns', () => {
(useGetQueryKeySuggestions as jest.Mock).mockReturnValue({
data: { data: { data: { keys: {} } } },
isFetching: false,
});
(usePreferenceContext as jest.Mock).mockReturnValue({
traces: {
preferences: {
columns: [
{ name: 'body', fieldContext: 'log' },
{ key: 'legacy-key-no-name', fieldContext: 'log' },
{ name: 'timestamp', fieldContext: 'log' },
],
formatting: { format: 'table', maxLines: 1, fontSize: 'small' },
mockUseGetQueryKeySuggestions.mockReturnValue(keySuggestions([]));
mockUsePreferenceContext.mockReturnValue({
[SavedviewtypesSourceDTO.traces]: slice(
[
{ name: 'body', fieldContext: 'log' },
// A legacy stored column: `key` only, no `name`.
{
key: 'legacy-key-no-name',
fieldContext: 'log',
} as unknown as TelemetryFieldKey,
{ name: 'timestamp', fieldContext: 'log' },
],
{
format: 'table',
maxLines: 1,
fontSize: FontSize.SMALL,
},
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
},
logs: {
preferences: { columns: [], formatting: {} },
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
},
});
),
[SavedviewtypesSourceDTO.logs]: slice([], {}),
} satisfies PreferenceContextValue);
const { result } = renderHook(() =>
useOptionsMenu({
dataSource: DataSource.TRACES,
aggregateOperator: 'count',
}),
const { result } = renderHook(
() =>
useOptionsMenu({
sourcePage: SavedviewtypesSourceDTO.traces,
aggregateOperator: 'count',
}),
{ wrapper },
);
const fields = result.current.config.fieldsSelector?.value ?? [];

View File

@@ -1,4 +1,6 @@
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'api/v5/v5';
import { PREFERENCE_SOURCE_PAGES } from 'providers/preferences/constants';
import { DataSource } from 'types/common/queryBuilder';
import { FontSize, OptionsQuery } from './types';
@@ -13,6 +15,14 @@ export const defaultOptionsQuery: OptionsQuery = {
fontSize: FontSize.SMALL,
};
export const SOURCE_PAGE_SIGNAL: Record<
(typeof PREFERENCE_SOURCE_PAGES)[number],
DataSource
> = {
[SavedviewtypesSourceDTO.logs]: DataSource.LOGS,
[SavedviewtypesSourceDTO.traces]: DataSource.TRACES,
};
export const EXCLUDED_COLUMNS: Record<DataSource, string[]> = {
[DataSource.TRACES]: ['body', 'isRoot', 'isEntryPoint'],
[DataSource.METRICS]: ['body'],

View File

@@ -1,6 +1,7 @@
/* eslint-disable sonarjs/cognitive-complexity */
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useQueries } from 'react-query';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { getKeySuggestions } from 'api/querySuggestions/getKeySuggestions';
import { TelemetryFieldKey } from 'api/v5/v5';
import { AxiosResponse } from 'axios';
@@ -11,6 +12,7 @@ import useUrlQueryData from 'hooks/useUrlQueryData';
import { has } from 'lodash-es';
import { AllTraceFilterKeyValue } from 'constants/traceFilterKeys';
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
import { PreferenceSourcePage } from 'providers/preferences/types';
import {
QueryKeyRequestProps,
QueryKeySuggestionsResponseProps,
@@ -20,13 +22,13 @@ import {
FieldDataType,
SignalType,
} from 'types/api/v5/queryRange';
import { DataSource } from 'types/common/queryBuilder';
import {
defaultLogsSelectedColumns,
defaultOptionsQuery,
defaultTraceSelectedColumns,
EXCLUDED_COLUMNS,
SOURCE_PAGE_SIGNAL,
URL_OPTIONS,
} from './constants';
import {
@@ -40,7 +42,7 @@ import { buildCompositeKey, getOptionsFromKeys } from './utils';
interface UseOptionsMenuProps {
storageKey?: string;
dataSource: DataSource;
sourcePage: PreferenceSourcePage;
aggregateOperator?: string;
initialOptions?: InitialOptions;
}
@@ -52,15 +54,14 @@ interface UseOptionsMenu {
}
const useOptionsMenu = ({
dataSource,
// aggregateOperator,
sourcePage,
initialOptions = {},
}: UseOptionsMenuProps): UseOptionsMenu => {
const signal = SOURCE_PAGE_SIGNAL[sourcePage];
const { notifications } = useNotifications();
const prefCtx = usePreferenceContext();
// TODO: send null to updateColumns and updateFormatting if dataSource is not logs or traces
const slice = dataSource === DataSource.TRACES ? prefCtx.traces : prefCtx.logs;
const { preferences, updateColumns, updateFormatting } = slice;
const { preferences, updateColumns, updateFormatting } =
usePreferenceContext()[sourcePage];
const [searchText, setSearchText] = useState<string>('');
const [isFocused, setIsFocused] = useState<boolean>(false);
@@ -68,10 +69,10 @@ const useOptionsMenu = ({
const initialQueryParamsV5: QueryKeyRequestProps = useMemo(
() => ({
signal: dataSource,
signal,
searchText: '',
}),
[dataSource],
[signal],
);
const { query: optionsQuery, redirectWithQuery: redirectWithOptionsData } =
@@ -127,7 +128,7 @@ const useOptionsMenu = ({
?.map((column) => attributesData.find(({ name }) => name === column))
.filter((e) => !!e) || []) as TelemetryFieldKey[];
if (dataSource === DataSource.TRACES) {
if (sourcePage === SavedviewtypesSourceDTO.traces) {
initialSelected = initialSelected
?.map((col) => {
if (col && Object.keys(AllTraceFilterKeyValue).includes(col?.name)) {
@@ -157,7 +158,7 @@ const useOptionsMenu = ({
isFetchedInitialAttributes,
initialOptions?.selectColumns,
initialAttributesResult,
dataSource,
sourcePage,
]);
const {
@@ -195,7 +196,7 @@ const useOptionsMenu = ({
fieldDataType: e.fieldDataType,
}));
}
if (dataSource === DataSource.TRACES) {
if (sourcePage === SavedviewtypesSourceDTO.traces) {
return defaultTraceSelectedColumns.map((e) => ({
...e,
name: e.name,
@@ -203,16 +204,16 @@ const useOptionsMenu = ({
}
return [];
}, [dataSource, searchedAttributesDataV5?.data.data.keys]);
}, [sourcePage, searchedAttributesDataV5?.data.data.keys]);
const initialOptionsQuery: OptionsQuery = useMemo(() => {
let defaultColumns: TelemetryFieldKey[] = defaultOptionsQuery.selectColumns;
if (dataSource === DataSource.TRACES) {
if (sourcePage === SavedviewtypesSourceDTO.traces) {
defaultColumns = defaultTraceSelectedColumns.map((e) => ({
...e,
name: e.name,
}));
} else if (dataSource === DataSource.LOGS) {
} else if (sourcePage === SavedviewtypesSourceDTO.logs) {
// eslint-disable-next-line sonarjs/no-identical-functions
defaultColumns = defaultLogsSelectedColumns.map((e) => ({
...e,
@@ -232,7 +233,7 @@ const useOptionsMenu = ({
...initialOptions,
selectColumns: finalSelectColumns,
};
}, [dataSource, initialOptions, initialSelectedColumns]);
}, [sourcePage, initialOptions, initialSelectedColumns]);
const selectedColumnKeys = useMemo(
() => preferences?.columns?.map(({ name }) => name) || [],
@@ -241,7 +242,7 @@ const useOptionsMenu = ({
const optionsFromAttributeKeys = useMemo(() => {
const filteredAttributeKeys = searchedAttributeKeys.filter((item) => {
const exclusions = EXCLUDED_COLUMNS[dataSource];
const exclusions = EXCLUDED_COLUMNS[signal];
if (exclusions) {
return !exclusions.includes(item.name);
}
@@ -249,7 +250,7 @@ const useOptionsMenu = ({
});
return getOptionsFromKeys(filteredAttributeKeys, selectedColumnKeys);
}, [dataSource, searchedAttributeKeys, selectedColumnKeys]);
}, [signal, searchedAttributeKeys, selectedColumnKeys]);
const handleRedirectWithOptionsData = useCallback(
(newQueryData: OptionsQuery) => {
@@ -285,7 +286,10 @@ const useOptionsMenu = ({
buildCompositeKey(f.name, f.fieldContext, f.fieldDataType) !== columnKey,
);
if (!newSelectedColumns?.length && dataSource !== DataSource.LOGS) {
if (
!newSelectedColumns?.length &&
sourcePage !== SavedviewtypesSourceDTO.logs
) {
notifications.error({
message: 'There must be at least one selected column',
});
@@ -294,7 +298,7 @@ const useOptionsMenu = ({
updateColumns(newSelectedColumns || []);
},
[dataSource, notifications, preferences, updateColumns],
[sourcePage, notifications, preferences, updateColumns],
);
const handleFormatChange = useCallback(

View File

@@ -112,7 +112,7 @@ export function Formula({
);
return (
<Row gutter={[0, 15]} data-testid={`formula-${formula.queryName}`}>
<Row gutter={[0, 15]}>
<QBEntityOptions
isCollapsed={isCollapse}
showFunctions={false}
@@ -130,7 +130,6 @@ export function Formula({
<Input.TextArea
name="expression"
className="formula-expression"
data-testid="formula-expression"
onChange={handleChange}
size="middle"
value={formula.expression}
@@ -142,7 +141,6 @@ export function Formula({
<Input
name="legend"
className="formula-legend"
data-testid="formula-legend"
onChange={handleChange}
size="middle"
value={formula.legend}

View File

@@ -98,7 +98,6 @@ export default function QBEntityOptions({
value="search"
className="periscope-btn collapse"
onClick={onCollapseEntity}
data-testid="qb-entity-collapse"
>
{isCollapsed ? <ChevronRight size={16} /> : <ChevronDown size={16} />}
</Button>
@@ -109,7 +108,6 @@ export default function QBEntityOptions({
className="periscope-btn visibility-toggle"
onClick={onToggleVisibility}
disabled={isRawQuery && !showTraceOperator}
data-testid="qb-entity-visibility"
>
{entityData.disabled ? <EyeOff size={16} /> : <Eye size={16} />}
</Button>
@@ -117,11 +115,7 @@ export default function QBEntityOptions({
{entityType === 'query' && showCloneOption && (
<Tooltip title={`Clone Query ${entityData.queryName}`}>
<Button
className={cx('periscope-btn')}
onClick={handleCloneEntity}
data-testid="qb-entity-clone"
>
<Button className={cx('periscope-btn')} onClick={handleCloneEntity}>
<Copy size={14} />
</Button>
</Tooltip>
@@ -137,7 +131,6 @@ export default function QBEntityOptions({
: '',
isLogsExplorerPage && lastUsedQuery === index ? 'sync-btn' : '',
)}
data-testid="qb-entity-name"
>
{entityData.queryName}
</Button>
@@ -192,11 +185,7 @@ export default function QBEntityOptions({
</div>
{showDeleteButton && !isRawQuery && (
<Button
className="periscope-btn ghost"
onClick={onDelete}
data-testid="qb-entity-delete"
>
<Button className="periscope-btn ghost" onClick={onDelete}>
<Trash2 size={14} />
</Button>
)}

View File

@@ -1,10 +1,9 @@
import { useState } from 'react';
import { act, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Button } from '@signozhq/ui/button';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import ROUTES from 'constants/routes';
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
import { act, screen, userEvent, waitFor } from 'tests/test-utils';
import SavedViewsHeader from '../SavedViewsHeader';
import { mockSavedViewsApi } from './savedViewsApiMock';
@@ -28,7 +27,7 @@ const errors = {
};
function Harness(): JSX.Element {
const { traces } = usePreferenceContext();
const traces = usePreferenceContext()[SavedviewtypesSourceDTO.traces];
const [headerKey, setHeaderKey] = useState(0);
const columns = traces.preferences?.columns ?? [];
@@ -37,7 +36,7 @@ function Harness(): JSX.Element {
<SavedViewsHeader
key={headerKey}
source={SavedviewtypesSourceDTO.traces}
onOpenViews={jest.fn()}
onOpenViews={jest.fn() as jest.MockedFunction<() => void>}
/>
<span data-testid="columns">
{columns.map((column) => column.name).join(',')}
@@ -84,13 +83,14 @@ describe('SavedViewsHeader columns', () => {
});
it('keeps edited columns when the view is fetched again', async () => {
const user = userEvent.setup();
mockSavedViewsApi([errors]);
await openView();
await userEvent.click(screen.getByTestId('add-column'));
await user.click(screen.getByTestId('add-column'));
await waitFor(() => expect(isDirty()).toBe(true));
await userEvent.click(screen.getByTestId('remount-header'));
await user.click(screen.getByTestId('remount-header'));
await act(() => new Promise((resolve) => setTimeout(resolve, 200)));
expect(columnsText()).toBe('service.name,name,extra-2');
@@ -98,35 +98,37 @@ describe('SavedViewsHeader columns', () => {
});
it('discard puts the saved columns back', async () => {
const user = userEvent.setup();
mockSavedViewsApi([errors]);
await openView();
await userEvent.click(screen.getByTestId('add-column'));
await user.click(screen.getByTestId('add-column'));
await waitFor(() => expect(isDirty()).toBe(true));
await userEvent.click(screen.getByTestId('saved-views-discard'));
await user.click(screen.getByTestId('saved-views-discard'));
await waitFor(() => expect(columnsText()).toBe('service.name,name'));
expect(isDirty()).toBe(false);
});
it('discard after an update goes back to the updated columns', async () => {
const user = userEvent.setup();
mockSavedViewsApi([errors]);
await openView();
await userEvent.click(screen.getByTestId('add-column'));
await user.click(screen.getByTestId('add-column'));
await waitFor(() => expect(isDirty()).toBe(true));
await userEvent.click(screen.getByTestId('saved-views-save-changes'));
await user.click(screen.getByTestId('saved-views-save-changes'));
const update = await screen.findByTestId(
'saved-views-save-changes-item-update',
);
await waitFor(() => expectRowUsable(update), MENU_CHECK_TIMEOUT);
await userEvent.click(update);
await user.click(update);
await waitFor(() => expect(isDirty()).toBe(false));
await userEvent.click(screen.getByTestId('add-column'));
await user.click(screen.getByTestId('add-column'));
await waitFor(() => expect(isDirty()).toBe(true));
await userEvent.click(screen.getByTestId('saved-views-discard'));
await user.click(screen.getByTestId('saved-views-discard'));
await waitFor(() => expect(columnsText()).toBe('service.name,name,extra-2'));
expect(isDirty()).toBe(false);

View File

@@ -1,28 +1,16 @@
import { Copy, Link, PenLine, Trash2 } from '@signozhq/icons';
import {
SavedviewtypesSchemaVersionDTO,
SavedviewtypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { SavedviewtypesSchemaVersionDTO } from 'api/generated/services/sigNoz.schemas';
import { QueryParams } from 'constants/query';
import ROUTES from 'constants/routes';
import {
buildSavedViewDeletePermission,
buildSavedViewUpdatePermission,
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import { DataSource } from 'types/common/queryBuilder';
import { SavedViewRowActionConfig, SaveViewModalMode } from './types';
export const SAVED_VIEW_SCHEMA_VERSION = SavedviewtypesSchemaVersionDTO.v2;
// Only the logs and traces explorers have columns and formatting to save.
export const SAVED_VIEW_OPTIONS_DATA_SOURCE: Partial<
Record<SavedviewtypesSourceDTO, DataSource>
> = {
[SavedviewtypesSourceDTO.logs]: DataSource.LOGS,
[SavedviewtypesSourceDTO.traces]: DataSource.TRACES,
};
// What selecting a view writes to the url, so clearing it removes exactly these.
export const SAVED_VIEW_URL_PARAMS = [
QueryParams.viewKey,

View File

@@ -8,10 +8,9 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
import { buildSavedViewReadPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import { useAuthZ } from 'lib/authz/hooks/useAuthZ/useAuthZ';
import { DataSource } from 'types/common/queryBuilder';
import { isPreferenceSourcePage } from 'providers/preferences/utils';
import { toAPIError } from 'utils/errorUtils';
import { SAVED_VIEW_OPTIONS_DATA_SOURCE } from '../constants';
import { UseActiveSavedViewResult } from '../types';
import { hasUnsavedViewChanges } from '../utils/hasUnsavedViewChanges';
@@ -21,9 +20,9 @@ export function useActiveSavedView(
const { viewKey } = useGetSavedViewParams();
const { stagedQuery, panelType } = useQueryBuilder();
const optionsDataSource = SAVED_VIEW_OPTIONS_DATA_SOURCE[source];
const hasOptions = isPreferenceSourcePage(source);
const { options } = useOptionsMenu({
dataSource: optionsDataSource ?? DataSource.LOGS,
sourcePage: hasOptions ? source : SavedviewtypesSourceDTO.logs,
});
const { isLoading: isCheckingRead, deniedPermissions } = useAuthZ(
@@ -63,7 +62,7 @@ export function useActiveSavedView(
view,
stagedQuery,
panelType: panelType ?? PANEL_TYPES.LIST,
options: optionsDataSource ? options : undefined,
options: hasOptions ? options : undefined,
});
}, [
view,
@@ -71,7 +70,7 @@ export function useActiveSavedView(
isStagedQueryCurrent,
stagedQuery,
panelType,
optionsDataSource,
hasOptions,
options,
]);

View File

@@ -20,13 +20,12 @@ import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useGetSavedViewParams } from 'hooks/saveViews/useGetSavedViewParams';
import { useHandleExplorerTabChange } from 'hooks/useHandleExplorerTabChange';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { usePreferenceContext } from 'providers/preferences/context/PreferenceContextProvider';
import { DataSource } from 'types/common/queryBuilder';
import { usePreferenceSlice } from 'providers/preferences/context/usePreferenceSlice';
import { isPreferenceSourcePage } from 'providers/preferences/utils';
import { toAPIError } from 'utils/errorUtils';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import {
SAVED_VIEW_OPTIONS_DATA_SOURCE,
SAVED_VIEW_SCHEMA_VERSION,
SAVED_VIEW_TOAST_POSITION,
SAVED_VIEW_URL_PARAMS,
@@ -60,15 +59,11 @@ export function useSavedViewActions(
const { viewKey } = useGetSavedViewParams();
const logSavedViewEvent = useSavedViewLogEvent(source);
const optionsDataSource = SAVED_VIEW_OPTIONS_DATA_SOURCE[source];
const hasOptions = isPreferenceSourcePage(source);
const { options } = useOptionsMenu({
dataSource: optionsDataSource ?? DataSource.LOGS,
sourcePage: hasOptions ? source : SavedviewtypesSourceDTO.logs,
});
const preferences = usePreferenceContext();
const preferencesSlice =
optionsDataSource === DataSource.TRACES
? preferences.traces
: preferences.logs;
const preferenceSlice = usePreferenceSlice(source);
const { mutateAsync: createSavedView, isLoading: isCreating } =
useCreateSavedView();
@@ -86,10 +81,10 @@ export function useSavedViewActions(
query: stagedQuery ?? currentQuery,
panelType: panelType ?? PANEL_TYPES.LIST,
displayName,
options: optionsDataSource ? options : undefined,
options: hasOptions ? options : undefined,
color,
}),
[stagedQuery, currentQuery, panelType, optionsDataSource, options],
[stagedQuery, currentQuery, panelType, hasOptions, options],
);
const selectView = useCallback(
@@ -105,14 +100,14 @@ export function useSavedViewActions(
const revertView = useCallback(
(view: SavedviewtypesSavedViewDTO): void => {
if (optionsDataSource) {
if (preferenceSlice) {
const { columns, formatting } = getViewColumnsAndFormatting(
view.spec,
optionsDataSource,
source,
);
preferencesSlice.updateColumns(columns);
preferenceSlice.updateColumns(columns);
if (formatting) {
preferencesSlice.updateFormatting(formatting);
preferenceSlice.updateFormatting(formatting);
}
}
selectView(view);
@@ -120,7 +115,7 @@ export function useSavedViewActions(
[SavedViewEventKeys.ViewId]: view.id,
});
},
[optionsDataSource, preferencesSlice, selectView, logSavedViewEvent],
[source, preferenceSlice, selectView, logSavedViewEvent],
);
// The query builder redirects only ever add params, so the url is rebuilt

View File

@@ -1,4 +1,7 @@
import { SavedviewtypesSavedViewSpecDTO } from 'api/generated/services/sigNoz.schemas';
import {
SavedviewtypesSavedViewSpecDTO,
SavedviewtypesSourceDTO,
} from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'api/v5/v5';
import {
defaultLogsSelectedColumns,
@@ -7,7 +10,6 @@ import {
} from 'container/OptionsMenu/constants';
import { FontSize, LogViewMode } from 'container/OptionsMenu/types';
import { Preferences } from 'providers/preferences/types';
import { DataSource } from 'types/common/queryBuilder';
function withColumnNames(
columns: TelemetryFieldKey[] | undefined,
@@ -25,11 +27,11 @@ function withColumnNames(
// defaults filled in where the view has none.
export function getViewColumnsAndFormatting(
spec: SavedviewtypesSavedViewSpecDTO | undefined,
dataSource: DataSource,
sourcePage: SavedviewtypesSourceDTO,
): Preferences {
const selectedFields = spec?.selectedFields as TelemetryFieldKey[] | undefined;
if (dataSource === DataSource.LOGS) {
if (sourcePage === SavedviewtypesSourceDTO.logs) {
return {
columns: ensureLogsRequiredColumns(
withColumnNames(selectedFields) || defaultLogsSelectedColumns,
@@ -42,7 +44,7 @@ export function getViewColumnsAndFormatting(
},
};
}
if (dataSource === DataSource.TRACES) {
if (sourcePage === SavedviewtypesSourceDTO.traces) {
return { columns: selectedFields || defaultTraceSelectedColumns };
}
return { columns: [] };

View File

@@ -7,6 +7,7 @@ import { HasUnsavedViewChangesArgs } from '../types';
import { getSavedViewQuery } from './getSavedViewQuery';
import { toSavedViewPanelType } from './toSavedViewSpec';
import { getViewColumnsAndFormatting } from './getViewColumnsAndFormatting';
import { toSavedViewSource } from './toSavedViewSource';
// Legacy context names the server stores under their v5 name.
const FIELD_CONTEXT_ALIASES: Record<string, TelemetrytypesFieldContextDTO> = {
@@ -79,7 +80,7 @@ export function hasUnsavedViewChanges({
const dataSource = stagedQuery.builder.queryData[0]?.dataSource;
const { columns, formatting } = getViewColumnsAndFormatting(
view.spec,
dataSource,
toSavedViewSource(dataSource),
);
const toNames = (fields: { name?: string; key?: string }[]): unknown[] =>
fields.map((field) => field.name ?? field.key);

View File

@@ -3,11 +3,8 @@ import { DataSource } from 'types/common/queryBuilder';
import { SavedViewSourcePage } from '../types';
// Explorers and the preferences module are keyed by DataSource (the signal),
// the api keys views by source page. Same values today, so this is the one
// place they meet. AI observability views will come with their own source and
// DataSource cannot tell them apart from traces, so preferences should move to
// source page at that point and this map goes with it.
// Queries and the AI assistant name a source by DataSource (the signal), the
// api keys views by source page.
const SAVED_VIEW_SOURCE: Record<SavedViewSourcePage, SavedviewtypesSourceDTO> =
{
[DataSource.LOGS]: SavedviewtypesSourceDTO.logs,

View File

@@ -11,6 +11,7 @@ import {
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import logEvent from 'api/common/logEvent';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
import ListViewOrderBy from 'components/OrderBy/ListViewOrderBy';
import type { TableColumnDef } from 'components/TanStackTableView/types';
@@ -86,7 +87,7 @@ function ListView({
const { options, config } = useOptionsMenu({
storageKey: LOCALSTORAGE.TRACES_LIST_OPTIONS,
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
aggregateOperator: 'count',
initialOptions: {
selectColumns: defaultSelectedColumns,

View File

@@ -1,10 +1,8 @@
import {
RuletypesAlertStateDTO,
RuletypesAlertTypeDTO,
RuletypesEvaluationRollingDTOKind,
RuletypesPanelTypeDTO,
RuletypesQueryTypeDTO,
RuletypesRuleDTOSchemaVersion,
RuletypesRuleTypeDTO,
} from 'api/generated/services/sigNoz.schemas';
import type {
@@ -40,12 +38,6 @@ const make = (
evalWindow: '5m0s',
frequency: '1m0s',
ruleType: RuletypesRuleTypeDTO.threshold_rule,
schemaVersion: RuletypesRuleDTOSchemaVersion.v2alpha1,
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: '5m0s', frequency: '1m0s' },
},
notificationSettings: { usePolicy: false, renotify: { enabled: false } },
...overrides,
});

View File

@@ -18,7 +18,6 @@ import {
RuletypesMatchTypeDTO,
RuletypesPanelTypeDTO,
RuletypesQueryTypeDTO,
RuletypesRuleDTOSchemaVersion,
RuletypesRuleTypeDTO,
RuletypesSeasonalityDTO,
RuletypesThresholdBasicDTOKind,
@@ -35,6 +34,7 @@ import {
type AlertmanagertypesGettableNotificationChannelDTO,
type AlertmanagertypesListedNotificationChannelDTO,
} from 'api/generated/services/sigNoz.schemas';
import { NEW_ALERT_SCHEMA_VERSION } from 'types/api/alerts/alertTypesV2';
const MINUTE = 60 * 1000;
const HOUR = 60 * MINUTE;
@@ -388,18 +388,18 @@ const buildRule = (index: number, shape: RuleShape): RuletypesRuleDTO => {
},
evalWindow: isAnomaly ? '1h0m0s' : '5m0s',
frequency: '1m0s',
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: isAnomaly ? '1h0m0s' : '5m0s', frequency: '1m0s' },
},
...(isAnomaly && {
evaluation: {
kind: RuletypesEvaluationRollingDTOKind.rolling,
spec: { evalWindow: '1h0m0s', frequency: '1m0s' },
},
}),
createdAt: ago((index + 3) * DAY),
updatedAt: ago((index + 1) * HOUR),
createdBy: 'ada@signoz.io',
updatedBy: 'grace@signoz.io',
// classic rows predate schemaVersion, which the spec now requires
schemaVersion: (shape.schema === 'classic'
? undefined
: RuletypesRuleDTOSchemaVersion.v2alpha1) as RuletypesRuleDTOSchemaVersion,
schemaVersion:
shape.schema === 'classic' ? undefined : NEW_ALERT_SCHEMA_VERSION,
version: 'v5',
source: 'http://localhost/alerts',
preferredChannels: ['ops-slack'],

View File

@@ -166,10 +166,7 @@ function PanelEditorQueryBuilder({
return modes.map((queryType) => ({
key: queryType,
label: (
<div
className={styles.queryTypeTab}
data-testid={`query-type-tab-${queryType}`}
>
<div className={styles.queryTypeTab}>
{queryTypeComponents[queryType].icon}
<Typography>{queryTypeComponents[queryType].label}</Typography>
</div>

View File

@@ -73,7 +73,7 @@ function TracesExplorer(): JSX.Element {
const { options } = useOptionsMenu({
storageKey: LOCALSTORAGE.TRACES_LIST_OPTIONS,
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
aggregateOperator: 'noop',
initialOptions: {
selectColumns: defaultSelectedColumns,

View File

@@ -1,15 +1,15 @@
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'api/v5/v5';
import { LOCALSTORAGE } from 'constants/localStorage';
import { LogViewMode } from 'container/OptionsMenu/types';
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
import {
defaultLogsSelectedColumns,
defaultTraceSelectedColumns,
} from 'container/OptionsMenu/constants';
import { FontSize } from 'container/OptionsMenu/types';
import { render, screen, userEvent } from 'tests/test-utils';
import { DataSource } from 'types/common/queryBuilder';
import { usePreferenceContext } from '../context/PreferenceContextProvider';
import { PreferenceSourcePage } from '../types';
const ROUTE_LOGS = '/logs';
const ROUTE_TRACES = '/traces';
@@ -38,14 +38,13 @@ function getLocalStorageJSON<T>(key: string): T | null {
}
function Consumer({
dataSource,
sourcePage,
testIdPrefix,
}: {
dataSource: DataSource;
sourcePage: PreferenceSourcePage;
testIdPrefix: string;
}): JSX.Element {
const ctx = usePreferenceContext();
const slice = dataSource === DataSource.TRACES ? ctx.traces : ctx.logs;
const slice = usePreferenceContext()[sourcePage];
return (
<div>
@@ -58,7 +57,7 @@ function Consumer({
type="button"
onClick={(): void => {
const newCols: TelemetryFieldKey[] =
dataSource === DataSource.TRACES
sourcePage === SavedviewtypesSourceDTO.traces
? (defaultTraceSelectedColumns.slice(0, 1) as TelemetryFieldKey[])
: (defaultLogsSelectedColumns.slice(0, 1) as TelemetryFieldKey[]);
slice.updateColumns(newCols);
@@ -78,7 +77,10 @@ describe('PreferencesProvider integration', () => {
describe('Logs', () => {
it('loads defaults when no localStorage or url provided', () => {
render(
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.logs}
testIdPrefix={TESTID_LOGS}
/>,
undefined,
{
initialRoute: ROUTE_LOGS,
@@ -101,7 +103,10 @@ describe('PreferencesProvider integration', () => {
});
render(
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.logs}
testIdPrefix={TESTID_LOGS}
/>,
undefined,
{
initialRoute: ROUTE_LOGS,
@@ -116,7 +121,10 @@ describe('PreferencesProvider integration', () => {
it('direct mode updateColumns persists to localStorage', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.logs}
testIdPrefix={TESTID_LOGS}
/>,
undefined,
{
initialRoute: ROUTE_LOGS,
@@ -142,7 +150,7 @@ describe('PreferencesProvider integration', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<Consumer dataSource={DataSource.LOGS} testIdPrefix="logs" />,
<Consumer sourcePage={SavedviewtypesSourceDTO.logs} testIdPrefix="logs" />,
undefined,
{
initialRoute: initialEntry,
@@ -175,7 +183,10 @@ describe('PreferencesProvider integration', () => {
});
render(
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.logs}
testIdPrefix={TESTID_LOGS}
/>,
undefined,
{
initialRoute: ROUTE_LOGS,
@@ -197,7 +208,7 @@ describe('PreferencesProvider integration', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
function FormattingConsumer(): JSX.Element {
const { logs } = usePreferenceContext();
const logs = usePreferenceContext()[SavedviewtypesSourceDTO.logs];
return (
<button
data-testid="logs-update-formatting"
@@ -235,7 +246,10 @@ describe('PreferencesProvider integration', () => {
const initialEntry = `/logs?viewKey=${encodeURIComponent(viewKey)}`;
render(
<Consumer dataSource={DataSource.LOGS} testIdPrefix={TESTID_LOGS} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.logs}
testIdPrefix={TESTID_LOGS}
/>,
undefined,
{ initialRoute: initialEntry },
);
@@ -254,7 +268,10 @@ describe('PreferencesProvider integration', () => {
describe('Traces', () => {
it('loads defaults when no localStorage or url provided', () => {
render(
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.traces}
testIdPrefix={TESTID_TRACES}
/>,
undefined,
{
initialRoute: ROUTE_TRACES,
@@ -273,7 +290,10 @@ describe('PreferencesProvider integration', () => {
});
render(
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.traces}
testIdPrefix={TESTID_TRACES}
/>,
undefined,
{
initialRoute: ROUTE_TRACES,
@@ -286,7 +306,10 @@ describe('PreferencesProvider integration', () => {
it('direct mode updateColumns persists to localStorage', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.traces}
testIdPrefix={TESTID_TRACES}
/>,
undefined,
{
initialRoute: ROUTE_TRACES,
@@ -309,7 +332,10 @@ describe('PreferencesProvider integration', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
render(
<Consumer dataSource={DataSource.TRACES} testIdPrefix="traces" />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.traces}
testIdPrefix="traces"
/>,
undefined,
{
initialRoute: initialEntry,
@@ -338,7 +364,10 @@ describe('PreferencesProvider integration', () => {
});
render(
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.traces}
testIdPrefix={TESTID_TRACES}
/>,
undefined,
{ initialRoute: ROUTE_TRACES },
);
@@ -355,7 +384,7 @@ describe('PreferencesProvider integration', () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
function TracesFormattingConsumer(): JSX.Element {
const { traces } = usePreferenceContext();
const traces = usePreferenceContext()[SavedviewtypesSourceDTO.traces];
return (
<button
data-testid="traces-update-formatting"
@@ -390,7 +419,10 @@ describe('PreferencesProvider integration', () => {
const initialEntry = `/traces?viewKey=${encodeURIComponent(viewKey)}`;
render(
<Consumer dataSource={DataSource.TRACES} testIdPrefix={TESTID_TRACES} />,
<Consumer
sourcePage={SavedviewtypesSourceDTO.traces}
testIdPrefix={TESTID_TRACES}
/>,
undefined,
{ initialRoute: initialEntry },
);

View File

@@ -1,6 +1,9 @@
import { renderHook, waitFor } from '@testing-library/react';
import { Dispatch, SetStateAction } from 'react';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { defaultLogsSelectedColumns } from 'container/OptionsMenu/constants';
import { DataSource } from 'types/common/queryBuilder';
import { FontSize } from 'container/OptionsMenu/types';
import { renderHook, waitFor } from 'tests/test-utils';
import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';
import logsLoaderConfig from '../configs/logsLoaderConfig';
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
@@ -42,15 +45,18 @@ jest.mock('../configs/tracesLoaderConfig', () => ({
}));
describe('usePreferenceLoader', () => {
const setReSync = jest.fn() as jest.MockedFunction<
Dispatch<SetStateAction<boolean>>
>;
beforeEach(() => {
jest.clearAllMocks();
});
it('should load logs preferences based on priority order', async () => {
const setReSync = jest.fn();
const { result } = renderHook(() =>
usePreferenceLoader({
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
reSync: false,
setReSync,
}),
@@ -71,10 +77,9 @@ describe('usePreferenceLoader', () => {
});
it('should load traces preferences', async () => {
const setReSync = jest.fn();
const { result } = renderHook(() =>
usePreferenceLoader({
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
reSync: false,
setReSync,
}),
@@ -93,13 +98,11 @@ describe('usePreferenceLoader', () => {
});
it('should call setReSync when reSync is true', async () => {
const setReSync = jest.fn();
// Test that the hook calls setReSync(false) when reSync is true
// We'll unmount quickly to avoid the infinite loop
const { unmount } = renderHook(() =>
usePreferenceLoader({
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
reSync: true,
setReSync,
}),
@@ -118,19 +121,25 @@ describe('usePreferenceLoader', () => {
it('should handle errors during loading', async () => {
// Make first call succeed (initial state), second call throw in reSync effect
const localSpy: jest.SpyInstance = jest.spyOn(logsLoaderConfig, 'local');
const localSpy = jest.spyOn(logsLoaderConfig, 'local');
// The loader reads stored columns by name, though `local()` types them as
// the older key-based shape.
localSpy.mockImplementationOnce(() => ({
columns: [{ name: 'local-column' }],
formatting: { maxLines: 5, format: 'table', fontSize: 'medium', version: 1 },
columns: [{ name: 'local-column' }] as unknown as BaseAutocompleteData[],
formatting: {
maxLines: 5,
format: 'table',
fontSize: FontSize.MEDIUM,
version: 1,
},
}));
localSpy.mockImplementationOnce(() => {
throw new Error('Loading failed');
});
const setReSync = jest.fn();
const { result } = renderHook(() =>
usePreferenceLoader({
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
reSync: true,
setReSync,
}),

View File

@@ -1,4 +1,3 @@
import { renderHook } from '@testing-library/react';
import { useGetSavedView } from 'api/generated/services/saved-view';
import {
SavedviewtypesSavedViewDTO,
@@ -9,32 +8,21 @@ import {
defaultTraceSelectedColumns,
ensureLogsRequiredColumns,
} from 'container/OptionsMenu/constants';
import { DataSource } from 'types/common/queryBuilder';
import { renderHook } from 'tests/test-utils';
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
import { usePreferenceSync } from '../sync/usePreferenceSync';
import { PreferenceMode } from '../types';
import { PreferenceMode, Preferences } from '../types';
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
jest.mock('api/generated/services/saved-view');
const loaderPreferences = { columns: [{ name: 'from-loader' }] };
jest.mock('../loader/usePreferenceLoader', () => ({
usePreferenceLoader: jest.fn(() => ({
preferences: loaderPreferences,
loading: false,
error: null,
})),
}));
jest.mock('../loader/usePreferenceLoader');
jest.mock('../updater/usePreferenceUpdater');
jest.mock('../updater/usePreferenceUpdater', () => ({
usePreferenceUpdater: jest.fn(() => ({
updateColumns: jest.fn(),
updateFormatting: jest.fn(),
})),
}));
const loaderPreferences: Preferences = { columns: [{ name: 'from-loader' }] };
const mockedUseGetSavedView = useGetSavedView as jest.MockedFunction<
typeof useGetSavedView
>;
const mockedUseGetSavedView = jest.mocked(useGetSavedView);
function makeView(
id: string,
@@ -76,6 +64,19 @@ function mockViews(views: SavedviewtypesSavedViewDTO[]): void {
describe('usePreferenceSync in saved view mode', () => {
beforeEach(() => {
mockedUseGetSavedView.mockReset();
jest.mocked(usePreferenceLoader).mockReturnValue({
preferences: loaderPreferences,
loading: false,
error: null,
});
jest.mocked(usePreferenceUpdater).mockReturnValue({
updateColumns: jest.fn() as jest.MockedFunction<
ReturnType<typeof usePreferenceUpdater>['updateColumns']
>,
updateFormatting: jest.fn() as jest.MockedFunction<
ReturnType<typeof usePreferenceUpdater>['updateFormatting']
>,
});
});
it('fetches the view only in saved view mode with a view id', () => {
@@ -84,7 +85,7 @@ describe('usePreferenceSync in saved view mode', () => {
renderHook(() =>
usePreferenceSync({
mode: PreferenceMode.DIRECT,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
savedViewId: undefined,
}),
);
@@ -101,7 +102,7 @@ describe('usePreferenceSync in saved view mode', () => {
const { result } = renderHook(() =>
usePreferenceSync({
mode: PreferenceMode.DIRECT,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
savedViewId: undefined,
}),
);
@@ -120,7 +121,7 @@ describe('usePreferenceSync in saved view mode', () => {
const { result } = renderHook(() =>
usePreferenceSync({
mode: PreferenceMode.SAVED_VIEW,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
savedViewId: 'view-1',
}),
);
@@ -147,7 +148,7 @@ describe('usePreferenceSync in saved view mode', () => {
const { result } = renderHook(() =>
usePreferenceSync({
mode: PreferenceMode.SAVED_VIEW,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
savedViewId: 'view-1',
}),
);
@@ -174,14 +175,14 @@ describe('usePreferenceSync in saved view mode', () => {
const withFields = renderHook(() =>
usePreferenceSync({
mode: PreferenceMode.SAVED_VIEW,
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
savedViewId: 'with-fields',
}),
);
const withoutFields = renderHook(() =>
usePreferenceSync({
mode: PreferenceMode.SAVED_VIEW,
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
savedViewId: 'without-fields',
}),
);
@@ -202,7 +203,7 @@ describe('usePreferenceSync in saved view mode', () => {
const { result } = renderHook(() =>
usePreferenceSync({
mode: PreferenceMode.SAVED_VIEW,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
savedViewId: 'missing',
}),
);

View File

@@ -1,45 +1,39 @@
import { act } from 'react-dom/test-utils';
import { renderHook } from '@testing-library/react';
import { Dispatch, SetStateAction } from 'react';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'api/v5/v5';
import { LogViewMode } from 'container/OptionsMenu/types';
import { FontSize } from 'container/OptionsMenu/types';
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
import useUrlQueryData from 'hooks/useUrlQueryData';
import {
FormattingOptions,
PreferenceMode,
Preferences,
} from 'providers/preferences/types';
import { act, renderHook } from 'tests/test-utils';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import { DataSource } from 'types/common/queryBuilder';
import getLogsUpdaterConfig from '../configs/logsUpdaterConfig';
import getTracesUpdaterConfig from '../configs/tracesUpdaterConfig';
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
// Mock the config updaters
const mockUpdateColumns = jest.fn();
const mockUpdateFormatting = jest.fn();
jest.mock('../configs/logsUpdaterConfig');
jest.mock('../configs/tracesUpdaterConfig');
jest.mock('hooks/useUrlQueryData');
jest.mock('../configs/logsUpdaterConfig', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
})),
}));
type LogsUpdater = ReturnType<typeof getLogsUpdaterConfig>;
type TracesUpdater = ReturnType<typeof getTracesUpdaterConfig>;
jest.mock('../configs/tracesUpdaterConfig', () => ({
__esModule: true,
default: jest.fn().mockImplementation(() => ({
updateColumns: mockUpdateColumns,
updateFormatting: mockUpdateFormatting,
})),
}));
// Mock the URL query hook
jest.mock('hooks/useUrlQueryData', () => ({
__esModule: true,
default: jest.fn().mockReturnValue({
redirectWithQuery: jest.fn(),
}),
}));
const mockLogsUpdateColumns = jest.fn() as jest.MockedFunction<
LogsUpdater['updateColumns']
>;
const mockLogsUpdateFormatting = jest.fn() as jest.MockedFunction<
LogsUpdater['updateFormatting']
>;
const mockTracesUpdateColumns = jest.fn() as jest.MockedFunction<
TracesUpdater['updateColumns']
>;
const mockTracesUpdateFormatting = jest.fn() as jest.MockedFunction<
TracesUpdater['updateFormatting']
>;
describe('usePreferenceUpdater', () => {
const mockPreferences: Preferences = {
@@ -51,18 +45,36 @@ describe('usePreferenceUpdater', () => {
version: 1,
},
};
const setReSync = jest.fn() as jest.MockedFunction<
Dispatch<SetStateAction<boolean>>
>;
const setSavedViewPreferences = jest.fn() as jest.MockedFunction<
Dispatch<SetStateAction<Preferences | null>>
>;
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(getLogsUpdaterConfig).mockReturnValue({
updateColumns: mockLogsUpdateColumns,
updateFormatting: mockLogsUpdateFormatting,
});
jest.mocked(getTracesUpdaterConfig).mockReturnValue({
updateColumns: mockTracesUpdateColumns,
updateFormatting: mockTracesUpdateFormatting,
});
jest.mocked(useUrlQueryData).mockReturnValue({
query: null,
queryData: undefined,
redirectWithQuery: jest.fn() as jest.MockedFunction<
(newQueryData: unknown) => void
>,
});
});
it('should return updateColumns and updateFormatting functions', () => {
const setReSync = jest.fn();
const setSavedViewPreferences = jest.fn();
const { result } = renderHook(() =>
usePreferenceUpdater({
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
mode: PreferenceMode.DIRECT,
preferences: mockPreferences,
setReSync,
@@ -75,9 +87,7 @@ describe('usePreferenceUpdater', () => {
expect(typeof result.current.updateFormatting).toBe('function');
});
it('should call the logs updater for updateColumns with logs dataSource', () => {
const setReSync = jest.fn();
const setSavedViewPreferences = jest.fn();
it('should call the logs updater for updateColumns with the logs list key', () => {
const newColumns: TelemetryFieldKey[] = [
{
name: 'new-column',
@@ -88,7 +98,7 @@ describe('usePreferenceUpdater', () => {
const { result } = renderHook(() =>
usePreferenceUpdater({
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
mode: PreferenceMode.DIRECT,
preferences: mockPreferences,
setReSync,
@@ -101,16 +111,15 @@ describe('usePreferenceUpdater', () => {
});
// Should call the logs updater
expect(mockUpdateColumns).toHaveBeenCalledWith(
expect(mockLogsUpdateColumns).toHaveBeenCalledWith(
newColumns,
PreferenceMode.DIRECT,
);
expect(mockTracesUpdateColumns).not.toHaveBeenCalled();
expect(setReSync).toHaveBeenCalledWith(true);
});
it('should call the logs updater for updateFormatting with logs dataSource', () => {
const setReSync = jest.fn();
const setSavedViewPreferences = jest.fn();
it('should call the logs updater for updateFormatting with the logs list key', () => {
const newFormatting: FormattingOptions = {
maxLines: 10,
format: 'table' as LogViewMode,
@@ -120,7 +129,7 @@ describe('usePreferenceUpdater', () => {
const { result } = renderHook(() =>
usePreferenceUpdater({
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
mode: PreferenceMode.DIRECT,
preferences: mockPreferences,
setReSync,
@@ -133,16 +142,15 @@ describe('usePreferenceUpdater', () => {
});
// Should call the logs updater
expect(mockUpdateFormatting).toHaveBeenCalledWith(
expect(mockLogsUpdateFormatting).toHaveBeenCalledWith(
newFormatting,
PreferenceMode.DIRECT,
);
expect(mockTracesUpdateFormatting).not.toHaveBeenCalled();
expect(setReSync).toHaveBeenCalledWith(true);
});
it('should call the traces updater for updateColumns with traces dataSource', () => {
const setReSync = jest.fn();
const setSavedViewPreferences = jest.fn();
it('should call the traces updater for updateColumns with the traces list key', () => {
const newColumns: TelemetryFieldKey[] = [
{
name: 'new-trace-column',
@@ -153,7 +161,7 @@ describe('usePreferenceUpdater', () => {
const { result } = renderHook(() =>
usePreferenceUpdater({
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
mode: PreferenceMode.DIRECT,
preferences: mockPreferences,
setReSync,
@@ -166,16 +174,15 @@ describe('usePreferenceUpdater', () => {
});
// Should call the traces updater
expect(mockUpdateColumns).toHaveBeenCalledWith(
expect(mockTracesUpdateColumns).toHaveBeenCalledWith(
newColumns,
PreferenceMode.DIRECT,
);
expect(mockLogsUpdateColumns).not.toHaveBeenCalled();
expect(setReSync).toHaveBeenCalledWith(true);
});
it('should call the traces updater for updateFormatting with traces dataSource', () => {
const setReSync = jest.fn();
const setSavedViewPreferences = jest.fn();
it('should call the traces updater for updateFormatting with the traces list key', () => {
const newFormatting: FormattingOptions = {
maxLines: 10,
format: 'table' as LogViewMode,
@@ -185,7 +192,7 @@ describe('usePreferenceUpdater', () => {
const { result } = renderHook(() =>
usePreferenceUpdater({
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
mode: PreferenceMode.DIRECT,
preferences: mockPreferences,
setReSync,
@@ -198,20 +205,18 @@ describe('usePreferenceUpdater', () => {
});
// Should call the traces updater
expect(mockUpdateFormatting).toHaveBeenCalledWith(
expect(mockTracesUpdateFormatting).toHaveBeenCalledWith(
newFormatting,
PreferenceMode.DIRECT,
);
expect(mockLogsUpdateFormatting).not.toHaveBeenCalled();
expect(setReSync).toHaveBeenCalledWith(true);
});
it('should increment reSync counter when updates are called', () => {
const setReSync = jest.fn();
const setSavedViewPreferences = jest.fn();
const { result } = renderHook(() =>
usePreferenceUpdater({
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
mode: PreferenceMode.DIRECT,
preferences: mockPreferences,
setReSync,

View File

@@ -0,0 +1,20 @@
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { isPreferenceSourcePage } from '../utils';
describe('isPreferenceSourcePage', () => {
it.each([SavedviewtypesSourceDTO.logs, SavedviewtypesSourceDTO.traces])(
'is true for %s',
(source) => {
expect(isPreferenceSourcePage(source)).toBe(true);
},
);
it.each([
SavedviewtypesSourceDTO.metrics,
SavedviewtypesSourceDTO.meter,
SavedviewtypesSourceDTO.ai_observability,
])('is false for %s', (source) => {
expect(isPreferenceSourcePage(source)).toBe(false);
});
});

View File

@@ -0,0 +1,7 @@
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
// Only the logs and traces explorers keep column and formatting preferences.
export const PREFERENCE_SOURCE_PAGES = [
SavedviewtypesSourceDTO.logs,
SavedviewtypesSourceDTO.traces,
] as const;

View File

@@ -5,12 +5,12 @@ import React, {
useContext,
useMemo,
} from 'react';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import useUrlQuery from 'hooks/useUrlQuery';
import {
PreferenceContextValue,
PreferenceMode,
} from 'providers/preferences/types';
import { DataSource } from 'types/common/queryBuilder';
import { usePreferenceSync } from '../sync/usePreferenceSync';
@@ -38,19 +38,19 @@ export function PreferenceContextProvider({
const logsSlice = usePreferenceSync({
mode: savedViewId ? PreferenceMode.SAVED_VIEW : PreferenceMode.DIRECT,
savedViewId: savedViewId || undefined,
dataSource: DataSource.LOGS,
sourcePage: SavedviewtypesSourceDTO.logs,
});
const tracesSlice = usePreferenceSync({
mode: savedViewId ? PreferenceMode.SAVED_VIEW : PreferenceMode.DIRECT,
savedViewId: savedViewId || undefined,
dataSource: DataSource.TRACES,
sourcePage: SavedviewtypesSourceDTO.traces,
});
const value = useMemo<PreferenceContextValue>(
() => ({
logs: logsSlice,
traces: tracesSlice,
[SavedviewtypesSourceDTO.logs]: logsSlice,
[SavedviewtypesSourceDTO.traces]: tracesSlice,
}),
[logsSlice, tracesSlice],
);

View File

@@ -0,0 +1,12 @@
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { PreferenceSlice } from '../types';
import { isPreferenceSourcePage } from '../utils';
import { usePreferenceContext } from './PreferenceContextProvider';
export function usePreferenceSlice(
sourcePage: SavedviewtypesSourceDTO,
): PreferenceSlice | undefined {
const context = usePreferenceContext();
return isPreferenceSourcePage(sourcePage) ? context[sourcePage] : undefined;
}

View File

@@ -1,12 +1,12 @@
import { useEffect, useState } from 'react';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'api/v5/v5';
import { ensureLogsRequiredColumns } from 'container/OptionsMenu/constants';
import { has } from 'lodash-es';
import { DataSource } from 'types/common/queryBuilder';
import logsLoaderConfig from '../configs/logsLoaderConfig';
import tracesLoaderConfig from '../configs/tracesLoaderConfig';
import { FormattingOptions, Preferences } from '../types';
import { FormattingOptions, Preferences, PreferenceSourcePage } from '../types';
const migrateColumns = (columns: any): any =>
columns.map((column: any) => {
@@ -62,15 +62,21 @@ function logsPreferencesLoader(): {
function tracesPreferencesLoader(): {
columns: TelemetryFieldKey[];
} {
return preferencesLoader(tracesLoaderConfig);
const { columns } = preferencesLoader<Preferences>(tracesLoaderConfig);
return { columns };
}
const PREFERENCE_LOADERS: Record<PreferenceSourcePage, () => Preferences> = {
[SavedviewtypesSourceDTO.logs]: logsPreferencesLoader,
[SavedviewtypesSourceDTO.traces]: tracesPreferencesLoader,
};
export function usePreferenceLoader({
dataSource,
sourcePage,
reSync,
setReSync,
}: {
dataSource: DataSource;
sourcePage: PreferenceSourcePage;
reSync: boolean;
setReSync: (value: boolean) => void;
}): {
@@ -78,17 +84,10 @@ export function usePreferenceLoader({
loading: boolean;
error: Error | null;
} {
const [preferences, setPreferences] = useState<Preferences | null>(() => {
if (dataSource === DataSource.LOGS) {
const { columns, formatting } = logsPreferencesLoader();
return { columns, formatting };
}
if (dataSource === DataSource.TRACES) {
const { columns } = tracesPreferencesLoader();
return { columns };
}
return null;
});
const loadSlicePreferences = PREFERENCE_LOADERS[sourcePage];
const [preferences, setPreferences] = useState<Preferences | null>(
loadSlicePreferences,
);
const [error, setError] = useState<Error | null>(null);
useEffect((): void => {
@@ -96,15 +95,7 @@ export function usePreferenceLoader({
setError(null);
try {
if (dataSource === DataSource.LOGS) {
const { columns, formatting } = logsPreferencesLoader();
setPreferences({ columns, formatting });
}
if (dataSource === DataSource.TRACES) {
const { columns } = tracesPreferencesLoader();
setPreferences({ columns });
}
setPreferences(loadSlicePreferences());
} catch (e) {
setError(e as Error);
} finally {
@@ -119,7 +110,7 @@ export function usePreferenceLoader({
if (reSync) {
loadPreferences();
}
}, [dataSource, reSync, setReSync]);
}, [loadSlicePreferences, reSync, setReSync]);
return { preferences, loading: false, error };
}

View File

@@ -3,19 +3,23 @@ import { useEffect, useRef, useState } from 'react';
import { useGetSavedView } from 'api/generated/services/saved-view';
import { TelemetryFieldKey } from 'api/v5/v5';
import { getViewColumnsAndFormatting } from 'container/SavedViews/utils/getViewColumnsAndFormatting';
import { DataSource } from 'types/common/queryBuilder';
import { usePreferenceLoader } from '../loader/usePreferenceLoader';
import { FormattingOptions, PreferenceMode, Preferences } from '../types';
import {
FormattingOptions,
PreferenceMode,
Preferences,
PreferenceSourcePage,
} from '../types';
import { usePreferenceUpdater } from '../updater/usePreferenceUpdater';
export function usePreferenceSync({
mode,
dataSource,
sourcePage,
savedViewId,
}: {
mode: PreferenceMode;
dataSource: DataSource;
sourcePage: PreferenceSourcePage;
savedViewId: string | undefined;
}): {
preferences: Preferences | null;
@@ -41,25 +45,25 @@ export function usePreferenceSync({
if (view && view.id === savedViewId) {
if (seededViewId.current !== savedViewId) {
seededViewId.current = savedViewId;
setSavedViewPreferences(getViewColumnsAndFormatting(view.spec, dataSource));
setSavedViewPreferences(getViewColumnsAndFormatting(view.spec, sourcePage));
}
return;
}
seededViewId.current = undefined;
setSavedViewPreferences(getViewColumnsAndFormatting(undefined, dataSource));
}, [viewData, dataSource, savedViewId]);
setSavedViewPreferences(getViewColumnsAndFormatting(undefined, sourcePage));
}, [viewData, sourcePage, savedViewId]);
// We are using a reSync state because we have URL updates as well as local storage updates
// and we want to make sure we are always using the latest preferences
const [reSync, setReSync] = useState(false);
const { preferences, loading, error } = usePreferenceLoader({
dataSource,
sourcePage,
reSync,
setReSync,
});
const { updateColumns, updateFormatting } = usePreferenceUpdater({
dataSource,
sourcePage,
mode,
preferences,
setReSync,

View File

@@ -1,12 +1,15 @@
import { TelemetryFieldKey } from 'api/v5/v5';
import { LogViewMode } from 'container/OptionsMenu/types';
import { FontSize } from 'container/OptionsMenu/types';
import { LogViewMode, FontSize } from 'container/OptionsMenu/types';
import { PREFERENCE_SOURCE_PAGES } from '../constants';
export enum PreferenceMode {
SAVED_VIEW = 'savedView',
DIRECT = 'direct',
}
export type PreferenceSourcePage = (typeof PREFERENCE_SOURCE_PAGES)[number];
export interface PreferenceSlice {
preferences: Preferences | null;
loading: boolean;
@@ -15,10 +18,10 @@ export interface PreferenceSlice {
updateFormatting: (newFormatting: FormattingOptions) => void;
}
export interface PreferenceContextValue {
logs: PreferenceSlice;
traces: PreferenceSlice;
}
export type PreferenceContextValue = Record<
PreferenceSourcePage,
PreferenceSlice
>;
export interface FormattingOptions {
maxLines?: number;

View File

@@ -1,4 +1,5 @@
import { Dispatch, SetStateAction } from 'react';
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { TelemetryFieldKey } from 'api/v5/v5';
import {
defaultOptionsQuery,
@@ -6,48 +7,41 @@ import {
} from 'container/OptionsMenu/constants';
import { OptionsQuery } from 'container/OptionsMenu/types';
import useUrlQueryData from 'hooks/useUrlQueryData';
import { DataSource } from 'types/common/queryBuilder';
import getLogsUpdaterConfig from '../configs/logsUpdaterConfig';
import getTracesUpdaterConfig from '../configs/tracesUpdaterConfig';
import { FormattingOptions, Preferences } from '../types';
const metricsUpdater = {
updateColumns: (): void => {}, // no-op for metrics
updateFormatting: (): void => {}, // no-op for metrics
};
import { FormattingOptions, Preferences, PreferenceSourcePage } from '../types';
const getUpdaterConfig = (
preferences: Preferences | null,
redirectWithOptionsData: (options: OptionsQuery) => void,
setSavedViewPreferences: Dispatch<SetStateAction<Preferences | null>>,
): Record<
DataSource,
PreferenceSourcePage,
{
updateColumns: (newColumns: TelemetryFieldKey[], mode: string) => void;
updateFormatting: (newFormatting: FormattingOptions, mode: string) => void;
}
> => ({
[DataSource.LOGS]: getLogsUpdaterConfig(
[SavedviewtypesSourceDTO.logs]: getLogsUpdaterConfig(
preferences,
redirectWithOptionsData,
setSavedViewPreferences,
),
[DataSource.TRACES]: getTracesUpdaterConfig(
[SavedviewtypesSourceDTO.traces]: getTracesUpdaterConfig(
redirectWithOptionsData,
setSavedViewPreferences,
),
[DataSource.METRICS]: metricsUpdater,
});
export function usePreferenceUpdater({
dataSource,
sourcePage,
mode,
preferences,
setReSync,
setSavedViewPreferences,
}: {
dataSource: DataSource;
sourcePage: PreferenceSourcePage;
mode: string;
preferences: Preferences | null;
setReSync: Dispatch<SetStateAction<boolean>>;
@@ -62,7 +56,7 @@ export function usePreferenceUpdater({
preferences,
redirectWithOptionsData,
setSavedViewPreferences,
)[dataSource];
)[sourcePage];
return {
updateColumns: (newColumns: TelemetryFieldKey[]): void => {

View File

@@ -0,0 +1,12 @@
import { SavedviewtypesSourceDTO } from 'api/generated/services/sigNoz.schemas';
import { PREFERENCE_SOURCE_PAGES } from './constants';
import { PreferenceSourcePage } from './types';
export function isPreferenceSourcePage(
sourcePage: SavedviewtypesSourceDTO,
): sourcePage is PreferenceSourcePage {
return (
PREFERENCE_SOURCE_PAGES as readonly SavedviewtypesSourceDTO[]
).includes(sourcePage);
}

View File

@@ -221,15 +221,16 @@ func postableRuleExamples() []handler.OpenAPIExample {
},
{
Name: "metric_anomaly",
Summary: "Metric anomaly rule",
Description: "Wraps a builder query in the `anomaly` function with daily seasonality, so SigNoz compares each point against the forecast for that time of day. The threshold is compared against the signed anomaly score, so `below` with a target of -2 fires when an abrupt drop holds for the entire window; `requireMinPoints` guards against noisy intervals.",
Summary: "Metric anomaly rule (v1 only)",
Description: "Anomaly rules are not yet supported under schemaVersion v2alpha1, so this example uses the v1 shape. Wraps a builder query in the `anomaly` function with daily seasonality SigNoz compares each point against the forecast for that time of day. Fires when the anomaly score stays below the threshold for the entire window; `requireMinPoints` guards against noisy intervals.",
Value: map[string]any{
"alert": "Anomalous drop in ingested spans",
"alertType": "METRIC_BASED_ALERT",
"description": "Detect an abrupt drop in span ingestion using a z-score anomaly function",
"ruleType": "anomaly_rule",
"version": "v5",
"schemaVersion": "v2alpha1",
"alert": "Anomalous drop in ingested spans",
"alertType": "METRIC_BASED_ALERT",
"description": "Detect an abrupt drop in span ingestion using a z-score anomaly function",
"ruleType": "anomaly_rule",
"version": "v5",
"evalWindow": "24h",
"frequency": "3h",
"condition": map[string]any{
"compositeQuery": map[string]any{
"queryType": "builder",
@@ -255,29 +256,17 @@ func postableRuleExamples() []handler.OpenAPIExample {
},
},
},
"op": "below",
"matchType": "all_the_times",
"target": 2,
"algorithm": "standard",
"seasonality": "daily",
"selectedQueryName": "A",
"requireMinPoints": true,
"requiredNumPoints": 3,
"thresholds": map[string]any{
"kind": "basic",
"spec": []any{
map[string]any{
"name": "warning",
"op": "below",
"matchType": "all_the_times",
"target": -2,
"channels": []any{"slack-ingestion"},
},
},
},
},
"evaluation": rolling("24h", "3h"),
"notificationSettings": map[string]any{
"renotify": renotify("4h", "firing"),
},
"labels": map[string]any{"severity": "warning"},
"labels": map[string]any{"severity": "warning"},
"preferredChannels": []any{"slack-ingestion"},
"annotations": map[string]any{
"description": "Ingestion rate for tenant {{$tenant_id}} is anomalously low (z-score {{$value}}).",
"summary": "Span ingestion anomaly",

View File

@@ -117,10 +117,10 @@ type RuleCondition struct {
TargetUnit string `json:"targetUnit,omitempty" description:"schemaVersion v1 only: the unit of target, such as percent or ms. Converted to compositeQuery.unit before comparison when the two differ."`
Algorithm string `json:"algorithm,omitempty" description:"anomaly_rule only: the anomaly detection algorithm. The supported value is standard."`
Seasonality Seasonality `json:"seasonality,omitzero" description:"anomaly_rule only: the seasonal period the history is compared against, hourly, daily or weekly."`
SelectedQuery string `json:"selectedQueryName,omitempty" required:"true" description:"The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery."`
SelectedQuery string `json:"selectedQueryName,omitempty" description:"The name of the query whose result is evaluated, such as A or F1. Must match a query in compositeQuery. When omitted, F1 is used if present, otherwise the enabled query with the highest name."`
RequireMinPoints bool `json:"requireMinPoints,omitempty" description:"Whether a series is skipped until it has at least requiredNumPoints points in the window. Defaults to false."`
RequiredNumPoints int `json:"requiredNumPoints,omitempty" description:"The minimum number of points a series needs before it is evaluated. Must be greater than 0 when requireMinPoints is true."`
Thresholds *RuleThresholdData `json:"thresholds,omitempty" required:"true" description:"The thresholds to evaluate, as a kind and spec."`
Thresholds *RuleThresholdData `json:"thresholds,omitempty" description:"The thresholds to evaluate, as a kind and spec. Required when schemaVersion is v2alpha1; derived from op, target and matchType for v1."`
}
func (rc *RuleCondition) SelectedQueryName() string {

View File

@@ -9,7 +9,6 @@ import (
"unicode/utf8"
"github.com/prometheus/alertmanager/config"
"github.com/swaggest/jsonschema-go"
"github.com/SigNoz/signoz/pkg/errors"
"github.com/SigNoz/signoz/pkg/types"
@@ -64,7 +63,7 @@ type PostableRule struct {
AlertName valuer.DisplayName `json:"alert" required:"true" description:"The display name of the alert rule."`
AlertType AlertType `json:"alertType" required:"true" description:"The signal the rule evaluates: METRIC_BASED_ALERT, TRACES_BASED_ALERT, LOGS_BASED_ALERT, EXCEPTIONS_BASED_ALERT or AI_TRACES_BASED_ALERT."`
Description string `json:"description,omitempty" description:"A human readable description of what the rule monitors."`
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder and clickhouse_sql queries and is forced to promql_rule for promql queries."`
RuleType RuleType `json:"ruleType" required:"true" description:"The evaluation strategy: threshold_rule compares against thresholds, promql_rule evaluates a PromQL expression, anomaly_rule scores deviation from seasonal history. Defaults to threshold_rule for builder queries and is forced to promql_rule for promql queries."`
EvalWindow valuer.TextDuration `json:"evalWindow,omitzero" description:"The lookback window as a Go duration such as 5m. Only read when schemaVersion is v1, defaulting to 5m; v2alpha1 rules set it in evaluation.spec instead."`
Frequency valuer.TextDuration `json:"frequency,omitzero" description:"How often the rule is evaluated, as a Go duration such as 1m. Only read when schemaVersion is v1, defaulting to 1m; v2alpha1 rules set it in evaluation.spec instead."`
@@ -78,12 +77,12 @@ type PostableRule struct {
PreferredChannels []string `json:"preferredChannels,omitempty" description:"The displayName of each notification channel to notify, for schemaVersion v1 rules. Ignored for v2alpha1, where each threshold carries its own channels."`
Version string `json:"version" description:"The query payload version. Nothing reads it."`
Version string `json:"version" description:"The query payload version. Only v5 is accepted and it is filled in when omitted."`
Evaluation *EvaluationEnvelope `json:"evaluation,omitempty" required:"true" description:"The evaluation window, as a kind and spec."`
SchemaVersion string `json:"schemaVersion,omitempty" required:"true" enum:"v2alpha1" description:"The rule payload schema."`
Evaluation *EvaluationEnvelope `json:"evaluation,omitempty" description:"The evaluation window, as a kind and spec. Required when schemaVersion is v2alpha1; derived from evalWindow and frequency for v1."`
SchemaVersion string `json:"schemaVersion,omitempty" description:"The rule payload schema: v1 (the default when omitted) uses the flat condition fields, v2alpha1 uses condition.thresholds, evaluation and notificationSettings."`
NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty" required:"true" description:"Grouping, re-notification and routing behaviour."`
NotificationSettings *NotificationSettings `json:"notificationSettings,omitempty" description:"Grouping, re-notification and routing behaviour. Required when schemaVersion is v2alpha1; derived from the v1 fields otherwise."`
}
type NotificationSettings struct {
@@ -336,19 +335,6 @@ func (r *PostableRule) UnmarshalJSON(bytes []byte) error {
return r.validate()
}
var _ jsonschema.Preparer = PostableRule{}
// PrepareJSONSchema marks version and source deprecated: nothing reads them,
// they stay only so existing clients keep a stable schema.
func (PostableRule) PrepareJSONSchema(schema *jsonschema.Schema) error {
for _, name := range []string{"version", "source"} {
if property, ok := schema.Properties[name]; ok && property.TypeObject != nil {
property.TypeObject.WithDeprecated(true)
}
}
return nil
}
func isValidLabelName(ln string) bool {
if len(ln) == 0 {
return false

View File

@@ -1,715 +0,0 @@
/**
* AI-owned. Generated and maintained by coding agents alongside the specs that
* use it. Do not hand-edit: regenerate it with the spec that needs the change.
*/
import {
expect,
type Locator,
type Page,
type Request,
} from '@playwright/test';
import { ownDropdown } from '../helpers/alert-forms/shared';
import { postToSeeder } from '../helpers/alerts/seeding';
import { watchConsole, type ConsoleWatch } from '../helpers/common';
import { isQueryRange } from '../helpers/query-range-mock';
import { dismissQuickFiltersAnnouncement } from '../helpers/quick-filters';
import { driver, kit, seeded } from './kit';
export const EXPLORER = {
logs: '/logs/logs-explorer',
traces: '/traces-explorer',
metrics: '/metrics-explorer/explorer',
} as const;
/** A monotonic Sum in the golden dataset. */
export const SUM_METRIC = 'signoz_calls_total';
/** Another golden Sum, for switching between metrics of one type. */
export const OTHER_SUM_METRIC = 'signoz_latency_count';
/** The golden dataset has only Sums; these are seeded per worker. */
export interface MetricTypes {
gauge: string;
histogram: string;
}
/** Inside the golden dataset's window. */
export const RELATIVE_TIME = '6h';
/** One entry of a v5 `query_range` body's `compositeQuery.queries`. */
export interface V5Query {
type: string;
spec: {
name?: string;
signal?: string;
disabled?: boolean;
filter?: { expression?: string };
aggregations?: {
expression?: string;
metricName?: string;
timeAggregation?: string;
spaceAggregation?: string;
reduceTo?: string;
}[];
groupBy?: { name: string }[];
having?: { expression?: string };
order?: { key: { name: string }; direction: string }[];
limit?: number;
stepInterval?: number;
[key: string]: unknown;
};
}
export interface V5Body {
requestType: string;
compositeQuery: { queries: V5Query[] };
}
export interface FilterEditor {
root(): Locator;
/** The contenteditable CodeMirror surface. */
content(): Locator;
/** Replaces the expression by typing it key by key. */
type(text: string): Promise<void>;
/** Appends at the caret without clearing. */
append(text: string): Promise<void>;
clear(): Promise<void>;
press(key: string): Promise<void>;
/** The document text, placeholder excluded, lines joined with `\n`. */
expression(): Promise<string>;
lineCount(): Locator;
/** The open autocomplete popup. */
suggestions(): Locator;
/**
* Ctrl+Space: opens the popup at the caret. Typing opens it only once the
* debounced key fetch answers, which a loaded stack can delay past a test's
* next step.
*/
openSuggestions(): Promise<void>;
suggestion(label: string | RegExp): Locator;
}
export interface QueryBlock {
root(): Locator;
filter: FilterEditor;
/** The filter's status icon: shown only while unfocused and non-empty. */
filterStatus(): Locator;
aggregation: FilterEditor;
/** The aggregation's "every … Seconds" input. */
step(): Locator;
metric: MetricControls;
addOns: AddOns;
/** The "…" menu: offered only where several queries are allowed. */
actions(): Locator;
/** A row of the open "…" menu. */
menuItem(action: 'clone' | 'delete'): Locator;
clone(): Promise<void>;
delete(): Promise<void>;
toggleVisibility(): Promise<void>;
collapse(): Promise<void>;
/** The data-source dropdown's value; only on hosts that let it change. */
signal(): Locator;
setSignal(label: 'Logs' | 'Traces' | 'Metrics'): Promise<void>;
}
export interface FormulaBlock {
root(): Locator;
expression(): Locator;
legend(): Locator;
delete(): Promise<void>;
}
/** `query-add-on-<field>` toggle values: a documented DOM contract. */
export type AddOnField =
| 'group_by'
| 'having'
| 'order_by'
| 'limit'
| 'legend_format'
| 'reduce_to';
export interface AddOns {
/** The toggle row; its children name the add-ons on offer. */
toggles(): Locator;
/** Idempotent: leaves an already-open add-on open. */
open(field: AddOnField): Promise<void>;
content(field: AddOnField): Locator;
groupBy: {
/** Types `key` and picks the suggestion with that exact name. */
add(key: string): Promise<void>;
remove(key: string): Promise<void>;
/** The selected keys, in order. */
values(): Promise<string[]>;
};
having: FilterEditor;
limit(): Locator;
legend(): Locator;
reduceTo: {
/** The selected value. */
value(): Locator;
set(label: string): Promise<void>;
};
}
/** The metrics aggregation section: metric picker plus time/space selects. */
export interface MetricControls {
select(name: string): Promise<void>;
/** The metric name input. */
input(): Locator;
/** The selected value. Absent for histograms. */
timeAggregation(): Locator;
/** The selected value. */
spaceAggregation(): Locator;
setTimeAggregation(label: string): Promise<void>;
setSpaceAggregation(label: string): Promise<void>;
/** Labels offered by the space-aggregation select, as shown. */
spaceOptions(): Promise<string[]>;
}
export interface QuickFilterValue {
checkbox(): Locator;
/** Toggles the value; returns the query_range bodies the toggle fired. */
toggle(): Promise<V5Body[]>;
}
/** The explorer's tab, carried in the `panelTypes` param. */
export type ExplorerView = 'list' | 'graph' | 'table';
export interface OpenOptions {
/** Serialised the way the app writes it. */
query?: unknown;
/** A `compositeQuery` value sent as given, for malformed input. */
raw?: string;
view?: ExplorerView;
}
export interface QueryBuilderDriver {
/**
* Resolves once the page's own first query_range has answered: the explorer
* rewrites its URL and re-mounts the builder until then, which drops
* keystrokes. Returns the bodies that load fired.
*/
openExplorer(path: string, options?: OpenOptions): Promise<V5Body[]>;
query(name: string): QueryBlock;
/** Adds the next query (B, C, …) and waits for its block. */
addQuery(name: string): Promise<QueryBlock>;
/** Builder query names, top to bottom. */
queryNames(): Promise<string[]>;
/** Panel-editor query-type tab, by its queryType (`builder`, `promql`, …). */
tab(queryType: string): Locator;
promql(): Locator;
formula(name: string): FormulaBlock;
addFormula(name: string): Promise<FormulaBlock>;
traceOperator: {
root(): Locator;
/** "Add Trace Matching": offered on traces hosts that allow it. */
addButton(): Locator;
add(): Promise<void>;
remove(): Promise<void>;
editor: FilterEditor;
};
/**
* Explorer "Add to dashboard": picks the dashboard titled `title` and waits
* for the new-panel editor the export navigates to.
*/
addToDashboard(title: string): Promise<void>;
runButton(): Locator;
/** The logs explorer's results area, below the builder. */
logsResults(): Locator;
/** Clicks Run; returns every query_range body the click fired. */
run(): Promise<V5Body[]>;
/**
* Clicks Run until `read()` equals `expected`. For panel-editor structural
* edits, whose draft can lag the DOM: an early Run is a cache hit that
* sends nothing. Never clicks while the button is Cancel.
*/
rerunUntil(read: () => unknown, expected: unknown): Promise<void>;
/**
* Ctrl/Cmd+Enter from the focused field; returns the fired bodies. Waits two
* frames first: editor changes reach React state on its next scheduler task,
* and a keypress inside the same frame as the last keystroke reads the
* previous render — a gap no person can produce.
*/
runShortcut(): Promise<V5Body[]>;
/** A value in an explorer's checkbox quick filter, by its header title. */
quickFilter(title: string, value: string): QuickFilterValue;
/** The spec of query `name` in the first body that has it. */
spec(bodies: V5Body[], name: string): V5Query['spec'];
/** Every query_range body sent since the test started. */
sent(): V5Body[];
/**
* Query `name`'s spec in the newest body that has it, whatever sent it. The
* panel editor fetches on structural edits, so Run after one can be a cache
* hit that sends nothing: poll this rather than waiting on Run.
*/
latest(name: string): V5Query['spec'] | undefined;
/** The URL's `compositeQuery`, parsed. */
urlQuery(): Record<string, unknown> | null;
console: ConsoleWatch;
}
/** CodeMirror renders its placeholder inside the empty line. */
const EDITOR_DOC = async (root: Locator): Promise<string> => {
const lines = root.locator('.cm-content .cm-line');
const texts = await lines.allTextContents();
const placeholders = await lines.evaluateAll((nodes) =>
nodes.map((node) => node.querySelector('.cm-placeholder')?.textContent ?? ''),
);
return texts
.map((text, i) =>
placeholders[i] ? text.replace(placeholders[i], '') : text,
)
.join('\n');
};
function editorAt(page: Page, root: () => Locator): FilterEditor {
const content = (): Locator => root().locator('.cm-content');
const editor: FilterEditor = {
root,
content,
async type(text) {
await editor.clear();
await page.keyboard.type(text);
},
async append(text) {
await content().click();
await page.keyboard.press('End');
await page.keyboard.type(text);
},
async clear() {
await content().click();
await page.keyboard.press('ControlOrMeta+a');
await page.keyboard.press('Backspace');
await expect.poll(() => EDITOR_DOC(root())).toBe('');
},
press: (key) => page.keyboard.press(key),
expression: () => EDITOR_DOC(root()),
lineCount: () => root().locator('.cm-line'),
suggestions: () => page.locator('.cm-tooltip-autocomplete'),
async openSuggestions() {
await expect(async () => {
await page.keyboard.press('Control+Space');
await expect(editor.suggestions()).toBeVisible({ timeout: 2_000 });
}).toPass({ timeout: 15_000 });
},
suggestion: (label) =>
page
.locator('.cm-tooltip-autocomplete [role="option"]')
.filter({ hasText: label }),
};
return editor;
}
/**
* Opens the antd select inside `select` and returns its options. Scoped to the
* list the select owns: a previous select's list can still be mid-close.
*/
async function openSelect(page: Page, select: Locator): Promise<Locator> {
await select.locator('.ant-select-selector').click();
const list = await ownDropdown(page, select);
await expect(list).toBeVisible();
return list.locator('.ant-select-item-option');
}
/** antd renders select options with trailing whitespace ("Sum "). */
const exactly = (label: string): RegExp => new RegExp(`^\\s*${label}\\s*$`);
/** A reduce-to option or value by its operator: "Sum of values in timeframe". */
export const reduceToLabel = (operator: string): RegExp =>
new RegExp(`^\\s*${operator} of values`);
const ADD_ON_CONTENT: Record<AddOnField, string> = {
group_by: 'group-by-content',
having: 'having-content',
order_by: 'order-by-content',
limit: 'limit-content',
legend_format: 'legend-format-content',
reduce_to: 'reduce-to-content',
};
function addOnsAt(page: Page, root: () => Locator): AddOns {
const content = (field: AddOnField): Locator =>
root().getByTestId(ADD_ON_CONTENT[field]);
const groupBy = (): Locator => root().getByTestId('group-by');
const addOns: AddOns = {
toggles: () => root().locator('[data-testid^="query-add-on-"]'),
async open(field) {
if (await content(field).isVisible()) {
return;
}
await root().getByTestId(`query-add-on-${field}`).click();
await expect(content(field)).toBeVisible();
},
content,
groupBy: {
async add(key) {
const options = await openSelect(page, groupBy());
await groupBy().locator('input').fill(key);
await options
.filter({ hasText: exactly(key) })
.first()
.click();
await page.keyboard.press('Escape');
await expect(
groupBy().locator('.ant-select-selection-item', { hasText: key }),
).toBeVisible();
},
async remove(key) {
await groupBy()
.locator('.ant-select-selection-item', { hasText: key })
.locator('.ant-select-selection-item-remove')
.click();
},
async values() {
const texts = await groupBy()
.locator('.ant-select-selection-item-content')
.allTextContents();
return texts.map((text) => text.trim());
},
},
having: editorAt(page, () => root().getByTestId('having-editor')),
limit: () => content('limit').getByTestId('input-Limit'),
legend: () => content('legend_format').getByTestId('input-Legend format'),
reduceTo: {
value: () =>
root().getByTestId('reduce-to').locator('.ant-select-selection-item'),
// Labels read "<Op> of values in timeframe"; matched on the operator.
async set(label) {
const options = await openSelect(page, root().getByTestId('reduce-to'));
await options.filter({ hasText: reduceToLabel(label) }).click();
await expect(addOns.reduceTo.value()).toHaveText(reduceToLabel(label));
},
},
};
return addOns;
}
function metricAt(page: Page, root: () => Locator): MetricControls {
const picker = (): Locator =>
root().locator('[data-testid^="metric-name-selector-"]');
const time = (): Locator => root().getByTestId('metrics-time-aggregation');
const space = (): Locator => root().getByTestId('metrics-space-aggregation');
return {
async select(name) {
// An antd AutoComplete: the testid is on a wrapper.
const field = picker();
const options = await openSelect(page, field);
await field.locator('input').fill(name);
// Options carry the metric's type and unit next to its name.
await options.filter({ hasText: name }).first().click();
},
// The selection item, not the root: these selects render their list
// inside the root, so its text includes every option.
input: () => picker().locator('input'),
timeAggregation: () => time().locator('.ant-select-selection-item'),
spaceAggregation: () => space().locator('.ant-select-selection-item'),
async setTimeAggregation(label) {
const options = await openSelect(page, time());
await options.filter({ hasText: exactly(label) }).click();
await expect(this.timeAggregation()).toHaveText(label);
},
async setSpaceAggregation(label) {
const options = await openSelect(page, space());
await options.filter({ hasText: exactly(label) }).click();
await expect(this.spaceAggregation()).toHaveText(label);
},
async spaceOptions() {
const options = await openSelect(page, space());
const labels = await options.allTextContents();
await page.keyboard.press('Escape');
return labels.map((label) => label.trim());
},
};
}
/**
* Two frames: an edit reaches React state on its next scheduler task, and an
* action in the same frame reads the previous render. A long render delays
* the frame itself, so this cannot pass before the commit.
*/
async function afterRender(page: Page): Promise<void> {
await page.evaluate(
() =>
new Promise<void>((resolve) => {
// Runs in the browser; the e2e tsconfig has no DOM lib.
const { requestAnimationFrame: frame } = globalThis as unknown as {
requestAnimationFrame(this: void, callback: () => void): number;
};
frame(() => frame(() => resolve()));
}),
);
}
function queryBuilderDriver(page: Page): QueryBuilderDriver {
const bodies: V5Body[] = [];
page.on('request', (request: Request) => {
if (isQueryRange(request.url()) && request.method() === 'POST') {
bodies.push(request.postDataJSON() as V5Body);
}
});
const consoleWatch = watchConsole(page, {
// ANTLR reports every partial expression on console.error, prefixed
// with its position (`line 1:14 ...`).
ignore: ['line 1:', 'line 2:', 'line 3:'],
});
// Waits on a request the action started: a response to one already in
// flight (e.g. after a structural edit) would end the wait too early.
const firedBy = async (action: () => Promise<void>): Promise<V5Body[]> => {
const before = bodies.length;
const answered = page
.waitForRequest((r) => isQueryRange(r.url()) && r.method() === 'POST')
.then((request) => request.response());
await action();
await answered;
return bodies.slice(before);
};
const qb: QueryBuilderDriver = {
async openExplorer(path, { query, raw, view } = {}) {
await dismissQuickFiltersAnnouncement(page);
const params = [`relativeTime=${RELATIVE_TIME}`];
if (view) {
params.push(`panelTypes=${encodeURIComponent(JSON.stringify(view))}`);
}
const composite =
raw ??
(query === undefined
? undefined
: encodeURIComponent(JSON.stringify(query)));
if (composite !== undefined) {
params.push(`compositeQuery=${composite}`);
}
const url = `${path}?${params.join('&')}`;
// The metrics explorer runs nothing until a metric is chosen; its
// settle point is the metric list instead.
if (path === EXPLORER.metrics) {
await Promise.all([
page.waitForResponse((r) => r.url().includes('/api/v2/metrics')),
page.goto(url),
]);
await expect(qb.query('A').filter.content()).toBeVisible();
return [];
}
const fired = await firedBy(async () => {
await page.goto(url);
});
await expect(qb.query('A').filter.content()).toBeVisible();
return fired;
},
query(name) {
const root = (): Locator => page.getByTestId(`query-${name}`);
// Index-suffixed testids follow screen position, not the query's
// name (A, C, B after a delete and re-add): match them in the block.
const signalSelect = (): Locator =>
root().locator('[data-testid^="query-data-source-selector-"]');
return {
root,
filter: editorAt(page, () =>
root().getByTestId('query-where-clause-editor'),
),
filterStatus: () => root().getByTestId('query-validation-status'),
aggregation: editorAt(page, () =>
root().getByTestId('query-aggregation-editor'),
),
step: () => root().getByTestId('input-Seconds'),
metric: metricAt(page, root),
addOns: addOnsAt(page, root),
actions: () => root().getByTestId('query-actions'),
menuItem: (action) =>
page.getByTestId(`query-actions-item-${action}-query`),
async clone() {
await root().getByTestId('query-actions').click();
await page.getByTestId('query-actions-item-clone-query').click();
await afterRender(page);
},
async delete() {
await root().getByTestId('query-actions').click();
await page.getByTestId('query-actions-item-delete-query').click();
await expect(root()).toHaveCount(0);
await afterRender(page);
},
async toggleVisibility() {
await root().getByTestId('qb-entity-visibility').click();
// The icon is the only visible change and carries no state.
await afterRender(page);
},
collapse: () => root().getByTestId('qb-entity-collapse').click(),
signal: () => signalSelect().locator('.ant-select-selection-item'),
async setSignal(label) {
const options = await openSelect(page, signalSelect());
await options.filter({ hasText: exactly(label) }).click();
await expect(this.signal()).toHaveText(label);
},
};
},
tab: (queryType) => page.getByTestId(`query-type-tab-${queryType}`),
promql: () => page.getByTestId('promql-query-input').first(),
async addQuery(name) {
await page.getByTestId('add-new-query-button').click();
const block = qb.query(name);
await expect(block.filter.content()).toBeVisible();
return block;
},
queryNames: () =>
page.locator('[data-testid^="query-"]').evaluateAll((nodes) =>
nodes
.map((node) => node.getAttribute('data-testid') ?? '')
.filter((id) => /^query-[A-Z]$/.test(id))
.map((id) => id.slice('query-'.length)),
),
formula(name) {
const root = (): Locator => page.getByTestId(`formula-${name}`);
return {
root,
expression: () => root().getByTestId('formula-expression'),
legend: () => root().getByTestId('formula-legend'),
async delete() {
await root().getByTestId('qb-entity-delete').click();
await expect(root()).toHaveCount(0);
// The block leaves the DOM before the editor's draft follows.
await afterRender(page);
},
};
},
async addFormula(name) {
await page.getByTestId('add-formula-button').click();
const formula = qb.formula(name);
await expect(formula.expression()).toBeVisible();
return formula;
},
traceOperator: {
root: () => page.getByTestId('trace-operator'),
// No testid; the label is followed by a "Beta" tag inside the button.
addButton: () =>
page.getByRole('button').filter({ hasText: /^Add Trace Matching/ }),
async add() {
await qb.traceOperator.addButton().click();
await expect(qb.traceOperator.editor.content()).toBeVisible();
},
async remove() {
// The only direct button child: the trash icon, no testid.
await qb.traceOperator.root().locator(':scope > button').click();
await expect(qb.traceOperator.root()).toHaveCount(0);
},
editor: editorAt(page, () => page.getByTestId('trace-operator-editor')),
},
async addToDashboard(title) {
await page.getByTestId('explorer-add-to-dashboard').click();
const dialog = page.getByTestId('export-panel-dialog');
await dialog
.getByTestId('export-dashboard-select')
.locator('input')
.fill(title);
await dialog.locator(`.ant-select-item-option[title="${title}"]`).click();
await dialog.getByTestId('export-panel-export').click();
await page.waitForURL(/\/panel\/new\?/);
await expect(qb.query('A').filter.content()).toBeVisible();
},
runButton: () => page.locator('[data-run-query-btn]').first(),
// No testid on the container.
logsResults: () => page.locator('.logs-explorer-views'),
async run() {
await afterRender(page);
return firedBy(() => qb.runButton().click());
},
async rerunUntil(read, expected) {
await expect(async () => {
await expect(qb.runButton()).toHaveText(/Run Query/);
await afterRender(page);
await qb.runButton().click();
await expect.poll(read, { timeout: 3_000 }).toEqual(expected);
}).toPass({ timeout: 25_000 });
},
async runShortcut() {
await afterRender(page);
return firedBy(() => page.keyboard.press('ControlOrMeta+Enter'));
},
quickFilter(title, value) {
const checkbox = (): Locator =>
page.getByTestId(`checkbox-${title}-${value}`);
return {
checkbox,
toggle: () => firedBy(() => checkbox().click()),
};
},
spec(fired, name) {
for (const body of fired) {
const match = body.compositeQuery?.queries?.find(
(q) => q.spec?.name === name,
);
if (match) {
return match.spec;
}
}
throw new Error(`no query ${name} in ${fired.length} query_range bodies`);
},
sent: () => bodies,
latest: (name) =>
[...bodies]
.reverse()
.flatMap((body) => body.compositeQuery?.queries ?? [])
.find((query) => query.spec?.name === name)?.spec,
urlQuery() {
const raw = new URL(page.url()).searchParams.get('compositeQuery');
if (!raw) {
return null;
}
// The app encodes before URLSearchParams encodes again.
return JSON.parse(decodeURIComponent(raw)) as Record<string, unknown>;
},
console: consoleWatch,
};
return qb;
}
/** Layers `qb` onto another host's test, e.g. the alert-rule fixtures. */
export const withQueryBuilder = driver('qb', ({ page }) =>
queryBuilderDriver(page),
);
const HISTOGRAM_BOUNDS = ['1', '2', '4', '+Inf'];
/** Ten minutes of a gauge and a cumulative histogram, names unique per worker. */
export const withMetricTypes = seeded(
'metricTypes',
async ({ page, workerIndex }) => {
const suffix = `${workerIndex}_${Date.now()}`;
const types: MetricTypes = {
gauge: `e2e_qb_gauge_${suffix}`,
histogram: `e2e_qb_histogram_${suffix}`,
};
const now = Date.now();
const points: Record<string, unknown>[] = [];
for (let minute = 0; minute < 10; minute += 1) {
const timestamp = new Date(now - (10 - minute) * 60_000).toISOString();
points.push({
metric_name: types.gauge,
labels: { host: 'qb-host' },
timestamp,
value: 10 + minute,
type_: 'Gauge',
temporality: 'Unspecified',
is_monotonic: false,
});
HISTOGRAM_BOUNDS.forEach((le, bucket) => {
points.push({
metric_name: types.histogram,
labels: { le },
timestamp,
value: (minute + 1) * (bucket + 1),
type_: 'Histogram',
temporality: 'Cumulative',
is_monotonic: false,
});
});
}
await postToSeeder(page, '/telemetry/metrics', points);
return types;
},
);
export const test = withQueryBuilder(kit);
export { expect } from './kit';

View File

@@ -85,17 +85,8 @@ export async function pickChannelByName(
channelName: string,
): Promise<void> {
const tagsBefore = await selectedTags(select).count();
// A re-render of the condition section (e.g. after a query edit) can close
// the select as the click opens it; re-click only while it is still closed.
await expect(async () => {
const isOpen = await select.evaluate((node) =>
node.classList.contains('ant-select-open'),
);
if (!isOpen) {
await select.click();
}
await expect(select).toHaveClass(/ant-select-open/, { timeout: 2_000 });
}).toPass({ timeout: 15_000 });
await select.click();
await expect(select).toHaveClass(/ant-select-open/);
// `fill` on the combobox input rather than `keyboard.type`: the query is a ~30
// character channel name and every keystroke re-runs antd's filter, so typing it

View File

@@ -15,7 +15,7 @@ import type {
// ─── Seeding telemetry ───────────────────────────────────────────────────
export async function postToSeeder(
async function postToSeeder(
page: Page,
path: string,
data: unknown,

View File

@@ -272,9 +272,7 @@ export async function holdQueryRange(
});
await page.route(QUERY_RANGE_GLOB, async (route) => {
await gate;
// A cancelled run aborts its request while it is held; there is
// nothing left to answer.
await fulfill(route, body).catch(() => undefined);
await fulfill(route, body);
});
return { release: () => release() };
}

View File

@@ -1,152 +0,0 @@
import {
expect,
EXPLORER,
SUM_METRIC,
test,
} from '../../drivers/query-builder';
const HAVING = ['count() > 10', 'count() IN [1, 2]', 'count() NOT IN [1, 2]'];
test.describe('Query builder — add-ons', () => {
for (const explorer of ['logs', 'traces'] as const) {
test(`TC-21 ${explorer} group by keeps order through removal and reload`, async ({
qb,
}) => {
await qb.openExplorer(EXPLORER[explorer], { view: 'graph' });
const addOns = qb.query('A').addOns;
await addOns.open('group_by');
await addOns.groupBy.add('service.name');
await addOns.groupBy.add('deployment.environment');
await addOns.groupBy.add('k8s.namespace.name');
await addOns.groupBy.remove('service.name');
const fired = await qb.run();
const expected = ['deployment.environment', 'k8s.namespace.name'];
expect(qb.spec(fired, 'A').groupBy?.map((key) => key.name)).toEqual(
expected,
);
const reloaded = await qb.openExplorer(EXPLORER[explorer], {
view: 'graph',
query: qb.urlQuery(),
});
expect(qb.spec(reloaded, 'A').groupBy?.map((key) => key.name)).toEqual(
expected,
);
expect(await qb.query('A').addOns.groupBy.values()).toEqual(expected);
});
}
test('TC-21 metrics group by offers the metric’s own attributes', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.metrics);
const query = qb.query('A');
await query.metric.select(SUM_METRIC);
await query.addOns.groupBy.add('operation');
const fired = await qb.run();
expect(qb.spec(fired, 'A').groupBy?.map((key) => key.name)).toEqual([
'operation',
]);
});
for (const having of HAVING) {
test(`TC-22 having "${having}" is sent verbatim and accepted`, async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs, { view: 'graph' });
const addOns = qb.query('A').addOns;
await addOns.open('group_by');
await addOns.groupBy.add('service.name');
await addOns.open('having');
await addOns.having.type(having);
await addOns.having.press('Escape');
const fired = await qb.run();
expect(qb.spec(fired, 'A').having?.expression).toBe(having);
expect(qb.console.failedResponses).toEqual([]);
});
}
test('TC-23 the logs list orders by timestamp then id, traces by timestamp only', async ({
qb,
}) => {
const logs = await qb.openExplorer(EXPLORER.logs, { view: 'list' });
expect(qb.spec(logs, 'A').order?.map((o) => o.key.name)).toEqual([
'timestamp',
'id',
]);
const traces = await qb.openExplorer(EXPLORER.traces, { view: 'list' });
expect(qb.spec(traces, 'A').order?.map((o) => o.key.name)).toEqual([
'timestamp',
]);
});
test('TC-24 a positive limit is sent; empty and zero send none', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs, { view: 'graph' });
const addOns = qb.query('A').addOns;
await addOns.open('group_by');
await addOns.groupBy.add('service.name');
await addOns.open('limit');
await addOns.limit().fill('10');
expect(qb.spec(await qb.run(), 'A').limit).toBe(10);
await addOns.limit().fill('');
expect(qb.spec(await qb.run(), 'A')).not.toHaveProperty('limit');
await addOns.limit().fill('3');
await qb.run();
await addOns.limit().fill('0');
expect(qb.spec(await qb.run(), 'A')).not.toHaveProperty('limit');
});
// known: the input accepts a negative limit; Run then sends nothing, and the
// next Run sends it and the backend answers 400.
test.fixme('TC-24 a negative limit is never sent', async ({ qb }) => {
await qb.openExplorer(EXPLORER.logs, { view: 'graph' });
const addOns = qb.query('A').addOns;
await addOns.open('limit');
await addOns.limit().fill('-5');
await qb.runButton().click();
await qb.runButton().click();
expect(qb.sent().map((body) => qb.spec([body], 'A').limit)).not.toContain(-5);
expect(qb.console.failedResponses).toEqual([]);
});
test('TC-25 the legend prefills from group by and a custom one is kept', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs, { view: 'graph' });
const addOns = qb.query('A').addOns;
await addOns.open('group_by');
await addOns.groupBy.add('service.name');
await addOns.groupBy.add('deployment.environment');
await addOns.open('legend_format');
await expect(addOns.legend()).toHaveValue(
'service.name = {{service.name}}, deployment.environment = {{deployment.environment}}',
);
await addOns.legend().fill('{{service.name}} logs');
await addOns.groupBy.add('k8s.namespace.name');
await expect(addOns.legend()).toHaveValue('{{service.name}} logs');
expect(qb.spec(await qb.run(), 'A').legend).toBe('{{service.name}} logs');
});
test('TC-25 the legend opens empty without a group by', async ({ qb }) => {
await qb.openExplorer(EXPLORER.logs, { view: 'graph' });
await qb.query('A').addOns.open('legend_format');
await expect(qb.query('A').addOns.legend()).toHaveValue('');
});
});

View File

@@ -1,80 +0,0 @@
import { expect, EXPLORER, test } from '../../drivers/query-builder';
// One comma-separated term per entry in the request's `aggregations`.
const EXPRESSIONS: Record<string, string[]> = {
'a count': ['count()'],
'a distinct count': ['count_distinct(service.name)'],
'a percentile of a span field': ['p99(duration_nano)'],
'two aggregations': ['count()', 'p99(duration_nano)'],
};
test.describe('Query builder — logs and traces aggregations', () => {
for (const [label, terms] of Object.entries(EXPRESSIONS)) {
test(`TC-17 ${label} reaches the request`, async ({ qb }) => {
await qb.openExplorer(EXPLORER.traces, { view: 'graph' });
const aggregation = qb.query('A').aggregation;
await aggregation.type(terms.join(', '));
await aggregation.press('Escape');
const fired = await qb.run();
expect(qb.spec(fired, 'A').aggregations?.map((a) => a.expression)).toEqual(
terms,
);
});
}
test('TC-18 the step interval reaches the request', async ({
authedPage: page,
qb,
}) => {
await qb.openExplorer(EXPLORER.traces, { view: 'graph' });
await qb.query('A').step().fill('120');
await page.keyboard.press('Tab');
const fired = await qb.run();
expect(qb.spec(fired, 'A').stepInterval).toBe(120);
});
test('TC-30 a trace operator replaces per-query aggregation until removed', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.traces, { view: 'graph' });
await (await qb.addQuery('B')).filter.type("http.status_code = '500'");
await qb.query('B').filter.press('Escape');
await qb.traceOperator.add();
await qb.traceOperator.editor.type('A => B');
await qb.traceOperator.editor.press('Escape');
for (const name of ['A', 'B']) {
await expect(qb.query(name).aggregation.root()).toHaveCount(0);
await expect(qb.query(name).addOns.toggles()).toHaveCount(0);
}
const fired = await qb.run();
const operator = fired
.flatMap((body) => body.compositeQuery.queries)
.find((query) => query.type === 'builder_trace_operator');
expect(operator?.spec).toMatchObject({ expression: 'A => B' });
await qb.traceOperator.remove();
await expect(qb.query('A').aggregation.root()).toBeVisible();
await qb.rerunUntil(
() =>
qb
.sent()
.at(-1)
?.compositeQuery.queries.some(
(query) => query.type === 'builder_trace_operator',
),
false,
);
});
test('TC-30 the logs explorer offers no trace matching', async ({ qb }) => {
await qb.openExplorer(EXPLORER.logs, { view: 'graph' });
await expect(qb.query('A').root()).toBeVisible();
await expect(qb.traceOperator.addButton()).toHaveCount(0);
});
});

View File

@@ -1,85 +0,0 @@
import { withQueryBuilder } from '../../drivers/query-builder';
import {
expect,
test as alertRulesTest,
} from '../../fixtures/alerts/alert-rules';
import { AlertType } from '../../helpers/alert-forms/constants';
import { gotoCreateAlertV2 } from '../../helpers/alert-forms/navigation';
import {
selectThresholdChannel,
v2SaveButton,
} from '../../helpers/alert-forms/v2';
import { gotoAlertOverview } from '../../helpers/alerts/navigation';
const test = withQueryBuilder(alertRulesTest);
const FILTER_A = "http.method = 'GET'";
const FILTER_B = "http.status_code = '500'";
const TRACE_MATCH = 'A => B';
interface SavedRule {
condition?: {
compositeQuery?: {
queries?: {
type: string;
spec: {
name?: string;
expression?: string;
filter?: { expression?: string };
};
}[];
};
};
}
test.describe('Query builder — alerts', () => {
test('TC-06 a trace-matching traces alert saves and reopens intact', async ({
authedPage: page,
alertChannel,
ownedRules,
qb,
}) => {
await gotoCreateAlertV2(page, { alertType: AlertType.TRACES });
await page.getByTestId('alert-name-input').fill(`e2e-qb-tc06-${Date.now()}`);
await qb.query('A').filter.type(FILTER_A);
await qb.query('A').filter.press('Escape');
const b = await qb.addQuery('B');
await b.filter.type(FILTER_B);
await b.filter.press('Escape');
await qb.traceOperator.add();
await qb.traceOperator.editor.type(TRACE_MATCH);
await qb.traceOperator.editor.press('Escape');
// Blur first: the editor's blur re-renders the condition section, which
// otherwise closes the channel select as its click opens it.
await qb.traceOperator.editor.content().blur();
await selectThresholdChannel(page, 0, alertChannel.name);
const [response] = await Promise.all([
page.waitForResponse(
(r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
),
v2SaveButton(page).click(),
]);
await ownedRules.register(response);
const saved = response.request().postDataJSON() as SavedRule;
const queries = saved.condition?.compositeQuery?.queries ?? [];
expect(queries).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: 'builder_trace_operator',
spec: expect.objectContaining({ expression: TRACE_MATCH }),
}),
]),
);
const { data } = (await response.json()) as { data: { id: string } };
await gotoAlertOverview(page, String(data.id));
await expect.poll(() => qb.query('A').filter.expression()).toBe(FILTER_A);
await expect.poll(() => qb.query('B').filter.expression()).toBe(FILTER_B);
await expect
.poll(() => qb.traceOperator.editor.expression())
.toBe(TRACE_MATCH);
});
});

View File

@@ -1,72 +0,0 @@
import { emptyDashboard, test as editorTest } from '../../drivers/panel-editor';
import {
expect,
EXPLORER,
withQueryBuilder,
} from '../../drivers/query-builder';
const test = withQueryBuilder(editorTest);
const FILTER = "severity_text = 'ERROR'";
const AGGREGATION = 'count_distinct(service.name)';
interface StoredQuery {
spec: {
filter?: { expression?: string };
aggregations?: { expression?: string }[];
};
}
/** Where a non-List panel keeps its builder queries in the v2 dashboard spec. */
interface StoredPanel {
spec: {
queries: {
spec: { plugin: { kind: string; spec: { queries: StoredQuery[] } } };
}[];
};
}
test.describe('Query builder — explorer to dashboard', () => {
test('TC-05 a logs explorer query survives add to dashboard, save and reopen', async ({
dashboards,
editor,
qb,
}) => {
const dashboard = emptyDashboard();
const title = dashboard.spec.display.name;
const id = await dashboards.seed(dashboard);
await qb.openExplorer(EXPLORER.logs, { view: 'graph' });
await qb.query('A').filter.type(FILTER);
await qb.query('A').filter.press('Escape');
await qb.query('A').aggregation.type(AGGREGATION);
await qb.query('A').aggregation.press('Escape');
await qb.run();
await qb.addToDashboard(title);
await expect.poll(() => qb.query('A').filter.expression()).toBe(FILTER);
await expect
.poll(() => qb.query('A').aggregation.expression())
.toBe(AGGREGATION);
await editor.save();
// The shared spec types model only bare BuilderQuery plugins.
const panels = (await dashboards.get(id)).spec.panels as unknown as Record<
string,
StoredPanel
>;
const [panelId] = Object.keys(panels);
const plugin = panels[panelId].spec.queries[0].spec.plugin;
expect(plugin.kind).toBe('signoz/CompositeQuery');
expect(plugin.spec.queries[0].spec).toMatchObject({
filter: { expression: FILTER },
aggregations: [{ expression: AGGREGATION }],
});
await dashboards.openEditor(id, panelId);
await expect.poll(() => qb.query('A').filter.expression()).toBe(FILTER);
await expect
.poll(() => qb.query('A').aggregation.expression())
.toBe(AGGREGATION);
});
});

View File

@@ -1,284 +0,0 @@
import { expect, EXPLORER, test } from '../../drivers/query-builder';
// Typing is real keystrokes: the regressions here (caret jumps, swallowed
// Enter, the run shortcut) only show up through the keyboard path.
const RECENT_KEPT = "service.name = 'frontend' AND severity_text = 'WARN'";
const RECENT_REMOVED = 'logger.name EXISTS';
const COMPOUND: Record<string, string> = {
'NOT over a parenthesised OR':
"NOT (severity_text = 'INFO' OR severity_text = 'WARN') AND service.name = 'frontend'",
'nested groups':
"(service.name = 'frontend' AND (severity_text = 'ERROR' OR severity_text = 'WARN'))",
'NOT IN with EXISTS':
"service.name NOT IN ['frontend', 'adservice'] AND logger.name EXISTS",
};
const queryWithFilter = (expression: string): unknown => ({
queryType: 'builder',
builder: {
queryFormulas: [],
queryData: [
{
queryName: 'A',
dataSource: 'logs',
expression: 'A',
filter: { expression },
aggregations: [{ expression: 'count()' }],
},
],
},
});
const VERBATIM: Record<string, string> = {
'an escaped quote': "logger.name = 'it\\'s'",
'a double-quoted string': 'logger.name = "double quoted"',
'a quoted numeric string': "logger.name = '123'",
'a bare number': 'logger.name = 123',
'a boolean': 'logger.name = true',
'spaces and a backslash': "logger.name = 'a b\\\\c'",
};
test.describe('Query builder — filter editor', () => {
test('TC-07 key, operator and value suggestions build the expression', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
const filter = qb.query('A').filter;
await filter.type('severity_te');
await filter.openSuggestions();
await filter.suggestion('severity_text').first().click();
await expect.poll(() => filter.expression()).toMatch(/^severity_text\s*$/);
await filter.openSuggestions();
await expect(filter.suggestion(/^=/).first()).toBeVisible();
await filter.append('= ');
await filter.openSuggestions();
await filter.suggestion('ERROR').first().click();
await expect
.poll(() => filter.expression())
.toMatch(/^severity_text = 'ERROR'\s*$/);
const fired = await qb.run();
expect(qb.spec(fired, 'A').filter?.expression?.trim()).toBe(
"severity_text = 'ERROR'",
);
});
for (const [label, expression] of Object.entries(VERBATIM)) {
test(`TC-08 ${label} is sent and restored verbatim`, async ({
authedPage: page,
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
const filter = qb.query('A').filter;
await filter.type(expression);
await filter.press('Escape');
const fired = await qb.run();
expect(qb.spec(fired, 'A').filter?.expression).toBe(expression);
await page.reload();
await expect(filter.content()).toBeVisible();
await expect.poll(() => filter.expression()).toBe(expression);
await expect(qb.query('A').filterStatus()).toHaveCount(0);
});
}
test('TC-11 the status icon shows only for an unfocused invalid filter', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
const query = qb.query('A');
await query.filter.type('service.name =');
await expect(query.filterStatus()).toHaveCount(0);
await query.filter.content().blur();
await expect(query.filterStatus()).toBeVisible();
await query.filter.type("service.name = 'frontend'");
await query.filter.content().blur();
await expect(query.filterStatus()).toHaveCount(0);
await query.filter.clear();
await query.filter.content().blur();
await expect(query.filterStatus()).toHaveCount(0);
});
test('TC-12 Enter and Shift+Enter never insert a newline or run', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
const filter = qb.query('A').filter;
await filter.type("severity_text = 'ERROR'");
await filter.press('Escape');
await expect(filter.suggestions()).toHaveCount(0);
const sentBefore = qb.sent().length;
await filter.press('Enter');
await filter.press('Shift+Enter');
await expect(filter.lineCount()).toHaveCount(1);
await expect.poll(() => filter.expression()).toBe("severity_text = 'ERROR'");
expect(qb.sent()).toHaveLength(sentBefore);
});
for (const explorer of ['logs', 'traces'] as const) {
test(`TC-13 Cmd/Ctrl+Enter in the ${explorer} filter runs the edited query`, async ({
qb,
}) => {
await qb.openExplorer(EXPLORER[explorer]);
const filter = qb.query('A').filter;
await filter.type("service.name = 'frontend'");
const fired = await qb.runShortcut();
expect(qb.spec(fired, 'A').filter?.expression).toBe(
"service.name = 'frontend'",
);
await expect(filter.lineCount()).toHaveCount(1);
expect(qb.urlQuery()).toMatchObject({ queryType: 'builder' });
});
}
test('TC-14 Escape closes suggestions and keeps the text', async ({ qb }) => {
await qb.openExplorer(EXPLORER.logs);
const filter = qb.query('A').filter;
await filter.type('serv');
await filter.openSuggestions();
await filter.press('Escape');
await expect(filter.suggestions()).toHaveCount(0);
await expect.poll(() => filter.expression()).toBe('serv');
await filter.press('i');
await expect.poll(() => filter.expression()).toBe('servi');
await filter.press('Escape');
await filter.press('Escape');
await expect.poll(() => filter.expression()).toBe('servi');
await expect(filter.content()).toBeFocused();
});
test('TC-09 value suggestions fill an IN list', async ({ qb }) => {
await qb.openExplorer(EXPLORER.logs);
const filter = qb.query('A').filter;
await filter.type('service.name IN ');
await filter.openSuggestions();
await filter.suggestion('frontend').first().click();
await expect
.poll(() => filter.expression())
.toBe("service.name IN ['frontend'] ");
await filter.type("service.name IN ['frontend', 'cartservice']");
await filter.press('Escape');
const fired = await qb.run();
expect(qb.spec(fired, 'A').filter?.expression).toBe(
"service.name IN ['frontend', 'cartservice']",
);
await expect(qb.query('A').filterStatus()).toHaveCount(0);
});
for (const [label, expression] of Object.entries(COMPOUND)) {
test(`TC-10 ${label} is valid and sent verbatim`, async ({ qb }) => {
await qb.openExplorer(EXPLORER.logs);
const query = qb.query('A');
await query.filter.type(expression);
await query.filter.press('Escape');
await query.filter.content().blur();
await expect(query.filterStatus()).toHaveCount(0);
const fired = await qb.run();
expect(qb.spec(fired, 'A').filter?.expression).toBe(expression);
});
}
test('TC-15 an expression with CRLF from the URL loads without a RangeError', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs, {
query: queryWithFilter("body CONTAINS 'line1\r\nline2'"),
});
await expect.poll(() => qb.query('A').filter.expression()).toContain('line1');
expect(qb.console.errors.filter((e) => e.includes('RangeError'))).toEqual([]);
await qb.query('A').filter.append(" AND severity_text = 'ERROR'");
await expect
.poll(() => qb.query('A').filter.expression())
.toMatch(/severity_text = 'ERROR'$/);
expect(qb.console.errors).toEqual([]);
});
test('TC-15 recent searches are offered, applied and deleted', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
const filter = qb.query('A').filter;
for (const expression of [RECENT_KEPT, RECENT_REMOVED]) {
await filter.type(expression);
await filter.press('Escape');
await qb.run();
}
await filter.clear();
await filter.openSuggestions();
await expect(filter.suggestion(RECENT_KEPT)).toBeVisible();
await expect(filter.suggestion(RECENT_REMOVED)).toBeVisible();
await filter.suggestion(RECENT_KEPT).click();
await expect.poll(() => filter.expression()).toBe(RECENT_KEPT);
await filter.clear();
await filter.openSuggestions();
await filter
.suggestion(RECENT_REMOVED)
.getByRole('button', { name: 'Remove from recent searches' })
.click();
await expect(filter.suggestion(RECENT_REMOVED)).toHaveCount(0);
});
test('TC-15 recent searches survive a reload and stay with their signal', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
await qb.query('A').filter.type(RECENT_KEPT);
await qb.query('A').filter.press('Escape');
await qb.run();
await qb.openExplorer(EXPLORER.logs);
await qb.query('A').filter.clear();
await qb.query('A').filter.openSuggestions();
await expect(qb.query('A').filter.suggestion(RECENT_KEPT)).toBeVisible();
await qb.openExplorer(EXPLORER.traces);
await qb.query('A').filter.clear();
await qb.query('A').filter.openSuggestions();
await expect(qb.query('A').filter.suggestion(RECENT_KEPT)).toHaveCount(0);
});
test('TC-16 a quick-filter value toggles between excluded and cleared', async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
const filter = qb.query('A').filter;
const handTyped = "service.name = 'frontend'";
const excluded = `${handTyped} severity_text not in ['ERROR']`;
const error = qb.quickFilter('Severity Text', 'ERROR');
await filter.type(handTyped);
await qb.run();
for (const expected of [excluded, handTyped, excluded]) {
const fired = await error.toggle();
expect(qb.spec(fired, 'A').filter?.expression).toBe(expected);
await expect.poll(() => filter.expression()).toBe(expected);
}
await expect(error.checkbox()).toHaveAttribute('aria-checked', 'false');
});
});

View File

@@ -1,106 +0,0 @@
import {
expect,
EXPLORER,
type MetricTypes,
OTHER_SUM_METRIC,
SUM_METRIC,
test as base,
withMetricTypes,
} from '../../drivers/query-builder';
const test = withMetricTypes(base);
const MOMENT_AGGREGATIONS = ['Sum', 'Avg', 'Min', 'Max'];
interface TypeDefaults {
metric: (types: MetricTypes) => string;
time?: string;
space: string;
spaceOptions: string[];
}
const DEFAULTS: Record<string, TypeDefaults> = {
sum: {
metric: () => SUM_METRIC,
time: 'Rate',
space: 'Sum',
spaceOptions: MOMENT_AGGREGATIONS,
},
gauge: {
metric: (types) => types.gauge,
time: 'Avg',
space: 'Avg',
spaceOptions: MOMENT_AGGREGATIONS,
},
histogram: {
metric: (types) => types.histogram,
space: 'P90',
spaceOptions: ['P50', 'P75', 'P90', 'P95', 'P99'],
},
};
test.describe('Query builder — metric aggregations', () => {
for (const [type, expected] of Object.entries(DEFAULTS)) {
test(`TC-19 a ${type} metric gets its type's default aggregations`, async ({
metricTypes,
qb,
}) => {
const metricName = expected.metric(metricTypes);
await qb.openExplorer(EXPLORER.metrics);
const metric = qb.query('A').metric;
await metric.select(metricName);
await expect(metric.spaceAggregation()).toHaveText(expected.space);
expect(await metric.spaceOptions()).toEqual(expected.spaceOptions);
const fired = await qb.run();
expect(qb.spec(fired, 'A').aggregations?.[0]).toMatchObject({
metricName,
spaceAggregation: expected.space.toLowerCase(),
...(expected.time && { timeAggregation: expected.time.toLowerCase() }),
});
});
}
test('TC-19 a histogram has no time aggregation control', async ({
metricTypes,
qb,
}) => {
await qb.openExplorer(EXPLORER.metrics);
await qb.query('A').metric.select(metricTypes.histogram);
await expect(qb.query('A').metric.spaceAggregation()).toHaveText('P90');
await expect(qb.query('A').metric.timeAggregation()).toHaveCount(0);
});
test('TC-20 aggregations reset only when the metric type changes', async ({
metricTypes,
qb,
}) => {
await qb.openExplorer(EXPLORER.metrics);
const metric = qb.query('A').metric;
await metric.select(SUM_METRIC);
await metric.setTimeAggregation('Increase');
await metric.setSpaceAggregation('Max');
await metric.select(OTHER_SUM_METRIC);
await expect(metric.timeAggregation()).toHaveText('Increase');
await expect(metric.spaceAggregation()).toHaveText('Max');
await metric.select(metricTypes.gauge);
await expect(metric.timeAggregation()).toHaveText('Avg');
await expect(metric.spaceAggregation()).toHaveText('Avg');
await metric.select(SUM_METRIC);
await expect(metric.timeAggregation()).toHaveText('Rate');
await expect(metric.spaceAggregation()).toHaveText('Sum');
const fired = await qb.run();
expect(qb.spec(fired, 'A').aggregations?.[0]).toMatchObject({
metricName: SUM_METRIC,
timeAggregation: 'rate',
spaceAggregation: 'sum',
});
});
});

View File

@@ -1,112 +0,0 @@
import {
metricsQuery,
SINGLE_PANEL_ID,
singlePanelDashboard,
test as editorTest,
} from '../../drivers/panel-editor';
import {
expect,
OTHER_SUM_METRIC,
SUM_METRIC,
withQueryBuilder,
} from '../../drivers/query-builder';
// In the panel editor a new query starts as metrics with no metric picked, and
// Run does nothing until one is: each added query picks a metric first.
const test = withQueryBuilder(editorTest);
const CLONED_FILTER = "operation = '/ads/get'";
test.describe('Query builder — multiple queries', () => {
test('TC-28 a deleted name is reused by the next added query', async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: metricsQuery() }),
SINGLE_PANEL_ID,
);
for (const name of ['B', 'C']) {
await (await qb.addQuery(name)).metric.select(OTHER_SUM_METRIC);
}
expect(await qb.queryNames()).toEqual(['A', 'B', 'C']);
await qb.query('B').delete();
expect(await qb.queryNames()).toEqual(['A', 'C']);
const reAdded = await qb.addQuery('B');
expect(await qb.queryNames()).toEqual(['A', 'C', 'B']);
await reAdded.metric.select(SUM_METRIC);
await expect(reAdded.metric.input()).toHaveValue(SUM_METRIC);
await expect(qb.query('C').metric.input()).toHaveValue(OTHER_SUM_METRIC);
});
test('TC-28 a clone and a hidden query reach the request', async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: metricsQuery({ filter: CLONED_FILTER }) }),
SINGLE_PANEL_ID,
);
await (await qb.addQuery('B')).metric.select(OTHER_SUM_METRIC);
await qb.query('A').clone();
await expect
.poll(() => qb.query('C').filter.expression())
.toBe(CLONED_FILTER);
await qb.query('B').toggleVisibility();
await qb.runButton().click();
await expect.poll(() => qb.latest('B')?.disabled).toBe(true);
expect(qb.latest('C')).toMatchObject({
filter: { expression: CLONED_FILTER },
aggregations: [expect.objectContaining({ metricName: SUM_METRIC })],
});
});
test('TC-28 the last remaining query offers no delete', async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: metricsQuery() }),
SINGLE_PANEL_ID,
);
await (await qb.addQuery('B')).metric.select(OTHER_SUM_METRIC);
await qb.query('B').delete();
await qb.query('A').actions().click();
await expect(qb.query('A').menuItem('clone')).toBeVisible();
await expect(qb.query('A').menuItem('delete')).toHaveCount(0);
});
test('TC-29 a formula over two queries reaches the request', async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: metricsQuery() }),
SINGLE_PANEL_ID,
);
await (await qb.addQuery('B')).metric.select(OTHER_SUM_METRIC);
const formula = await qb.addFormula('F1');
await formula.expression().fill('A / B');
await formula.legend().fill('ratio');
await qb.runButton().click();
await expect
.poll(() => qb.latest('F1'))
.toMatchObject({ expression: 'A / B', legend: 'ratio' });
await formula.delete();
await qb.rerunUntil(
() =>
qb
.sent()
.at(-1)
?.compositeQuery.queries.map((q) => q.spec.name),
['A', 'B'],
);
});
});

View File

@@ -1,203 +0,0 @@
import {
logsCountQuery,
metricsQuery,
PanelKind,
SINGLE_PANEL_ID,
singlePanelDashboard,
test as editorTest,
} from '../../drivers/panel-editor';
import {
expect,
reduceToLabel,
SUM_METRIC,
withMetricTypes,
withQueryBuilder,
} from '../../drivers/query-builder';
const test = withMetricTypes(withQueryBuilder(editorTest));
const LOGS_FILTER = "severity_text = 'ERROR'";
const TRACES_FILTER = "http.method = 'GET'";
const PROMQL = 'sum(rate(signoz_calls_total[5m]))';
const QUERIES = {
logs: () => logsCountQuery(),
traces: () => logsCountQuery({ signal: 'traces' }),
metrics: () => metricsQuery(),
};
const ALL = ['group_by', 'having', 'order_by', 'limit', 'legend_format'];
const NO_HAVING = ['group_by', 'order_by', 'limit', 'legend_format'];
const METRICS = ['having', 'order_by', 'limit', 'legend_format'];
/**
* Add-on toggles each panel kind offers per signal. Metrics group by lives in
* the aggregation row, so it is never a toggle there.
*/
const ADD_ONS: Record<
keyof typeof QUERIES,
Partial<Record<string, string[]>>
> = {
logs: {
[PanelKind.TimeSeries]: ALL,
[PanelKind.BarChart]: ALL,
[PanelKind.Table]: ALL,
[PanelKind.PieChart]: ALL,
[PanelKind.Number]: ['legend_format'],
[PanelKind.Heatmap]: NO_HAVING,
},
traces: {
[PanelKind.TimeSeries]: ALL,
[PanelKind.BarChart]: ALL,
[PanelKind.Table]: ALL,
[PanelKind.PieChart]: ALL,
[PanelKind.Number]: ['legend_format'],
[PanelKind.Heatmap]: NO_HAVING,
},
metrics: {
[PanelKind.TimeSeries]: METRICS,
[PanelKind.BarChart]: METRICS,
[PanelKind.Table]: [...METRICS, 'reduce_to'],
[PanelKind.PieChart]: [...METRICS, 'reduce_to'],
[PanelKind.Number]: ['legend_format', 'reduce_to'],
[PanelKind.Heatmap]: ['order_by', 'limit', 'legend_format', 'bucket_options'],
},
};
test.describe('Query builder — panel editor', () => {
for (const [signal, kinds] of Object.entries(ADD_ONS)) {
for (const [kind, expected] of Object.entries(kinds)) {
test(`TC-27 ${signal} on ${kind.replace('signoz/', '')} offers its add-ons`, async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({
kind: kind as PanelKind,
query: QUERIES[signal as keyof typeof QUERIES](),
}),
SINGLE_PANEL_ID,
);
await expect(qb.query('A').addOns.toggles()).toHaveCount(
expected?.length ?? 0,
);
const toggles = await qb
.query('A')
.addOns.toggles()
.evaluateAll((nodes) =>
nodes.map((node) =>
(node.getAttribute('data-testid') ?? '').replace('query-add-on-', ''),
),
);
expect(toggles).toEqual(expected);
});
}
}
test('TC-27 a limit hidden by a kind switch reopens with its value', async ({
dashboards,
editor,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: logsCountQuery() }),
SINGLE_PANEL_ID,
);
const addOns = qb.query('A').addOns;
await addOns.open('limit');
await addOns.limit().fill('7');
await editor.switchType(PanelKind.Number);
await expect(addOns.content('limit')).toHaveCount(0);
await editor.switchType(PanelKind.TimeSeries);
await expect(addOns.limit()).toHaveValue('7');
// The kind switch already fetched: Run can be a cache hit.
await qb.runButton().click();
await expect.poll(() => qb.latest('A')?.limit).toBe(7);
});
test('TC-26 reduce-to follows the metric type and keeps a choice within it', async ({
dashboards,
metricTypes,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ kind: PanelKind.Table, query: metricsQuery() }),
SINGLE_PANEL_ID,
);
const query = qb.query('A');
await expect(query.addOns.reduceTo.value()).toHaveText(reduceToLabel('Sum'));
await query.addOns.reduceTo.set('Max');
await query.metric.select('signoz_latency_count');
await expect(query.addOns.reduceTo.value()).toHaveText(reduceToLabel('Max'));
await query.metric.select(metricTypes.gauge);
await expect(query.addOns.reduceTo.value()).toHaveText(
reduceToLabel('Average'),
);
await query.metric.select(SUM_METRIC);
await expect(query.addOns.reduceTo.value()).toHaveText(reduceToLabel('Sum'));
expect(qb.spec(await qb.run(), 'A').aggregations?.[0]).toMatchObject({
metricName: SUM_METRIC,
reduceTo: 'sum',
});
});
test('TC-31 switching signal restores the query left on each signal', async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: logsCountQuery({ groupBy: [] }) }),
SINGLE_PANEL_ID,
);
const query = qb.query('A');
await query.filter.type(LOGS_FILTER);
await query.filter.press('Escape');
await query.setSignal('Traces');
await expect.poll(() => query.filter.expression()).toBe('');
await query.filter.type(TRACES_FILTER);
await query.filter.press('Escape');
await query.setSignal('Logs');
await expect.poll(() => query.filter.expression()).toBe(LOGS_FILTER);
await query.setSignal('Traces');
await expect.poll(() => query.filter.expression()).toBe(TRACES_FILTER);
await qb.runButton().click();
await expect
.poll(() => qb.latest('A'))
.toMatchObject({
signal: 'traces',
filter: { expression: TRACES_FILTER },
});
});
test('TC-33 a PromQL query is sent as promql and kept across tab switches', async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: metricsQuery() }),
SINGLE_PANEL_ID,
);
await qb.tab('promql').click();
await qb.promql().fill(PROMQL);
const fired = await qb.run();
expect(fired.at(-1)?.compositeQuery.queries[0]).toMatchObject({
type: 'promql',
spec: { name: 'A', query: PROMQL },
});
await qb.tab('clickhouse_sql').click();
await qb.tab('builder').click();
await expect(qb.query('A').metric.spaceAggregation()).toHaveText('Sum');
await qb.tab('promql').click();
await expect(qb.promql()).toHaveValue(PROMQL);
});
});

View File

@@ -1,80 +0,0 @@
import { expect, EXPLORER, test } from '../../drivers/query-builder';
import {
holdQueryRange,
mockQueryRange,
mockQueryRangeError,
QueryRange,
unmockQueryRange,
} from '../../helpers/query-range-mock';
test.describe('Query builder — run and cancel', () => {
test('TC-34 a held run can be cancelled and the next run goes through', async ({
authedPage: page,
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
const held = await holdQueryRange(page, QueryRange.empty());
await qb.query('A').filter.type("severity_text = 'WARN'");
await qb.query('A').filter.press('Escape');
await qb.runButton().click();
await expect(qb.runButton()).toHaveText('Cancel');
await qb.runButton().click();
await expect(qb.runButton()).toHaveText(/Run Query/);
await expect(qb.logsResults()).toContainText('Query cancelled');
held.release();
await unmockQueryRange(page);
await qb.query('A').filter.type("severity_text = 'ERROR'");
await qb.query('A').filter.press('Escape');
// The cancelled query is re-sent alongside; the newest request wins.
await qb.run();
expect(qb.latest('A')?.filter?.expression).toBe("severity_text = 'ERROR'");
await expect(qb.logsResults()).not.toContainText('Query cancelled');
});
test('TC-35 a failed run keeps the query editable and the next run recovers', async ({
authedPage: page,
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
await mockQueryRangeError(page, 'mocked query failure');
await qb.query('A').filter.type("severity_text = 'INFO'");
await qb.query('A').filter.press('Escape');
await qb.runButton().click();
// The failed request is retried before the error settles.
await expect(qb.runButton()).toHaveText(/Run Query/, { timeout: 20_000 });
await expect(qb.logsResults()).toContainText('mocked query failure');
await expect
.poll(() => qb.query('A').filter.expression())
.toBe("severity_text = 'INFO'");
await unmockQueryRange(page);
await qb.query('A').filter.type("severity_text = 'WARN'");
await qb.query('A').filter.press('Escape');
const fired = await qb.run();
expect(qb.spec(fired, 'A').filter?.expression).toBe("severity_text = 'WARN'");
await expect(qb.logsResults()).not.toContainText('mocked query failure');
});
test('TC-35 an empty result leaves the query unchanged', async ({
authedPage: page,
qb,
}) => {
await qb.openExplorer(EXPLORER.logs);
await mockQueryRange(page, QueryRange.empty());
await qb.query('A').filter.type("service.name = 'nothing-here'");
await qb.query('A').filter.press('Escape');
const fired = await qb.run();
expect(qb.spec(fired, 'A').filter?.expression).toBe(
"service.name = 'nothing-here'",
);
await expect
.poll(() => qb.query('A').filter.expression())
.toBe("service.name = 'nothing-here'");
expect(qb.console.errors).toEqual([]);
});
});

View File

@@ -1,198 +0,0 @@
import { expect, EXPLORER, test } from '../../drivers/query-builder';
// A shared or hand-edited explorer link must never take the page down: the
// param is parsed, repaired and rewritten before the builder mounts.
const MALFORMED: Record<string, string> = {
'not JSON': 'not-json',
'truncated JSON': '%7B',
'a JSON string': encodeURIComponent('"a string"'),
'a JSON array': encodeURIComponent('[]'),
'JSON null': 'null',
'an empty JSON string': '%22%22',
'double encoded': encodeURIComponent(
encodeURIComponent(JSON.stringify({ queryType: 'builder' })),
),
};
const PARTIAL: Record<string, unknown> = {
'an empty object': {},
'builder with no builder block': { queryType: 'builder' },
'builder with no queryData': { queryType: 'builder', builder: {} },
'empty queryData': {
queryType: 'builder',
builder: { queryData: [], queryFormulas: [] },
},
'a query with no dataSource': {
queryType: 'builder',
builder: { queryData: [{ queryName: 'A' }] },
},
'an unknown queryType': { queryType: 'zzz' },
'non-array promql and clickhouse blocks': {
queryType: 'builder',
promql: {},
clickhouse_sql: 'x',
builder: { queryData: [{ queryName: 'A', dataSource: 'logs' }] },
},
};
/**
* Saved before the v5 builder: structured filters, a having array and an
* aggregate operator. The old having filter wrote `columnName` upper-cased
* (`COUNT()`).
*/
const legacyLogsQuery = (having: unknown[]): unknown => ({
queryType: 'builder',
promql: [],
clickhouse_sql: [],
builder: {
queryFormulas: [],
queryData: [
{
queryName: 'A',
dataSource: 'logs',
expression: 'A',
disabled: false,
aggregateOperator: 'count',
aggregateAttribute: { key: '', dataType: '', type: '', isColumn: false },
filters: {
op: 'AND',
items: [
{
id: 'f1',
key: {
key: 'severity_text',
dataType: 'string',
type: '',
isColumn: true,
},
op: '=',
value: 'ERROR',
},
],
},
having,
groupBy: [],
orderBy: [],
functions: [],
legend: '',
limit: null,
stepInterval: 60,
reduceTo: 'avg',
},
],
},
});
const FIRST = "service.name = 'frontend'";
const SECOND = "service.name = 'cartservice'";
interface UrlQuery {
builder?: { queryData?: { filter?: { expression?: string } }[] };
}
test.describe('Query builder — URL handling', () => {
for (const [label, raw] of Object.entries(MALFORMED)) {
test(`TC-01 logs explorer survives ${label} and still runs`, async ({
qb,
}) => {
await qb.openExplorer(EXPLORER.logs, { raw });
await expect(qb.query('A').filter.content()).toBeVisible();
await qb.query('A').filter.type("severity_text = 'ERROR'");
const fired = await qb.run();
expect(qb.spec(fired, 'A').filter?.expression).toBe(
"severity_text = 'ERROR'",
);
expect(qb.urlQuery()).toMatchObject({ queryType: 'builder' });
expect(qb.console.errors).toEqual([]);
});
}
for (const [label, query] of Object.entries(PARTIAL)) {
test(`TC-02 logs explorer repairs ${label}`, async ({ qb }) => {
const loaded = await qb.openExplorer(EXPLORER.logs, { query });
expect(qb.spec(loaded, 'A').signal).toBe('logs');
await expect
.poll(() => qb.urlQuery())
.toMatchObject({
queryType: 'builder',
builder: { queryData: [{ queryName: 'A', dataSource: 'logs' }] },
});
expect(qb.console.errors).toEqual([]);
});
}
test('TC-03 legacy filters and aggregate operator convert to v5 expressions', async ({
qb,
}) => {
const loaded = await qb.openExplorer(EXPLORER.logs, {
view: 'graph',
query: legacyLogsQuery([]),
});
const spec = qb.spec(loaded, 'A');
expect(spec.filter?.expression).toMatch(/^severity_text\s*=\s*'ERROR'$/);
expect(spec.aggregations?.[0]?.expression).toBe('count()');
expect(spec).not.toHaveProperty('filters');
await expect
.poll(() => qb.query('A').filter.expression())
.toMatch(/^severity_text\s*=\s*'ERROR'$/);
expect(qb.console.errors).toEqual([]);
});
// known: convertHavingToExpression keeps the stored `COUNT()` casing, which
// the v5 backend rejects with a 400 ("Invalid references in `Having`").
test.fixme('TC-03 a legacy having as the old builder stored it still runs', async ({
qb,
}) => {
const loaded = await qb.openExplorer(EXPLORER.logs, {
view: 'graph',
query: legacyLogsQuery([{ columnName: 'COUNT()', op: '>', value: 5 }]),
});
expect(qb.spec(loaded, 'A').having?.expression).toMatch(
/^count\(\)\s*>\s*5$/i,
);
expect(qb.console.failedResponses).toEqual([]);
});
for (const explorer of ['logs', 'traces'] as const) {
test(`TC-04 ${explorer} explorer query follows back, forward and reload`, async ({
authedPage: page,
qb,
}) => {
await qb.openExplorer(EXPLORER[explorer]);
const filter = qb.query('A').filter;
const urlFilter = (): unknown =>
(qb.urlQuery() as UrlQuery | null)?.builder?.queryData?.[0]?.filter
?.expression;
await filter.type(FIRST);
await qb.run();
await filter.type(SECOND);
await qb.run();
await page.goBack();
await expect.poll(urlFilter).toBe(FIRST);
await expect.poll(() => filter.expression()).toBe(FIRST);
await page.goForward();
await expect.poll(urlFilter).toBe(SECOND);
await expect.poll(() => filter.expression()).toBe(SECOND);
await filter.type("service.name = 'unsaved'");
const sentBefore = qb.sent().length;
await page.reload();
await expect.poll(() => filter.expression()).toBe(SECOND);
await expect
.poll(() => qb.sent().slice(sentBefore).length)
.toBeGreaterThan(0);
expect(qb.spec(qb.sent().slice(sentBefore), 'A').filter?.expression).toBe(
SECOND,
);
});
}
});