Compare commits

...

5 Commits

Author SHA1 Message Date
Ashwin Bhatkal
fc2d6a9b7b chore(notification-channels): remove useChannelOptions 2026-11-07 10:45:36 +05:30
Ashwin Bhatkal
b8c35ac2c9 feat(routing-policies): search notification channels on the server 2026-11-07 10:45:36 +05:30
Ashwin Bhatkal
d308206291 feat(alerts): search notification channels on the server 2026-11-07 10:45:36 +05:30
Ashwin Bhatkal
1b90a39d20 feat(notification-channels): add a server-side channel search hook 2026-11-07 10:45:36 +05:30
Abhi kumar
d1f4503b40 test(query-builder): add e2e suite for the query builder (#13313)
Some checks failed
build-staging / prepare (push) Has been cancelled
build-staging / js-build (push) Has been cancelled
build-staging / go-build (push) Has been cancelled
build-staging / staging (push) Has been cancelled
cacheci / tests (push) Has been cancelled
Release Drafter / update_release_draft (push) Has been cancelled
#### Description

- Adds a host-agnostic `qb` driver
(`tests/e2e/drivers/query-builder.ts`) and ~110 query builder tests
across the logs, traces and metrics explorers, the V2 panel editor and
alerts. Assertions read the outgoing `query_range` body and the URL
query, never exact counts.
- Covers URL handling (malformed, partial, legacy shapes,
back/forward/reload), the filter editor (suggestions, quoting, IN lists,
nesting, validation, keyboard, recents, quick filters), metric-type
defaults, aggregations, add-ons per panel kind, multi-query and
formulas, trace operator, signal and query-type switching, cross-host
round trips (explorer → dashboard, alert save → reopen) and
run/cancel/error states.
- Each regression-driven case names the fix it guards (#13257, #12705,
#12496, #10048, #9947, #9732, #11208, #9637, #11035, #10100, #12755,
#9066, #8250).
- Seeds a gauge and a histogram per worker (golden metrics are all
sums); exports the seeder's retrying POST for that.
- Shared helper fixes found under load: `pickChannelByName` re-clicks
while the select is still closed; `holdQueryRange` tolerates a request
cancelled while held.

#### Issues closed by this PR

Closes SigNoz/pulse-pod#662

#### Additional Information

- Stacked: #13315 (legacy having and limit fixes) → #13323 (added query
keeps its signal) → this PR. Merge in that order.
- Regression tests for both fixes (legacy having `COUNT() > 5`, negative
limit, added query's signal) fail against the unfixed app.
- Stable across 2 consecutive CI-mode runs on chromium (198 passed, 0
flaky). Meter source switching is not covered yet: the stack has no
meter metrics.
2026-11-06 20:25:12 +00:00
45 changed files with 2843 additions and 583 deletions

View File

@@ -2,7 +2,6 @@ import { ReactNode } from 'react';
import { Button, Tooltip } from 'antd';
import classNames from 'classnames';
import { Activity, ChartLine } from '@signozhq/icons';
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import { useCreateAlertState } from '../context';
@@ -26,13 +25,6 @@ function AlertCondition(): JSX.Element {
const { alertType, setAlertType } = useCreateAlertState();
useAnomalyFunctionSync();
const {
data: channels,
isLoading: isLoadingChannels,
isError: isErrorChannels,
refetch: refreshChannels,
} = useChannelOptions();
const isAnomalyDetectionEnabled = useIsAnomalyDetectionAvailable();
// Anomaly rules stay editable even without a cloud or enterprise license.
@@ -111,22 +103,8 @@ function AlertCondition(): JSX.Element {
))}
</div>
</div>
{alertType !== AlertTypes.ANOMALY_BASED_ALERT && (
<AlertThreshold
channels={channels}
isLoadingChannels={isLoadingChannels}
isErrorChannels={isErrorChannels}
refreshChannels={refreshChannels}
/>
)}
{alertType === AlertTypes.ANOMALY_BASED_ALERT && (
<AnomalyThreshold
channels={channels}
isLoadingChannels={isLoadingChannels}
isErrorChannels={isErrorChannels}
refreshChannels={refreshChannels}
/>
)}
{alertType !== AlertTypes.ANOMALY_BASED_ALERT && <AlertThreshold />}
{alertType === AlertTypes.ANOMALY_BASED_ALERT && <AnomalyThreshold />}
<div className="condensed-advanced-options-container">
<AdvancedOptions />
</div>

View File

@@ -19,7 +19,6 @@ import {
import EvaluationSettings from '../EvaluationSettings/EvaluationSettings';
import { normalizeMatchType, normalizeOperator } from '../utils';
import ThresholdItem from './ThresholdItem';
import { AnomalyAndThresholdProps } from './types';
import { useThresholdList } from './useThresholdList';
import {
getCategoryByOptionId,
@@ -32,12 +31,7 @@ import {
import './styles.scss';
import '../EvaluationSettings/styles.scss';
function AlertThreshold({
channels,
isLoadingChannels,
isErrorChannels,
refreshChannels,
}: AnomalyAndThresholdProps): JSX.Element {
function AlertThreshold(): JSX.Element {
const {
alertState,
thresholdState,
@@ -248,11 +242,7 @@ function AlertThreshold({
updateThreshold={updateThreshold}
removeThreshold={removeThreshold}
showRemoveButton={index !== 0 && thresholdState.thresholds.length > 1}
channels={channels}
isLoadingChannels={isLoadingChannels}
units={categorySelectOptions}
isErrorChannels={isErrorChannels}
refreshChannels={refreshChannels}
/>
))}
<Button

View File

@@ -19,18 +19,12 @@ import {
import EvaluationSettings from '../EvaluationSettings/EvaluationSettings';
import { normalizeMatchType, normalizeOperator } from '../utils';
import ThresholdItem from './ThresholdItem';
import { AnomalyAndThresholdProps } from './types';
import { useThresholdList } from './useThresholdList';
import { getQueryNames, RoutingPolicyBanner } from './utils';
import styles from './AnomalyThreshold.module.scss';
function AnomalyThreshold({
channels,
isLoadingChannels,
isErrorChannels,
refreshChannels,
}: AnomalyAndThresholdProps): JSX.Element {
function AnomalyThreshold(): JSX.Element {
const {
thresholdState,
setThresholdState,
@@ -168,11 +162,7 @@ function AnomalyThreshold({
updateThreshold={updateThreshold}
removeThreshold={removeThreshold}
showRemoveButton={index !== 0 && thresholdState.thresholds.length > 1}
channels={channels}
isLoadingChannels={isLoadingChannels}
units={[]}
isErrorChannels={isErrorChannels}
refreshChannels={refreshChannels}
isAnomaly
/>
))}

View File

@@ -2,7 +2,9 @@ import { useMemo, useState } from 'react';
import { Input } from '@signozhq/ui/input';
import { Button, Select, Tooltip } from 'antd';
import { Typography } from '@signozhq/ui/typography';
import { Spinner } from '@signozhq/ui/spinner';
import { CircleX, Trash } from '@signozhq/icons';
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
import { useAppContext } from 'providers/App/App';
import { useCreateAlertState } from '../context';
@@ -16,16 +18,21 @@ function ThresholdItem({
updateThreshold,
removeThreshold,
showRemoveButton,
channels,
units,
isErrorChannels,
refreshChannels,
isLoadingChannels,
isAnomaly = false,
}: ThresholdItemProps): JSX.Element {
const { user } = useAppContext();
const { thresholdState, notificationSettings } = useCreateAlertState();
const [showRecoveryThreshold, setShowRecoveryThreshold] = useState(false);
const {
options: channelOptions,
searchTerm: channelSearchTerm,
setSearchTerm: setChannelSearchTerm,
isSearching: isSearchingChannels,
isError: isErrorChannels,
refetch: refreshChannels,
loadMoreOnScroll: loadMoreChannelsOnScroll,
} = useChannelSearch();
const yAxisUnitSelect = useMemo(() => {
let component = (
@@ -140,29 +147,38 @@ function ThresholdItem({
}
data-testid="threshold-notification-channel-select"
style={{ width: 350 }}
options={channels.map((channel) => ({
value: channel.name,
label: channel.name,
options={channelOptions.map((option) => ({
...option,
'data-testid': `threshold-notification-channel-option-${threshold.label}`,
}))}
mode="multiple"
placeholder="Select notification channels"
showSearch
searchValue={channelSearchTerm}
onSearch={setChannelSearchTerm}
onSelect={(): void => setChannelSearchTerm('')}
onDropdownVisibleChange={(open): void => {
if (!open) {
setChannelSearchTerm('');
}
}}
onPopupScroll={loadMoreChannelsOnScroll}
filterOption={false}
maxTagCount={2}
maxTagPlaceholder={(omittedValues): string =>
`+${omittedValues.length} more`
}
maxTagTextLength={10}
filterOption={(input, option): boolean =>
option?.label?.toLowerCase().includes(input.toLowerCase()) || false
}
status={isErrorChannels ? 'error' : undefined}
disabled={isLoadingChannels}
notFoundContent={
<NotificationChannelsNotFoundContent
user={user}
refreshChannels={refreshChannels}
/>
isSearchingChannels ? (
<Spinner testId="threshold-notification-channel-spinner" />
) : (
<NotificationChannelsNotFoundContent
user={user}
refreshChannels={refreshChannels}
/>
)
}
/>
</>

View File

@@ -2,7 +2,6 @@ import { QueryClient, QueryClientProvider } from 'react-query';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { TestRouter } from 'tests/router';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import { CreateAlertProvider } from '../../context';
import {
@@ -11,17 +10,6 @@ import {
} from '../../context/constants';
import AlertThreshold from '../AlertThreshold';
const mockChannels: ChannelOption[] = [];
const mockRefreshChannels = jest.fn();
const mockIsLoadingChannels = false;
const mockIsErrorChannels = false;
const mockProps = {
channels: mockChannels,
isLoadingChannels: mockIsLoadingChannels,
isErrorChannels: mockIsErrorChannels,
refreshChannels: mockRefreshChannels,
};
jest.mock('uplot', () => {
const paths = {
spline: jest.fn(),
@@ -88,20 +76,6 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
}),
}));
// Mock getAllChannels API
jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
__esModule: true,
useChannelOptions: jest.fn(() => ({
data: [
{ id: '1', name: 'Email Channel' },
{ id: '2', name: 'Slack Channel' },
] as ChannelOption[],
isLoading: false,
isError: false,
refetch: jest.fn(),
})),
}));
// Mock alert format categories
jest.mock('constants/formats/alertFormatCategories', () => ({
getCategoryByOptionId: jest.fn(() => ({ name: 'bytes' })),
@@ -136,7 +110,7 @@ const renderAlertThreshold = (): ReturnType<typeof render> => {
<TestRouter>
<QueryClientProvider client={queryClient}>
<CreateAlertProvider initialAlertType={AlertTypes.METRICS_BASED_ALERT}>
<AlertThreshold {...mockProps} />
<AlertThreshold />
</CreateAlertProvider>
</QueryClientProvider>
</TestRouter>,
@@ -278,13 +252,6 @@ describe('AlertThreshold', () => {
expect(thresholdItems).toHaveLength(1);
});
it('handles loading state for channels', () => {
renderAlertThreshold();
// Component should render even while channels are loading
expect(screen.getByText('Send a notification when')).toBeInTheDocument();
});
it('renders with correct initial state', () => {
renderAlertThreshold();

View File

@@ -1,6 +1,5 @@
import { createMockAlertContextState } from 'container/CreateAlertV2/EvaluationSettings/__tests__/testUtils';
import { render, screen, userEvent, within } from 'tests/test-utils';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import * as context from '../../context';
import { AlertThresholdMatchType } from '../../context/types';
@@ -49,17 +48,8 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
}),
}));
const channels: ChannelOption[] = [{ id: '1', name: 'slack-alerts' }];
const renderAnomalyThreshold = (): ReturnType<typeof render> =>
render(
<AnomalyThreshold
channels={channels}
isLoadingChannels={false}
isErrorChannels={false}
refreshChannels={jest.fn()}
/>,
);
render(<AnomalyThreshold />);
describe('AnomalyThreshold', () => {
beforeEach(() => {
@@ -144,10 +134,10 @@ describe('AnomalyThreshold', () => {
it('picks channels by name when routing policies are off', async () => {
renderAnomalyThreshold();
await pickOption('threshold-notification-channel-select', 'slack-alerts');
await pickOption('threshold-notification-channel-select', 'Dummy-Channel');
expect(mockSetThresholdState).toHaveBeenCalledWith({
type: 'SET_THRESHOLDS',
payload: [expect.objectContaining({ channels: ['slack-alerts'] })],
payload: [expect.objectContaining({ channels: ['Dummy-Channel'] })],
});
});

View File

@@ -1,9 +1,17 @@
import { fireEvent, render, screen } from '@testing-library/react';
import type { DefaultOptionType } from 'antd/es/select';
import { createMockAlertContextState } from 'container/CreateAlertV2/EvaluationSettings/__tests__/testUtils';
import { getAppContextMockState } from 'container/RoutingPolicies/__tests__/testUtils';
import { notificationChannelsListResponse } from 'mocks-server/__mockdata__/alerts';
import { rest, server } from 'mocks-server/server';
import * as appHooks from 'providers/App/App';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import * as context from '../../context';
import ThresholdItem from '../ThresholdItem';
@@ -38,9 +46,6 @@ const TEST_CONSTANTS = {
WARNING_LABEL: 'WARNING',
INFO_LABEL: 'INFO',
CHANNEL_1: 'channel-1',
CHANNEL_2: 'channel-2',
CHANNEL_3: 'channel-3',
EMAIL_CHANNEL_NAME: 'Email Channel',
EMAIL_CHANNEL_TRUNCATED: 'Email Chan...',
ENTER_THRESHOLD_NAME: 'Enter threshold name',
ENTER_THRESHOLD_VALUE: 'Enter threshold value',
@@ -57,14 +62,8 @@ const mockThreshold = {
color: '#ff0000',
};
const mockChannels: ChannelOption[] = [
{
id: TEST_CONSTANTS.CHANNEL_1,
name: TEST_CONSTANTS.EMAIL_CHANNEL_NAME,
} as any,
{ id: TEST_CONSTANTS.CHANNEL_2, name: 'Slack Channel' } as any,
{ id: TEST_CONSTANTS.CHANNEL_3, name: 'PagerDuty Channel' } as any,
];
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
const CHANNEL_SELECT = 'threshold-notification-channel-select';
const mockUnits: DefaultOptionType[] = [
{ label: 'Bytes', value: 'bytes' },
@@ -77,11 +76,7 @@ const defaultProps: ThresholdItemProps = {
updateThreshold: jest.fn(),
removeThreshold: jest.fn(),
showRemoveButton: false,
channels: mockChannels,
isLoadingChannels: false,
units: mockUnits,
isErrorChannels: false,
refreshChannels: jest.fn(),
};
const renderThresholdItem = (
@@ -106,12 +101,6 @@ const verifySelectorWidth = (
// fireEvent.click(recoveryButton);
// };
const verifyComponentRendersWithLoading = (): void => {
expect(
screen.getByPlaceholderText(TEST_CONSTANTS.ENTER_THRESHOLD_NAME),
).toBeInTheDocument();
};
const verifyUnitSelectorDisabled = (): void => {
const unitSelectors = screen.getAllByRole('combobox');
const unitSelector = unitSelectors[0]; // First combobox is the unit selector
@@ -348,9 +337,106 @@ describe('ThresholdItem', () => {
verifySelectorWidth(0, '150px');
});
it('handles loading channels state', () => {
renderThresholdItem({ isLoadingChannels: true });
verifyComponentRendersWithLoading();
it('searches channels on the server as the user types', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const requests: Record<string, string>[] = [];
server.use(
rest.get(CHANNELS_URL, (req, res, ctx) => {
requests.push(Object.fromEntries(req.url.searchParams));
return res(
ctx.json(
notificationChannelsListResponse(
req.url.searchParams.get('query')
? ['Oncall PagerDuty']
: ['Dummy-Channel', 'Oncall PagerDuty'],
),
),
);
}),
);
renderThresholdItem();
const input = within(screen.getByTestId(CHANNEL_SELECT)).getByRole(
'combobox',
);
await user.click(input);
await screen.findByTitle('Dummy-Channel');
await user.type(input, 'pager');
await expect(
screen.findByTitle('Oncall PagerDuty'),
).resolves.toBeInTheDocument();
expect(screen.queryByTitle('Dummy-Channel')).not.toBeInTheDocument();
expect(requests).toStrictEqual([
expect.not.objectContaining({ query: expect.anything() }),
expect.objectContaining({ query: 'pager', limit: '100', offset: '0' }),
]);
});
it('shows a spinner, not the empty state, while a search is in flight', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(CHANNELS_URL, (req, res, ctx) =>
req.url.searchParams.get('query')
? res(ctx.delay(5_000), ctx.json(notificationChannelsListResponse([])))
: res(ctx.json(notificationChannelsListResponse([]))),
),
);
renderThresholdItem();
const input = within(screen.getByTestId(CHANNEL_SELECT)).getByRole(
'combobox',
);
await user.click(input);
await expect(
screen.findByText('No channels yet.'),
).resolves.toBeInTheDocument();
await user.type(input, 'pager');
expect(
screen.getByTestId('threshold-notification-channel-spinner'),
).toBeInTheDocument();
expect(screen.queryByText('No channels yet.')).not.toBeInTheDocument();
});
it('loads the next page when the list is scrolled to the bottom', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const offsets: string[] = [];
server.use(
rest.get(CHANNELS_URL, (req, res, ctx) => {
const offset = Number(req.url.searchParams.get('offset'));
offsets.push(String(offset));
const names = Array.from(
{ length: offset === 0 ? 100 : 20 },
(_, index) => `channel-${offset + index}`,
);
return res(ctx.json(notificationChannelsListResponse(names, 120)));
}),
);
renderThresholdItem();
await user.click(
within(screen.getByTestId(CHANNEL_SELECT)).getByRole('combobox'),
);
await screen.findByTitle('channel-0');
fireEvent.scroll(
document.querySelector('.rc-virtual-list-holder') as HTMLElement,
);
await waitFor(() => expect(offsets).toStrictEqual(['0', '100']));
});
it('keeps the name of a saved channel the results do not include', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
renderThresholdItem({
threshold: { ...mockThreshold, channels: ['old-pager'] },
});
const select = screen.getByTestId(CHANNEL_SELECT);
await user.click(within(select).getByRole('combobox'));
await screen.findByTitle('Dummy-Channel');
expect(within(select).getByTitle('old-pager')).toHaveTextContent('old-pager');
});
it.skip('renders recovery threshold with correct initial value', () => {

View File

@@ -1,5 +1,4 @@
import type { DefaultOptionType } from 'antd/es/select';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import {
NotificationSettingsAction,
@@ -21,11 +20,7 @@ export interface ThresholdItemProps {
updateThreshold: UpdateThreshold;
removeThreshold: (thresholdId: string) => void;
showRemoveButton: boolean;
channels: ChannelOption[];
isLoadingChannels: boolean;
units: DefaultOptionType[];
isErrorChannels: boolean;
refreshChannels: () => void;
isAnomaly?: boolean;
}
@@ -35,13 +30,6 @@ export interface ThresholdList {
updateThreshold: UpdateThreshold;
}
export interface AnomalyAndThresholdProps {
channels: ChannelOption[];
isLoadingChannels: boolean;
isErrorChannels: boolean;
refreshChannels: () => void;
}
export interface RoutingPolicyBannerProps {
notificationSettings: NotificationSettingsState;
setNotificationSettings: (

View File

@@ -6,11 +6,10 @@ import { Switch } from '@signozhq/ui/switch';
import logEvent from 'api/common/logEvent';
import { ALERTS_DATA_SOURCE_MAP } from 'constants/alerts';
import ROUTES from 'constants/routes';
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
import { useNotificationChannelCollectionPermissions } from 'hooks/notificationChannels/useNotificationChannelCollectionPermissions';
import { AlertTypes } from 'types/api/alerts/alertTypes';
import { AlertDef, Labels } from 'types/api/alerts/def';
import APIError from 'types/api/error';
import { requireErrorMessage } from 'utils/form/requireErrorMessage';
import { openInNewTab } from 'utils/navigation';
import { popupContainer } from 'utils/selectPopupContainer';
@@ -43,13 +42,7 @@ function BasicInfo({
}: BasicInfoProps): JSX.Element {
const { t } = useTranslation('alerts');
const {
isLoading,
data: channels,
error,
isError,
refetch,
} = useChannelOptions();
const { isLoading, total: channelCount } = useChannelSearch();
const { canCreate: addNewChannelPermission } =
useNotificationChannelCollectionPermissions();
@@ -75,7 +68,7 @@ function BasicInfo({
});
};
const noChannels = channels.length === 0;
const noChannels = !channelCount;
const handleCreateNewChannels = useCallback(() => {
logEvent('Alert: Create notification channel button clicked', {
dataSource: ALERTS_DATA_SOURCE_MAP[alertDef?.alertType as AlertTypes],
@@ -88,19 +81,15 @@ function BasicInfo({
useEffect(() => {
if (!isLoading && isNewRule && !hasLoggedEvent.current) {
logEvent('Alert: New alert creation page visited', {
void logEvent('Alert: New alert creation page visited', {
dataSource: ALERTS_DATA_SOURCE_MAP[alertDef?.alertType as AlertTypes],
numberOfChannels: channels.length,
numberOfChannels: channelCount ?? 0,
});
hasLoggedEvent.current = true;
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [isLoading]);
const refetchChannels = async (): Promise<void> => {
await refetch();
};
return (
<>
<StepHeading> {t('alert_form_step4')} </StepHeading>
@@ -220,14 +209,9 @@ function BasicInfo({
]}
>
<ChannelSelect
onDropdownOpen={refetchChannels}
disabled={shouldBroadCastToAllChannels}
currentValue={alertDef.preferredChannels}
handleCreateNewChannels={handleCreateNewChannels}
channels={channels}
isLoading={isLoading}
hasError={isError}
error={error as APIError}
onSelectChannels={(preferredChannels): void => {
setAlertDef({
...alertDef,

View File

@@ -0,0 +1,123 @@
import { setupAuthzDenyAll } from 'lib/authz/utils/authz-test-utils';
import { notificationChannelsListResponse } from 'mocks-server/__mockdata__/alerts';
import { rest, server } from 'mocks-server/server';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import ChannelSelect from '..';
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
const CHANNEL_SELECT = 'alert-channel-select';
const renderChannelSelect = (currentValue: string[] = []): void => {
render(
<ChannelSelect
currentValue={currentValue}
onSelectChannels={jest.fn()}
handleCreateNewChannels={jest.fn()}
/>,
);
};
const channelInput = (): HTMLElement =>
within(screen.getByTestId(CHANNEL_SELECT)).getByRole('combobox');
describe('ChannelSelect', () => {
beforeEach(() => {
server.use(setupAuthzDenyAll());
});
it('searches channels on the server as the user types', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const queries: (string | null)[] = [];
server.use(
rest.get(CHANNELS_URL, (req, res, ctx) => {
const query = req.url.searchParams.get('query');
queries.push(query);
return res(
ctx.json(
notificationChannelsListResponse(
query ? ['Oncall PagerDuty'] : ['Dummy-Channel', 'Oncall PagerDuty'],
),
),
);
}),
);
renderChannelSelect();
await user.click(channelInput());
await screen.findByTitle('Dummy-Channel');
await user.type(channelInput(), 'pager');
await waitFor(() => expect(queries).toContain('pager'));
await expect(
screen.findByTitle('Oncall PagerDuty'),
).resolves.toBeInTheDocument();
expect(screen.queryByTitle('Dummy-Channel')).not.toBeInTheDocument();
});
it('refetches the channels each time the dropdown opens', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
let requestCount = 0;
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) => {
requestCount += 1;
return res(ctx.json(notificationChannelsListResponse(['Dummy-Channel'])));
}),
);
renderChannelSelect();
await waitFor(() => expect(requestCount).toBe(1));
await user.click(channelInput());
await waitFor(() => expect(requestCount).toBe(2));
});
it('loads the next page when the list is scrolled to the bottom', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const offsets: string[] = [];
server.use(
rest.get(CHANNELS_URL, (req, res, ctx) => {
const offset = Number(req.url.searchParams.get('offset'));
offsets.push(String(offset));
const names = Array.from(
{ length: offset === 0 ? 100 : 20 },
(_, index) => `channel-${offset + index}`,
);
return res(ctx.json(notificationChannelsListResponse(names, 120)));
}),
);
renderChannelSelect();
await user.click(channelInput());
await screen.findByTitle('channel-0');
fireEvent.scroll(
document.querySelector('.rc-virtual-list-holder') as HTMLElement,
);
await waitFor(() => expect(offsets).toContain('100'));
});
it('keeps the name of a saved channel the results do not include', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) =>
res(ctx.json(notificationChannelsListResponse(['Dummy-Channel']))),
),
);
renderChannelSelect(['old-pager']);
await user.click(channelInput());
await screen.findByTitle('Dummy-Channel');
expect(
within(screen.getByTestId(CHANNEL_SELECT)).getByTitle('old-pager'),
).toHaveTextContent('old-pager');
});
});

View File

@@ -2,10 +2,10 @@ import { ReactNode } from 'react';
import { useTranslation } from 'react-i18next';
import { Plus } from '@signozhq/icons';
import { Select, Spin } from 'antd';
import { convertToApiError } from 'api/ErrorResponseHandlerForGeneratedAPIs';
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
import { useNotificationChannelCollectionPermissions } from 'hooks/notificationChannels/useNotificationChannelCollectionPermissions';
import { useNotifications } from 'hooks/useNotifications';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import APIError from 'types/api/error';
import { StyledCreateChannelOption, StyledSelect } from './styles';
@@ -13,11 +13,6 @@ export interface ChannelSelectProps {
disabled?: boolean;
currentValue?: string[];
onSelectChannels: (s: string[]) => void;
onDropdownOpen: () => void;
isLoading: boolean;
channels: ChannelOption[];
hasError: boolean;
error: APIError;
handleCreateNewChannels: () => void;
}
@@ -25,17 +20,22 @@ function ChannelSelect({
disabled,
currentValue,
onSelectChannels,
onDropdownOpen,
channels,
isLoading,
hasError,
error,
handleCreateNewChannels,
}: ChannelSelectProps): JSX.Element | null {
// init namespace for translations
const { t } = useTranslation('alerts');
const { notifications } = useNotifications();
const {
options,
searchTerm,
setSearchTerm,
isSearching,
isError: hasError,
error,
refetch,
loadMoreOnScroll,
} = useChannelSearch();
const handleChange = (value: string[]): void => {
if (value.includes('add-new-channel')) {
@@ -46,9 +46,10 @@ function ChannelSelect({
};
if (hasError) {
const apiError = convertToApiError(error);
notifications.error({
message: error?.getErrorCode?.() || 'Error',
description: error?.getErrorMessage?.() || 'Something went wrong',
message: apiError?.getErrorCode?.() || 'Error',
description: apiError?.getErrorMessage?.() || 'Something went wrong',
});
}
@@ -58,7 +59,7 @@ function ChannelSelect({
const renderOptions = (): ReactNode[] => {
const children: ReactNode[] = [];
if (!isLoading && addNewChannelPermission) {
if (!isSearching && addNewChannelPermission) {
children.push(
<Select.Option key="add-new-channel" value="add-new-channel">
<StyledCreateChannelOption>
@@ -69,14 +70,10 @@ function ChannelSelect({
);
}
if (isLoading || channels.length === 0) {
return children;
}
channels.forEach((o) => {
options.forEach((o) => {
children.push(
<Select.Option key={o.id} value={o.name}>
{o.name}
<Select.Option key={o.value} value={o.value}>
{o.label}
</Select.Option>,
);
});
@@ -93,10 +90,17 @@ function ChannelSelect({
placeholder={t('placeholder_channel_select')}
data-testid="alert-channel-select"
value={currentValue}
notFoundContent={isLoading && <Spin size="small" />}
searchValue={searchTerm}
onSearch={setSearchTerm}
onSelect={(): void => setSearchTerm('')}
filterOption={false}
onPopupScroll={loadMoreOnScroll}
notFoundContent={isSearching && <Spin size="small" />}
onDropdownVisibleChange={(open): void => {
if (open) {
onDropdownOpen();
refetch();
} else {
setSearchTerm('');
}
}}
onChange={(value): void => {

View File

@@ -33,11 +33,6 @@ function RoutingPolicies(): JSX.Element {
isFetchingRoutingPolicies,
isErrorRoutingPolicies,
refetchRoutingPolicies,
// Channels
channels,
isLoadingChannels,
isErrorChannels,
refreshChannels,
// Search
searchTerm,
setSearchTerm,
@@ -169,12 +164,8 @@ function RoutingPolicies(): JSX.Element {
routingPolicy={selectedRoutingPolicy}
closeModal={handlePolicyDetailsModalClose}
mode={policyDetailsModalState.mode}
channels={channels}
isErrorChannels={isErrorChannels}
isLoadingChannels={isLoadingChannels}
handlePolicyDetailsModalAction={handlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={isPolicyDetailsModalActionLoading}
refreshChannels={refreshChannels}
/>
)}
{isDeleteModalOpen && (

View File

@@ -1,9 +1,11 @@
import { useMemo } from 'react';
import { Button, Flex, Form, Input, Modal, Select } from 'antd';
import { Spinner } from '@signozhq/ui/spinner';
import { Typography } from '@signozhq/ui/typography';
import ROUTES from 'constants/routes';
import { ModalTitle } from 'container/PipelinePage/PipelineListsView/styles';
import { Check, Loader, X } from '@signozhq/icons';
import { useChannelSearch } from 'hooks/notificationChannels/useChannelSearch';
import { useAppContext } from 'providers/App/App';
import { USER_ROLES } from 'types/roles';
import { openInNewTab } from 'utils/navigation';
@@ -17,16 +19,21 @@ import {
function RoutingPolicyDetails({
closeModal,
mode,
channels,
isErrorChannels,
isLoadingChannels,
routingPolicy,
handlePolicyDetailsModalAction,
isPolicyDetailsModalActionLoading,
refreshChannels,
}: RoutingPolicyDetailsProps): JSX.Element {
const [form] = Form.useForm();
const { user } = useAppContext();
const {
options: channelOptions,
searchTerm: channelSearchTerm,
setSearchTerm: setChannelSearchTerm,
isSearching: isSearchingChannels,
isError: isErrorChannels,
refetch: refreshChannels,
loadMoreOnScroll: loadMoreChannelsOnScroll,
} = useChannelSearch();
const initialFormState = useMemo(() => {
if (mode === 'edit') {
@@ -163,24 +170,34 @@ function RoutingPolicyDetails({
]}
>
<Select
options={channels.map((channel) => ({
value: channel.name,
label: channel.name,
}))}
options={channelOptions}
mode="multiple"
placeholder="Select notification channels"
data-testid="routing-policy-channel-select"
showSearch
searchValue={channelSearchTerm}
onSearch={setChannelSearchTerm}
onSelect={(): void => setChannelSearchTerm('')}
onDropdownVisibleChange={(open): void => {
if (!open) {
setChannelSearchTerm('');
}
}}
onPopupScroll={loadMoreChannelsOnScroll}
filterOption={false}
maxTagCount={3}
maxTagPlaceholder={(omittedValues): string =>
`+${omittedValues.length} more`
}
maxTagTextLength={10}
filterOption={(input, option): boolean =>
option?.label?.toLowerCase().includes(input.toLowerCase()) || false
}
status={isErrorChannels ? 'error' : undefined}
disabled={isLoadingChannels}
notFoundContent={notificationChannelsNotFoundContent}
notFoundContent={
isSearchingChannels ? (
<Spinner testId="routing-policy-channel-spinner" />
) : (
notificationChannelsNotFoundContent
)
}
/>
</Form.Item>
</div>

View File

@@ -1,43 +1,66 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { notificationChannelsListResponse } from 'mocks-server/__mockdata__/alerts';
import { rest, server } from 'mocks-server/server';
import * as appHooks from 'providers/App/App';
import {
fireEvent,
render,
screen,
userEvent,
waitFor,
within,
} from 'tests/test-utils';
import RoutingPolicyDetails from '../RoutingPolicyDetails';
import {
getAppContextMockState,
MOCK_CHANNEL_1,
MOCK_CHANNEL_2,
MOCK_ROUTING_POLICY_1,
} from './testUtils';
import { RoutingPolicyDetailsProps } from '../types';
import { getAppContextMockState, MOCK_ROUTING_POLICY_1 } from './testUtils';
jest.spyOn(appHooks, 'useAppContext').mockReturnValue(getAppContextMockState());
const mockHandlePolicyDetailsModalAction = jest.fn();
const mockCloseModal = jest.fn();
const mockChannels = [MOCK_CHANNEL_1, MOCK_CHANNEL_2];
const mockRoutingPolicy = MOCK_ROUTING_POLICY_1;
const mockRefreshChannels = jest.fn();
const CHANNELS_URL = 'http://localhost/api/v2/notification_channels';
const CHANNEL_SELECT = 'routing-policy-channel-select';
const CHANNEL_NAMES = ['Channel 1', 'Channel 2'];
const NEW_NAME = 'New Name';
const NEW_EXPRESSION = 'New Expression';
const NEW_DESCRIPTION = 'New Description';
const SAVE_BUTTON_TEXT = 'Save Routing Policy';
const NO_CHANNELS_FOUND_TEXT = 'No channels yet.';
const serveChannels = (names: string[]): void => {
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) =>
res(ctx.json(notificationChannelsListResponse(names))),
),
);
};
const renderRoutingPolicyDetails = (
props: Partial<RoutingPolicyDetailsProps> = {},
): ReturnType<typeof render> =>
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
{...props}
/>,
);
const channelInput = (): HTMLElement =>
within(screen.getByTestId(CHANNEL_SELECT)).getByRole('combobox');
describe('RoutingPolicyDetails', () => {
beforeEach(() => {
serveChannels(CHANNEL_NAMES);
});
it('renders base create layout with header, 3 inputs and footer', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails();
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByText('Create routing policy')).toBeInTheDocument();
@@ -51,19 +74,7 @@ describe('RoutingPolicyDetails', () => {
});
it('renders base edit layout with header, 3 inputs and footer', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="edit"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails({ mode: 'edit' });
expect(screen.getByRole('dialog')).toBeInTheDocument();
expect(screen.getByText('Edit routing policy')).toBeInTheDocument();
@@ -78,19 +89,7 @@ describe('RoutingPolicyDetails', () => {
});
it('prefills inputs with existing policy values in edit mode', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="edit"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails({ mode: 'edit' });
const nameInput = screen.getByDisplayValue(mockRoutingPolicy.name);
expect(nameInput).toBeInTheDocument();
@@ -100,23 +99,11 @@ describe('RoutingPolicyDetails', () => {
);
expect(expressionTextarea).toBeInTheDocument();
expect(screen.getByText(MOCK_CHANNEL_1.name)).toBeInTheDocument();
expect(screen.getByText(CHANNEL_NAMES[0])).toBeInTheDocument();
});
it('creating and saving the routing policy works correctly', async () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails();
const nameInput = screen.getByPlaceholderText('e.g. Base routing policy...');
expect(nameInput).toBeInTheDocument();
@@ -135,8 +122,7 @@ describe('RoutingPolicyDetails', () => {
fireEvent.change(expressionTextarea, { target: { value: NEW_EXPRESSION } });
fireEvent.change(descriptionTextarea, { target: { value: NEW_DESCRIPTION } });
const channelSelect = screen.getByRole('combobox');
fireEvent.mouseDown(channelSelect);
fireEvent.mouseDown(channelInput());
const channelOptions = await screen.findAllByText('Channel 1');
fireEvent.click(channelOptions[1]);
@@ -164,19 +150,7 @@ describe('RoutingPolicyDetails', () => {
});
it('editing and saving the routing policy works correctly', async () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="edit"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails({ mode: 'edit' });
const nameInput = screen.getByDisplayValue(mockRoutingPolicy.name);
expect(nameInput).toBeInTheDocument();
@@ -219,19 +193,7 @@ describe('RoutingPolicyDetails', () => {
});
it('should close modal when cancel button is clicked', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="edit"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails({ mode: 'edit' });
const cancelButton = screen.getByRole('button', { name: 'Cancel' });
fireEvent.click(cancelButton);
@@ -239,19 +201,10 @@ describe('RoutingPolicyDetails', () => {
});
it('buttons should be disabled when loading', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="edit"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails({
mode: 'edit',
isPolicyDetailsModalActionLoading: true,
});
const cancelButton = screen.getByRole('button', { name: 'Cancel' });
expect(cancelButton).toBeDisabled();
@@ -268,19 +221,7 @@ describe('RoutingPolicyDetails', () => {
});
it('submit should not be called when inputs are invalid', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={mockChannels}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
renderRoutingPolicyDetails();
const saveButton = screen.getByRole('button', {
name: SAVE_BUTTON_TEXT,
@@ -290,139 +231,155 @@ describe('RoutingPolicyDetails', () => {
expect(mockHandlePolicyDetailsModalAction).not.toHaveBeenCalled();
});
it('notification channels select should be disabled when channels are loading', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={[]}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels
refreshChannels={mockRefreshChannels}
/>,
it('shows a spinner in the channel list while channels load', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) =>
res(ctx.delay(1_000), ctx.json(notificationChannelsListResponse([]))),
),
);
renderRoutingPolicyDetails();
const channelSelect = screen.getByRole('combobox');
expect(channelSelect).toBeDisabled();
await user.click(channelInput());
expect(
screen.getByTestId('routing-policy-channel-spinner'),
).toBeInTheDocument();
expect(screen.queryByText(NO_CHANNELS_FOUND_TEXT)).not.toBeInTheDocument();
});
it('should show error state when channels fail to load', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={[]}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
it('should show error state when channels fail to load', async () => {
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) =>
res(ctx.status(500), ctx.json({ status: 'error' })),
),
);
renderRoutingPolicyDetails();
const channelSelect = screen.getByRole('combobox');
const selectContainer = channelSelect.closest('.ant-select');
expect(selectContainer).toHaveClass('ant-select-status-error');
await waitFor(() =>
expect(screen.getByTestId(CHANNEL_SELECT)).toHaveClass(
'ant-select-status-error',
),
);
});
it('should show empty state when no channels are available', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={[]}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
it('should show empty state when no channels are available', async () => {
serveChannels([]);
renderRoutingPolicyDetails();
const channelSelect = screen.getByRole('combobox');
fireEvent.mouseDown(channelSelect);
fireEvent.mouseDown(channelInput());
expect(screen.getByText(NO_CHANNELS_FOUND_TEXT)).toBeInTheDocument();
await expect(
screen.findByText(NO_CHANNELS_FOUND_TEXT),
).resolves.toBeInTheDocument();
});
it('should show create channel button for admin users in empty state', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={[]}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
it('should show create channel button for admin users in empty state', async () => {
serveChannels([]);
renderRoutingPolicyDetails();
const channelSelect = screen.getByRole('combobox');
fireEvent.mouseDown(channelSelect);
fireEvent.mouseDown(channelInput());
expect(screen.getByText(NO_CHANNELS_FOUND_TEXT)).toBeInTheDocument();
await expect(
screen.findByText(NO_CHANNELS_FOUND_TEXT),
).resolves.toBeInTheDocument();
expect(screen.getByText('Create one')).toBeInTheDocument();
});
it('should show admin message for non-admin users in empty state', () => {
it('should show admin message for non-admin users in empty state', async () => {
jest
.spyOn(appHooks, 'useAppContext')
.mockReturnValue(getAppContextMockState({ role: 'VIEWER' }));
serveChannels([]);
renderRoutingPolicyDetails();
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={[]}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
);
fireEvent.mouseDown(channelInput());
const channelSelect = screen.getByRole('combobox');
fireEvent.mouseDown(channelSelect);
expect(screen.getByText(NO_CHANNELS_FOUND_TEXT)).toBeInTheDocument();
await expect(
screen.findByText(NO_CHANNELS_FOUND_TEXT),
).resolves.toBeInTheDocument();
expect(
screen.getByText('Please ask your admin to create one.'),
).toBeInTheDocument();
expect(screen.queryByText('Create one')).not.toBeInTheDocument();
});
it('should call refreshChannels when refresh button is clicked in empty state', () => {
render(
<RoutingPolicyDetails
routingPolicy={mockRoutingPolicy}
closeModal={mockCloseModal}
mode="create"
channels={[]}
handlePolicyDetailsModalAction={mockHandlePolicyDetailsModalAction}
isPolicyDetailsModalActionLoading={false}
isErrorChannels={false}
isLoadingChannels={false}
refreshChannels={mockRefreshChannels}
/>,
it('refetches channels when refresh is clicked in empty state', async () => {
let requestCount = 0;
server.use(
rest.get(CHANNELS_URL, (_req, res, ctx) => {
requestCount += 1;
return res(ctx.json(notificationChannelsListResponse([])));
}),
);
renderRoutingPolicyDetails();
fireEvent.mouseDown(channelInput());
fireEvent.click(await screen.findByText('Refresh'));
await waitFor(() => expect(requestCount).toBe(2));
});
it('searches channels on the server as the user types', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const queries: (string | null)[] = [];
server.use(
rest.get(CHANNELS_URL, (req, res, ctx) => {
const query = req.url.searchParams.get('query');
queries.push(query);
return res(
ctx.json(
notificationChannelsListResponse(query ? ['Channel 2'] : CHANNEL_NAMES),
),
);
}),
);
renderRoutingPolicyDetails();
await user.click(channelInput());
await screen.findByTitle('Channel 1');
await user.type(channelInput(), '2');
await expect(screen.findByTitle('Channel 2')).resolves.toBeInTheDocument();
expect(screen.queryByTitle('Channel 1')).not.toBeInTheDocument();
expect(queries).toStrictEqual([null, '2']);
});
it('loads the next page when the list is scrolled to the bottom', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
const offsets: string[] = [];
server.use(
rest.get(CHANNELS_URL, (req, res, ctx) => {
const offset = Number(req.url.searchParams.get('offset'));
offsets.push(String(offset));
const names = Array.from(
{ length: offset === 0 ? 100 : 20 },
(_, index) => `channel-${offset + index}`,
);
return res(ctx.json(notificationChannelsListResponse(names, 120)));
}),
);
renderRoutingPolicyDetails();
await user.click(channelInput());
await screen.findByTitle('channel-0');
fireEvent.scroll(
document.querySelector('.rc-virtual-list-holder') as HTMLElement,
);
const channelSelect = screen.getByRole('combobox');
fireEvent.mouseDown(channelSelect);
await waitFor(() => expect(offsets).toStrictEqual(['0', '100']));
});
const refreshButton = screen.getByText('Refresh');
expect(refreshButton).toBeInTheDocument();
it('keeps the name of a saved channel the results do not include', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
serveChannels(['Channel 2']);
renderRoutingPolicyDetails({ mode: 'edit' });
fireEvent.click(refreshButton);
expect(mockRefreshChannels).toHaveBeenCalledTimes(1);
await user.click(channelInput());
await screen.findByTitle('Channel 2');
expect(
within(screen.getByTestId(CHANNEL_SELECT)).getByTitle('Channel 1'),
).toHaveTextContent('Channel 1');
});
});

View File

@@ -1,6 +1,5 @@
import { ApiRoutingPolicy } from 'api/routingPolicies/getRoutingPolicies';
import { IAppContext, IUser } from 'providers/App/types';
import { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
import { RoutingPolicy, UseRoutingPoliciesReturn } from '../types';
@@ -28,15 +27,6 @@ export const MOCK_ROUTING_POLICY_2: RoutingPolicy = {
updatedBy: 'user2@signoz.io',
};
export const MOCK_CHANNEL_1: ChannelOption = {
name: 'Channel 1',
id: '1',
};
export const MOCK_CHANNEL_2: ChannelOption = {
name: 'Channel 2',
id: '2',
};
export function getUseRoutingPoliciesMockData(
overrides?: Partial<UseRoutingPoliciesReturn>,
): UseRoutingPoliciesReturn {
@@ -45,8 +35,6 @@ export function getUseRoutingPoliciesMockData(
routingPoliciesData: [MOCK_ROUTING_POLICY_1, MOCK_ROUTING_POLICY_2],
isLoadingRoutingPolicies: false,
isErrorRoutingPolicies: false,
channels: [MOCK_CHANNEL_1, MOCK_CHANNEL_2],
isLoadingChannels: false,
searchTerm: '',
setSearchTerm: jest.fn(),
isDeleteModalOpen: false,
@@ -62,8 +50,6 @@ export function getUseRoutingPoliciesMockData(
handlePolicyDetailsModalOpen: jest.fn(),
handlePolicyDetailsModalAction: jest.fn(),
isPolicyDetailsModalActionLoading: false,
isErrorChannels: false,
refreshChannels: jest.fn(),
isFetchingRoutingPolicies: false,
refetchRoutingPolicies: jest.fn(),
...overrides,

View File

@@ -13,8 +13,6 @@ import { UseRoutingPoliciesReturn } from '../types';
import useRoutingPolicies from '../useRoutingPolicies';
import {
convertRoutingPolicyToApiResponse,
MOCK_CHANNEL_1,
MOCK_CHANNEL_2,
MOCK_ROUTING_POLICY_1,
MOCK_ROUTING_POLICY_2,
} from './testUtils';
@@ -73,15 +71,6 @@ jest.mock('hooks/routingPolicies/useDeleteRoutingPolicy', () => ({
isLoading: false,
}),
}));
jest.mock('hooks/notificationChannels/useChannelOptions', () => ({
__esModule: true,
useChannelOptions: (): any => ({
data: [MOCK_CHANNEL_1, MOCK_CHANNEL_2],
isLoading: false,
isError: false,
refetch: jest.fn(),
}),
}));
const ROUTING_POLICY_1_NAME = 'Routing Policy 1';
const TEST_SEARCH_TERM = 'test search';

View File

@@ -1,6 +1,5 @@
import type { AlertmanagertypesGettableRoutePolicyDTO } from 'api/generated/services/sigNoz.schemas';
import type { TableColumnDef } from 'components/TanStackTableView';
import type { ChannelOption } from 'hooks/notificationChannels/useChannelOptions';
export type RoutingPolicy = AlertmanagertypesGettableRoutePolicyDTO;
@@ -44,12 +43,8 @@ export interface RoutingPolicyDetailsProps {
routingPolicy: RoutingPolicy | null;
closeModal: () => void;
mode: PolicyDetailsModalMode;
channels: ChannelOption[];
isErrorChannels: boolean;
isLoadingChannels: boolean;
handlePolicyDetailsModalAction: HandlePolicyDetailsModalAction;
isPolicyDetailsModalActionLoading: boolean;
refreshChannels: () => void;
}
export interface DeleteRoutingPolicyProps {
@@ -67,11 +62,6 @@ export interface UseRoutingPoliciesReturn {
isFetchingRoutingPolicies: boolean;
isErrorRoutingPolicies: boolean;
refetchRoutingPolicies: () => void;
// Channels
channels: ChannelOption[];
isLoadingChannels: boolean;
isErrorChannels: boolean;
refreshChannels: () => void;
// Search
searchTerm: string;
setSearchTerm: (searchTerm: string) => void;

View File

@@ -7,7 +7,6 @@ import { GetRoutingPoliciesResponse } from 'api/routingPolicies/getRoutingPolici
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useCreateRoutingPolicy } from 'hooks/routingPolicies/useCreateRoutingPolicy';
import { useDeleteRoutingPolicy } from 'hooks/routingPolicies/useDeleteRoutingPolicy';
import { useChannelOptions } from 'hooks/notificationChannels/useChannelOptions';
import { useGetRoutingPolicies } from 'hooks/routingPolicies/useGetRoutingPolicies';
import { useUpdateRoutingPolicy } from 'hooks/routingPolicies/useUpdateRoutingPolicy';
import useDebouncedFn from 'hooks/useDebouncedFunction';
@@ -93,18 +92,6 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
);
}, [routingPolicies, searchTerm]);
// Channels list
const {
data: channels,
isLoading: isLoadingChannels,
isError: isErrorChannels,
refetch: refetchChannels,
} = useChannelOptions();
const refreshChannels = (): void => {
void refetchChannels();
};
// Handlers
const handlePolicyDetailsModalOpen = useCallback(
(mode: PolicyDetailsModalMode, routingPolicy: RoutingPolicy | null): void => {
@@ -243,11 +230,6 @@ function useRoutingPolicies(): UseRoutingPoliciesReturn {
isFetchingRoutingPolicies,
isErrorRoutingPolicies,
refetchRoutingPolicies,
// Channels
channels,
isLoadingChannels,
isErrorChannels,
refreshChannels,
// Search
searchTerm,
setSearchTerm: handleSearch,

View File

@@ -1,68 +0,0 @@
import { useQuery, UseQueryResult } from 'react-query';
import { listNotificationChannels } from 'api/generated/services/channels';
import {
AlertmanagertypesChannelListOrderDTO,
AlertmanagertypesChannelListSortDTO,
AlertmanagertypesListedNotificationChannelDTO,
} from 'api/generated/services/sigNoz.schemas';
import { range } from 'lodash-es';
const PAGE_SIZE = 100;
export const CHANNEL_OPTIONS_QUERY_KEY = ['notificationChannelOptions'];
export interface ChannelOption {
id: string;
/** The display name, which is what rules and routing policies reference. */
name: string;
}
export type UseChannelOptionsResult = Omit<
UseQueryResult<ChannelOption[], Error>,
'data'
> & {
data: ChannelOption[];
};
function fetchPage(
offset: number,
): ReturnType<typeof listNotificationChannels> {
return listNotificationChannels({
limit: PAGE_SIZE,
offset,
sort: AlertmanagertypesChannelListSortDTO.name,
order: AlertmanagertypesChannelListOrderDTO.asc,
});
}
/**
* Every channel, for the pickers that let a rule or a policy name one. The list
* API is paginated and silently clamps a larger limit, so the first page reports
* the total and any remainder is fetched alongside rather than truncating. One
* request covers an org with a page's worth of channels or fewer.
*/
async function fetchAllChannels(): Promise<ChannelOption[]> {
const first = await fetchPage(0);
const rest = await Promise.all(
range(PAGE_SIZE, first.data.total, PAGE_SIZE).map(fetchPage),
);
const channels: AlertmanagertypesListedNotificationChannelDTO[] = [
...first.data.channels,
...rest.flatMap((page) => page.data.channels),
];
return channels.map((channel) => ({
id: channel.id,
name: channel.displayName,
}));
}
export function useChannelOptions(): UseChannelOptionsResult {
const query = useQuery<ChannelOption[], Error>(
CHANNEL_OPTIONS_QUERY_KEY,
fetchAllChannels,
);
return { ...query, data: query.data ?? [] };
}

View File

@@ -0,0 +1,121 @@
import { UIEvent, useCallback, useMemo, useState } from 'react';
import { useInfiniteQuery } from 'react-query';
import {
listNotificationChannels,
ListNotificationChannelsQueryError,
} from 'api/generated/services/channels';
import {
AlertmanagertypesChannelListOrderDTO,
AlertmanagertypesChannelListSortDTO,
ListNotificationChannelsParams,
} from 'api/generated/services/sigNoz.schemas';
import useDebounce from 'hooks/useDebounce';
const PAGE_SIZE = 100;
const SEARCH_DEBOUNCE_MS = 300;
const LOAD_MORE_THRESHOLD_PX = 40;
export interface ChannelSelectOption {
/** What a rule or routing policy stores: today the display name. */
value: string;
label: string;
}
export interface UseChannelSearchResult {
options: ChannelSelectOption[];
/** How many channels match the current search, across every page. */
total: number | undefined;
searchTerm: string;
setSearchTerm: (term: string) => void;
/** A typed term is waiting on the debounce or on its first page. */
isSearching: boolean;
isLoading: boolean;
isError: boolean;
error: ListNotificationChannelsQueryError | null;
refetch: () => void;
loadMoreOnScroll: (event: UIEvent<HTMLDivElement>) => void;
}
export function useChannelSearch(): UseChannelSearchResult {
const [searchTerm, setSearchTerm] = useState('');
const trimmedTerm = searchTerm.trim();
const debouncedTerm = useDebounce(trimmedTerm, SEARCH_DEBOUNCE_MS);
// Clearing the box skips the debounce: the unfiltered list is already cached.
const query = trimmedTerm ? debouncedTerm : '';
const params: ListNotificationChannelsParams = {
query: query || undefined,
limit: PAGE_SIZE,
sort: AlertmanagertypesChannelListSortDTO.name,
order: AlertmanagertypesChannelListOrderDTO.asc,
};
const {
data,
isLoading,
isError,
error,
refetch,
hasNextPage,
isFetchingNextPage,
fetchNextPage,
} = useInfiniteQuery<
Awaited<ReturnType<typeof listNotificationChannels>>,
ListNotificationChannelsQueryError
>({
queryKey: ['notificationChannelSearch', params],
queryFn: ({ pageParam = 0, signal }) =>
listNotificationChannels({ ...params, offset: pageParam }, signal),
getNextPageParam: (lastPage, allPages) => {
const loaded = allPages.reduce(
(count, page) => count + page.data.channels.length,
0,
);
return lastPage.data.channels.length > 0 && loaded < lastPage.data.total
? loaded
: undefined;
},
});
const isSearching = trimmedTerm !== query || isLoading;
const options = useMemo(
() =>
isSearching
? []
: (data?.pages ?? []).flatMap((page) =>
page.data.channels.map((channel) => ({
value: channel.displayName,
label: channel.displayName,
})),
),
[data, isSearching],
);
const loadMoreOnScroll = useCallback(
(event: UIEvent<HTMLDivElement>): void => {
const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
if (
hasNextPage &&
!isFetchingNextPage &&
scrollHeight - scrollTop - clientHeight < LOAD_MORE_THRESHOLD_PX
) {
void fetchNextPage();
}
},
[hasNextPage, isFetchingNextPage, fetchNextPage],
);
return {
options,
total: data?.pages[0]?.data.total,
searchTerm,
setSearchTerm,
isSearching,
isLoading,
isError,
error,
refetch,
loadMoreOnScroll,
};
}

View File

@@ -1,3 +1,8 @@
import {
AlertmanagertypesChannelKindDTO,
ListNotificationChannels200,
} from 'api/generated/services/sigNoz.schemas';
export const editAlertChannelInitialValue = {
api_url:
'https://discord.com/api/webhooks/dummy_webhook_id/dummy_webhook_token/slack',
@@ -59,6 +64,25 @@ export const notificationChannelsV2 = [
},
];
/** A v2 list page with one channel per display name. */
export const notificationChannelsListResponse = (
displayNames: string[],
total = displayNames.length,
): ListNotificationChannels200 => ({
status: 'success',
data: {
channels: displayNames.map((displayName, index) => ({
id: `channel-${index}`,
name: displayName.toLowerCase(),
displayName,
kind: AlertmanagertypesChannelKindDTO.slack,
createdAt: '2024-02-03T04:45:19.239344617Z',
updatedAt: '2024-06-28T11:37:14.841184399Z',
})),
total,
},
});
export const notificationChannelV2 = {
id: '3',
name: 'dummy-channel',

View File

@@ -24,7 +24,7 @@ import {
import {
alertRuleByIdResponse,
ALERT_SCHEMAS,
notificationChannelsResponse,
notificationChannelsPage,
CHANNEL_MAX,
FIRST_RULE_NAME,
type AlertSchema,
@@ -149,7 +149,9 @@ export const alertHistoryMocks = defineStoryMocks({
rest.get(
'http://localhost/api/v2/notification_channels',
response.json(() => notificationChannelsResponse(CHANNEL_MAX)),
response.json((req) =>
notificationChannelsPage(CHANNEL_MAX, req.url.searchParams),
),
),
],
config: () => ({

View File

@@ -12,7 +12,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import {
alertRuleByIdResponse,
ALERT_SCHEMAS,
notificationChannelsResponse,
notificationChannelsPage,
CHANNEL_MAX,
RULE_KINDS,
RULE_STATE_CHOICES,
@@ -127,7 +127,9 @@ export const alertOverviewMocks = defineStoryMocks({
rest.get(
'http://localhost/api/v2/notification_channels',
response.json(() => notificationChannelsResponse(values.channels)),
response.json((req) =>
notificationChannelsPage(values.channels, req.url.searchParams),
),
),
rest.post(

View File

@@ -18,7 +18,7 @@ import {
import {
CHANNEL_MAX,
channelNames,
notificationChannelsResponse,
notificationChannelsPage,
} from '../../stories/__story_mockdata__/alerts';
import { AlertListSubTabs, AlertListTabs } from '../../types';
@@ -119,10 +119,12 @@ export const routingPoliciesMocks = defineStoryMocks({
: res(ctx.status(200), ctx.json({ status: 'success', data: null })),
),
rest.get('http://localhost/api/v2/notification_channels', (_req, res, ctx) =>
rest.get('http://localhost/api/v2/notification_channels', (req, res, ctx) =>
values.channelsState === 'error'
? res(ctx.status(500), ctx.json({ status: 'error' }))
: res(ctx.json(notificationChannelsResponse(values.channels))),
: res(
ctx.json(notificationChannelsPage(values.channels, req.url.searchParams)),
),
),
],
config: () => ({

View File

@@ -781,23 +781,6 @@ const buildListedChannel = (
};
};
/** The v2 list, which is what the redesigned channels list reads. */
export const notificationChannelsResponse = (
count: number,
): {
status: string;
data: {
channels: AlertmanagertypesListedNotificationChannelDTO[];
total: number;
};
} => {
const channels = Array.from({ length: count }, (_unused, index) =>
buildListedChannel(index),
);
return { status: 'success', data: { channels, total: channels.length } };
};
/**
* The v2 list as the API answers it: search, kind and paging are applied on the
* server, so the story has to narrow the rows rather than hand back all of them.

View File

@@ -21,7 +21,7 @@ import {
alertPreviewSeries,
} from '../../AlertList/stories/__story_mockdata__/alertQuery';
import {
notificationChannelsResponse,
notificationChannelsPage,
CHANNEL_MAX,
} from '../../AlertList/stories/__story_mockdata__/alerts';
@@ -128,7 +128,9 @@ export const createAlertMocks = defineStoryMocks({
rest.get(
'http://localhost/api/v2/notification_channels',
response.json(() => notificationChannelsResponse(values.channels)),
response.json((req) =>
notificationChannelsPage(values.channels, req.url.searchParams),
),
),
rest.post(

View File

@@ -20,7 +20,7 @@ import {
import {
alertRuleByIdResponse,
ALERT_SCHEMAS,
notificationChannelsResponse,
notificationChannelsPage,
CHANNEL_MAX,
type AlertSchema,
} from '../../AlertList/stories/__story_mockdata__/alerts';
@@ -78,7 +78,9 @@ export const editRulesMocks = defineStoryMocks({
rest.get(
'http://localhost/api/v2/notification_channels',
response.json(() => notificationChannelsResponse(values.channels)),
response.json((req) =>
notificationChannelsPage(values.channels, req.url.searchParams),
),
),
rest.post(

View File

@@ -64,8 +64,17 @@ export function antdDriver(page: Page): Antd {
*/
pickByName: async (select, name) => {
const before = await antd.selectedTags(select).count();
await select.click();
await expect(select).toHaveClass(/ant-select-open/);
// A re-render of the surrounding form (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 });
// `fill` rather than `keyboard.type`: every keystroke re-runs antd's
// filter, so typing a ~30 character name costs seconds per pick, while

261
tests/e2e/drivers/query-builder.ts generated Normal file
View File

@@ -0,0 +1,261 @@
/**
* 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 { watchConsole } from './console';
import { isQueryRange } from './query-range-mock';
import { dismissQuickFiltersAnnouncement } from './logs/explorer';
import { driver, kit } from './kit';
import { EXPLORER, RELATIVE_TIME } from './query-builder/constants';
import {
addOnsAt,
exactly,
metricAt,
openSelect,
} from './query-builder/controls';
import { afterRender, editorAt } from './query-builder/editor';
import type { QueryBuilderDriver, V5Body } from './query-builder/types';
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),
);
export const test = withQueryBuilder(kit);
export { expect } from './kit';
export * from './query-builder/constants';
export * from './query-builder/types';
export { reduceToLabel } from './query-builder/controls';
export { withMetricTypes } from './query-builder/seed';

View File

@@ -0,0 +1,17 @@
/**
* 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.
*/
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';
/** Inside the golden dataset's window. */
export const RELATIVE_TIME = '6h';

View File

@@ -0,0 +1,136 @@
/**
* 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 } from '@playwright/test';
import { antdDriver } from '../antd';
import { editorAt } from './editor';
import type { AddOnField, AddOns, MetricControls } from './types';
/**
* 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.
*/
export async function openSelect(
page: Page,
select: Locator,
): Promise<Locator> {
await select.locator('.ant-select-selector').click();
const list = await antdDriver(page).ownDropdown(select);
await expect(list).toBeVisible();
return list.locator('.ant-select-item-option');
}
/** antd renders select options with trailing whitespace ("Sum "). */
export 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',
};
export 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;
}
export 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());
},
};
}

View File

@@ -0,0 +1,77 @@
/**
* 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 } from '@playwright/test';
import type { FilterEditor } from './types';
/** 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');
};
export 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;
}
/**
* 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.
*/
export 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()));
}),
);
}

50
tests/e2e/drivers/query-builder/seed.ts generated Normal file
View File

@@ -0,0 +1,50 @@
/**
* 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 { postToSeeder } from '../telemetry';
import { seeded } from '../kit';
import type { MetricTypes } from './types';
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.request, '/telemetry/metrics', points);
return types;
},
);

225
tests/e2e/drivers/query-builder/types.ts generated Normal file
View File

@@ -0,0 +1,225 @@
/**
* 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 type { Locator } from '@playwright/test';
import type { ConsoleWatch } from '../console';
/** The golden dataset has only Sums; these are seeded per worker. */
export interface MetricTypes {
gauge: string;
histogram: string;
}
/** 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;
}

View File

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

View File

@@ -0,0 +1,154 @@
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');
});
test('TC-24 a limit input drops the sign of a negative number', 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('-5');
await expect(addOns.limit()).toHaveValue('5');
expect(qb.spec(await qb.run(), 'A').limit).toBe(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

@@ -0,0 +1,80 @@
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

@@ -0,0 +1,76 @@
import { AlertType, expect, test as alertsTest } from '../../drivers/alerts';
import { withQueryBuilder } from '../../drivers/query-builder';
const test = withQueryBuilder(alertsTest);
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,
alerts,
alertChannel,
ownedRules,
qb,
}) => {
await alerts.form.gotoV2({ alertType: AlertType.TRACES });
await alerts.form.name().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 alerts.form.selectThresholdChannel(0, alertChannel.name);
const [response] = await Promise.all([
page.waitForResponse(
(r) => r.url().includes('/api/v2/rules') && r.request().method() === 'POST',
),
alerts.form.saveButton().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 alerts.details.gotoOverview(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

@@ -0,0 +1,72 @@
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

@@ -0,0 +1,284 @@
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

@@ -0,0 +1,106 @@
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

@@ -0,0 +1,136 @@
import {
logsCountQuery,
metricsQuery,
SINGLE_PANEL_ID,
singlePanelDashboard,
test as editorTest,
} from '../../drivers/panel-editor';
import {
expect,
OTHER_SUM_METRIC,
SUM_METRIC,
withQueryBuilder,
} from '../../drivers/query-builder';
// An added query continues the previous query's signal. On these metrics
// panels it starts with no metric, and Run does nothing until one is picked.
const test = withQueryBuilder(editorTest);
const SIGNAL_LABEL = { logs: 'Logs', traces: 'Traces' } as const;
const CLONED_FILTER = "operation = '/ads/get'";
test.describe('Query builder — multiple queries', () => {
for (const signal of ['logs', 'traces'] as const) {
test(`TC-28 a query added to a ${signal} panel stays ${signal}`, async ({
dashboards,
qb,
}) => {
await dashboards.seedAndEdit(
singlePanelDashboard({ query: logsCountQuery({ signal }) }),
SINGLE_PANEL_ID,
);
const added = await qb.addQuery('B');
await expect(added.signal()).toHaveText(SIGNAL_LABEL[signal]);
await expect(added.aggregation.root()).toBeVisible();
await expect(added.metric.input()).toHaveCount(0);
await added.filter.type("service.name = 'frontend'");
await added.filter.press('Escape');
await qb.rerunUntil(() => qb.latest('B')?.signal, signal);
});
}
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

@@ -0,0 +1,203 @@
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

@@ -0,0 +1,80 @@
import { expect, EXPLORER, test } from '../../drivers/query-builder';
import {
holdQueryRange,
mockQueryRange,
mockQueryRangeError,
QueryRange,
unmockQueryRange,
} from '../../drivers/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

@@ -0,0 +1,194 @@
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([]);
});
test('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).toBe('count() > 5');
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,
);
});
}
});