Compare commits

...

8 Commits

30 changed files with 2980 additions and 638 deletions

View File

@@ -1,5 +1,4 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
@@ -8,9 +7,21 @@ import ROUTES from 'constants/routes';
import { DataSource } from 'types/common/queryBuilder';
import { QueryBuilderV2 } from '../QueryBuilderV2';
import { traceMatchingQuery } from './__story_mockdata__/queryBuilder';
import {
expectLogsCount,
expectLogsQuery,
expectMeterQuery,
expectMetricsQuery,
expectPanelEditorQuery,
expectTraceMatching,
expectTracesQuery,
hoverAddFormula,
hoverAddFunction,
hoverAddTraceMatching,
} from './__story_mockdata__/queryBuilder.play';
import {
DEFAULT_ARGS,
expectFirstQuery,
meterQuery,
PANEL_EDITOR_ARGS,
PANEL_EDITOR_PATH,
@@ -49,12 +60,7 @@ export const LogsExplorer: Story = {
parameters: {
signoz: { route: routeWith(ROUTES.LOGS_EXPLORER, initialQueriesMap.logs) },
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, {
signal: 'logs',
aggregations: [{ expression: 'count()' }],
});
},
play: expectLogsCount,
};
/** Traces explorer: a fixed traces signal, with trace matching offered. */
@@ -68,9 +74,7 @@ export const TracesExplorer: Story = {
route: routeWith(ROUTES.TRACES_EXPLORER, initialQueriesMap.traces),
},
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'traces' });
},
play: expectTracesQuery,
};
/** Metrics explorer: a fixed metrics signal, functions hidden. */
@@ -87,9 +91,7 @@ export const MetricsExplorer: Story = {
),
},
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'metrics' });
},
play: expectMetricsQuery,
};
/** Meter explorer: metrics read from the meter source. */
@@ -105,9 +107,7 @@ export const MeterExplorer: Story = {
parameters: {
signoz: { route: routeWith(ROUTES.METER_EXPLORER, meterQuery) },
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'metrics', source: 'meter' });
},
play: expectMeterQuery,
};
/**
@@ -121,12 +121,7 @@ export const PanelEditor: Story = {
route: routeWith(PANEL_EDITOR_PATH, initialQueriesMap.logs),
},
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
await expect(
within(canvasElement).getByTestId('query-data-source-selector-0'),
).toBeVisible();
},
play: expectPanelEditorQuery,
};
/** Logs alert: a fixed logs signal with functions, as the alert form mounts it. */
@@ -139,7 +134,54 @@ export const LogsAlert: Story = {
parameters: {
signoz: { route: routeWith(ROUTES.ALERTS_NEW, initialQueriesMap.logs) },
},
play: async ({ canvasElement }) => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
},
play: expectLogsQuery,
};
const TRACES_EXPLORER_ARGS = {
config: { initialDataSource: DataSource.TRACES, queryVariant: 'static' },
showTraceOperator: true,
} as const;
/** Traces explorer with trace matching: two queries joined by `A => B`. */
export const TraceMatching: Story = {
args: TRACES_EXPLORER_ARGS,
parameters: {
signoz: { route: routeWith(ROUTES.TRACES_EXPLORER, traceMatchingQuery) },
},
play: expectTraceMatching,
};
/** The tooltip on Add Formula, with its Learn more link. */
export const AddFormulaTooltip: Story = {
args: TRACES_EXPLORER_ARGS,
parameters: {
signoz: {
route: routeWith(ROUTES.TRACES_EXPLORER, initialQueriesMap.traces),
},
},
play: hoverAddFormula,
};
/** The tooltip on Add Trace Matching, with its Learn more link. */
export const AddTraceMatchingTooltip: Story = {
args: TRACES_EXPLORER_ARGS,
parameters: {
signoz: {
route: routeWith(ROUTES.TRACES_EXPLORER, initialQueriesMap.traces),
},
},
play: hoverAddTraceMatching,
};
/** The tooltip on a query's add-function button, with its Learn more link. */
export const AddFunctionTooltip: Story = {
args: {
config: { initialDataSource: DataSource.LOGS, queryVariant: 'static' },
showFunctions: true,
signalSourceChangeEnabled: true,
},
parameters: {
signoz: { route: routeWith(ROUTES.ALERTS_NEW, initialQueriesMap.logs) },
},
play: hoverAddFunction,
};

View File

@@ -0,0 +1,199 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { DataSource } from 'types/common/queryBuilder';
import type { QueryBuilderV2 } from '../../QueryBuilderV2';
import { QueryBuilderField } from '../../queryBuilderFields.types';
import {
mergeQueryBuilderFieldsConfig,
RAW_QUERY_FIELDS,
ResolvedQueryBuilderField,
resolveQueryBuilderField,
} from '../../queryBuilderFields.utils';
import { expectFirstQuery, payloadIn } from '../QueryBuilderV2.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: Partial<Parameters<typeof QueryBuilderV2>[0]>;
}
export const expectLogsCount = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, {
signal: 'logs',
aggregations: [{ expression: 'count()' }],
});
};
export const expectLogsQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
};
export const expectTracesQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'traces' });
};
export const expectMetricsQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'metrics' });
};
export const expectMeterQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'metrics', source: 'meter' });
};
export const expectPanelEditorQuery = async ({
canvasElement,
}: PlayContext): Promise<void> => {
await expectFirstQuery(canvasElement, { signal: 'logs' });
await expect(
within(canvasElement).getByTestId('query-data-source-selector-0'),
).toBeVisible();
};
/** The operator renders only where the host offers trace matching. */
export const expectTraceMatching = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!args.showTraceOperator) {
return;
}
await expect(
await within(canvasElement).findByTestId('trace-operator'),
).toBeVisible();
await waitFor(() =>
expect(payloadIn(canvasElement).queries).toContainEqual(
expect.objectContaining({
type: 'builder_trace_operator',
spec: expect.objectContaining({ expression: 'A => B' }),
}),
),
);
};
const hoverForLearnMore = async (
target: HTMLElement,
title: string,
): Promise<void> => {
await userEvent.hover(target);
await waitFor(async () => {
const tooltip = (await screen.findAllByRole('tooltip')).find((element) =>
element.textContent?.includes(title),
);
await expect(tooltip).toBeDefined();
await expect(
within(tooltip as HTMLElement).getByText('Learn more'),
).toBeVisible();
});
};
const resolvedField = (
args: PlayContext['args'],
field: QueryBuilderField,
): ResolvedQueryBuilderField =>
resolveQueryBuilderField(
field,
mergeQueryBuilderFieldsConfig(
args.isRawQuery ? RAW_QUERY_FIELDS : undefined,
args.fieldsConfig,
),
);
const isTracesBuilder = (args: PlayContext['args']): boolean =>
args.config?.queryVariant === 'static' &&
args.config.initialDataSource === DataSource.TRACES;
const canShowTraceOperator = (args: PlayContext['args']): boolean =>
Boolean(args.showTraceOperator) &&
!resolvedField(args, QueryBuilderField.TraceOperator).hidden;
const isFooterShown = (args: PlayContext['args']): boolean =>
(!args.showOnlyWhereClause && !args.isRawQuery) ||
(isTracesBuilder(args) && canShowTraceOperator(args));
/** A disabled Add Formula shows its reason instead of the Learn more tooltip. */
export const hoverAddFormula = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
const formula = resolvedField(args, QueryBuilderField.Formula);
if (
!isFooterShown(args) ||
formula.hidden ||
formula.disabled ||
(isTracesBuilder(args) && args.isRawQuery)
) {
return;
}
await hoverForLearnMore(
await within(canvasElement).findByTestId('add-formula-button'),
'Add New Formula',
);
};
/** Add Trace Matching is offered only with trace matching on and no operator yet. */
export const hoverAddTraceMatching = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canShowTraceOperator(args) || !isFooterShown(args)) {
return;
}
const button = await waitFor(() => {
const element = canvasElement.querySelector<HTMLElement>(
'.add-trace-operator-button',
);
if (!element) {
throw new Error('Add Trace Matching not rendered');
}
return element;
});
await hoverForLearnMore(button, 'Add Trace Matching');
};
/** The function picker sits in the query's options row when functions are shown. */
export const hoverAddFunction = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!args.showFunctions) {
return;
}
const button = await waitFor(() => {
const element = within(canvasElement)
.getByTestId('query-A')
.querySelector<HTMLElement>('.add-function-btn');
if (!element) {
throw new Error('Add function not rendered');
}
return element;
});
await hoverForLearnMore(button, 'Add new function');
};

View File

@@ -0,0 +1,37 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
initialQueriesMap,
initialQueryBuilderFormTraceOperatorValues,
} from 'constants/queryBuilder';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
const [tracesQuery] = initialQueriesMap.traces.builder.queryData;
/** Two traces queries joined by a trace operator: a span of A with a descendant from B. */
export const traceMatchingQuery: Query = {
...initialQueriesMap.traces,
builder: {
...initialQueriesMap.traces.builder,
queryData: [
{
...tracesQuery,
queryName: 'A',
expression: 'A',
filter: { expression: "service.name = 'frontend'" },
},
{
...tracesQuery,
queryName: 'B',
expression: 'B',
filter: { expression: "service.name = 'payments' AND has_error = true" },
},
],
queryTraceOperator: [
{ ...initialQueryBuilderFormTraceOperatorValues, expression: 'A => B' },
],
},
};

View File

@@ -17,6 +17,7 @@ import {
} from '@/storybook/msw/__story_mockdata__/fields';
import { quickFiltersResponse } from '@/storybook/msw/__story_mockdata__/quickFilters';
import { DEFAULT_VISIBLE_ITEMS_COUNT } from '../FilterRenderers/Checkbox/constants';
import { FiltersType, QuickFilterCheckboxUseFieldApis } from '../types';
const customFilters = [
@@ -137,3 +138,9 @@ export const selectedServiceQueryBuilder = {
},
},
};
/** More values than the checkbox filter shows before Show More. */
export const MANY_FILTER_VALUES = Array.from(
{ length: 2 * DEFAULT_VISIBLE_ITEMS_COUNT + 5 },
(_, index) => `service-${String(index + 1).padStart(2, '0')}`,
);

View File

@@ -1,11 +1,15 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import type { ComponentProps, ComponentType } from 'react';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import type { GlobalMockArgs } from '@/storybook/globals';
import QuickFilters from '../QuickFilters';
import {
dirtySettings,
openQueryPicker,
openSettings,
} from './__story_mockdata__/quickFilters.play';
import {
checkboxConfig,
fieldApis,
@@ -13,6 +17,7 @@ import {
handlers,
LONG_FILTER_VALUES,
loadingFiltersHandlers,
MANY_FILTER_VALUES,
queryBuilder,
selectedServiceQueryBuilder,
noSavedFiltersHandler,
@@ -47,40 +52,18 @@ export default meta;
type Story = StoryObj<typeof meta>;
type TooltipsStory = StoryObj<
type GlobalArgsStory = StoryObj<
ComponentProps<typeof QuickFilters> & GlobalMockArgs
>;
/**
* The settings control renders disabled while its permission check is in
* flight and is swapped for the enabled one once the check answers, so it is
* looked up again on every attempt; a click on the disabled one is dropped in
* silence.
*/
const settingsControl = (canvasElement: HTMLElement): Promise<HTMLElement> =>
waitFor(() => {
const control = within(canvasElement).getByTestId('settings-icon-container');
expect(control).not.toHaveAttribute('aria-disabled', 'true');
return control;
});
/** Interaction: the settings panel is opened through the admin settings control. */
export const SettingsOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(await settingsControl(canvasElement));
await screen.findByText('Edit quick filters');
},
export const SettingsOpen: GlobalArgsStory = {
play: openSettings,
};
/** Mutation: changing the settings list reveals the fixed save and discard footer. */
export const SettingsDirtyFooter: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(await settingsControl(canvasElement));
await userEvent.click(await screen.findByRole('button', { name: 'Add' }));
await screen.findByRole('button', { name: 'Save changes' });
},
export const SettingsDirtyFooter: GlobalArgsStory = {
play: dirtySettings,
};
/** Loading: dynamic filters are intentionally left pending to display the panel skeleton. */
@@ -100,6 +83,28 @@ export const NoResults: Story = {
},
};
/** A filter with more values than it lists at first: the value search and Show More. */
export const ShowMoreValues: Story = {
parameters: {
msw: {
handlers: [
noSavedFiltersHandler,
fieldValuesHandler(MANY_FILTER_VALUES),
...handlers,
],
},
},
};
/** A filter whose attribute has no values in the time range. */
export const NoValuesFound: Story = {
parameters: {
msw: {
handlers: [noSavedFiltersHandler, fieldValuesHandler([]), ...handlers],
},
},
};
/** Selection: an expanded checkbox shows the actual selected service values. */
export const SelectedExpandedCheckbox: Story = {
parameters: {
@@ -116,7 +121,7 @@ export const SelectedExpandedCheckbox: Story = {
* service names long enough to be cut. The Service name filter carries them, so
* the workspace's own saved filter list is answered empty.
*/
export const Tooltips: TooltipsStory = {
export const Tooltips: GlobalArgsStory = {
args: { tooltipsOpen: true },
parameters: {
msw: {
@@ -132,7 +137,7 @@ export const Tooltips: TooltipsStory = {
const [firstQuery] = queryBuilder.currentQuery.builder.queryData;
/** Interaction: the query picker lists every query the filters can follow. */
export const QueryPickerOpen: Story = {
export const QueryPickerOpen: GlobalArgsStory = {
parameters: {
signoz: {
queryBuilder: {
@@ -148,18 +153,5 @@ export const QueryPickerOpen: Story = {
},
},
},
play: async ({ canvasElement }): Promise<void> => {
const trigger = await waitFor(() => {
const element = canvasElement.querySelector<HTMLElement>(
'[data-slot="combobox-trigger"]',
);
expect(element).toBeInTheDocument();
return element as HTMLElement;
});
await userEvent.click(trigger);
await screen.findByRole('listbox');
},
play: openQueryPicker,
};

View File

@@ -0,0 +1,79 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import type { ComponentProps } from 'react';
import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import type { GlobalMockArgs } from '@/storybook/globals';
import type QuickFilters from '../../QuickFilters';
interface PlayContext {
canvasElement: HTMLElement;
args: ComponentProps<typeof QuickFilters> & GlobalMockArgs;
}
const UNTIL_LOADED = { timeout: 15_000 };
/** The settings control stays enabled when the check itself fails. */
const canManageQuickFilters = (args: PlayContext['args']): boolean =>
args.authzState === 'error' ||
grantsAll(args, ...QuickFilterManagePermissions);
/**
* The settings control renders disabled while its permission check is in
* flight and is swapped for the enabled one once the check answers, so it is
* looked up again on every attempt; a click on the disabled one is dropped in
* silence.
*/
const settingsControl = (canvasElement: HTMLElement): Promise<HTMLElement> =>
waitFor(async () => {
const control = within(canvasElement).getByTestId('settings-icon-container');
await expect(control).not.toHaveAttribute('aria-disabled', 'true');
return control;
}, UNTIL_LOADED);
export const openSettings = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!canManageQuickFilters(args)) {
return;
}
await userEvent.click(await settingsControl(canvasElement));
await screen.findByText('Edit quick filters');
};
export const dirtySettings = async (context: PlayContext): Promise<void> => {
if (!canManageQuickFilters(context.args)) {
return;
}
await openSettings(context);
await userEvent.click(await screen.findByRole('button', { name: 'Add' }));
await screen.findByRole('button', { name: 'Save changes' });
};
export const openQueryPicker = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const trigger = await waitFor(async () => {
const element = canvasElement.querySelector<HTMLElement>(
'[data-slot="combobox-trigger"]',
);
await expect(element).toBeInTheDocument();
return element as HTMLElement;
});
await userEvent.click(trigger);
await screen.findByRole('listbox');
};

View File

@@ -3,7 +3,13 @@
* Do not hand-edit: regenerate instead.
*/
import { rest, type RequestHandler } from 'msw';
import {
rest,
type RequestHandler,
type ResponseResolver,
type RestContext,
type RestRequest,
} from 'msw';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import remove from 'api/browser/localstorage/remove';
import {
@@ -18,9 +24,10 @@ import {
AUTHZ_CHECK_URL,
authzMockResponse,
} from 'lib/authz/utils/authz-test-utils';
import { SavedViewListPermission } from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { accessFor } from '@/storybook/access/access';
import { accessFor, grantsAll } from '@/storybook/access/access';
import {
choiceControl,
countControl,
@@ -30,6 +37,7 @@ import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { MockControlValues, StoryMocks } from '@/storybook/controls/types';
import { withCanvas } from '@/storybook/decorators/withCanvas';
import { authzMocks, type AuthzArgs } from '@/storybook/globals/authzMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { respondWith } from '@/storybook/runtime/responseState';
import {
@@ -45,7 +53,12 @@ import {
savedViewsListResponse,
type SavedViewSource,
unreadableViewId,
VIEW_QUERIES,
type ViewQuery,
withLongName,
WRITE_ERRORS,
WRITE_STATES,
type WriteState,
} from './__story_mockdata__/savedViews';
import SavedViewsHeader from '../SavedViewsHeader';
@@ -56,6 +69,7 @@ const API = 'http://localhost/api/v2/saved_views';
const LIST = 'Saved Views · list';
const VIEW = 'Saved Views · open view';
const WRITES = 'Saved Views · writes';
const controls = {
source: choiceControl<SavedViewSource>('Source', {
@@ -100,12 +114,42 @@ const controls = {
'Lengthens every view name past the sidebar width, so rows and the open view name truncate.',
value: false,
}),
viewQueries: choiceControl<ViewQuery>('View queries', {
group: LIST,
description:
'What every view saved: one filtered query, a query with no filter, which the hover card shows as No filters, or two filtered queries, which it lists by query name.',
options: VIEW_QUERIES,
value: 'filtered',
}),
writes: choiceControl<WriteState>('Writes', {
group: WRITES,
description:
'How creating, updating and deleting a view answer. `success` raises their toast, `loading` never answers, `error` answers a 500 and raises the failure toast.',
options: WRITE_STATES,
value: 'success',
}),
};
type SavedViewsValues = MockControlValues<typeof controls>;
type WrittenView = Pick<SavedviewtypesSavedViewDTO, 'spec' | 'source'>;
const gated =
(
state: WriteState,
error: (typeof WRITE_ERRORS)[keyof typeof WRITE_ERRORS],
success: ResponseResolver<RestRequest, RestContext>,
): ResponseResolver<RestRequest, RestContext> =>
(req, res, ctx) => {
if (state === 'loading') {
return res(ctx.delay('infinite'));
}
return state === 'error'
? res(ctx.status(500), ctx.json(error))
: success(req, res, ctx);
};
const viewDenied = (
transaction: AuthtypesTransactionDTO,
deniedId: string,
@@ -127,6 +171,8 @@ const definition = defineStoryMocks({
createdByMe,
createdByOthers,
longNames,
viewQueries,
writes,
} = values;
// What the panel writes stays in this handler set until a control changes.
@@ -143,7 +189,7 @@ const definition = defineStoryMocks({
): SavedviewtypesSavedViewDTO => (longNames ? withLongName(view) : view);
const findView = (id: string): SavedviewtypesSavedViewDTO | undefined => {
const stored = savedViewById(id);
const stored = savedViewById(id, viewQueries);
const view =
created.find((item) => item.id === id) ?? (stored && named(stored));
@@ -153,19 +199,27 @@ const definition = defineStoryMocks({
const openError = OPEN_VIEW_ERRORS[openView];
return [
rest.post(API, async (req, res, ctx) => {
const body = (await req.json()) as SavedviewtypesUpdatableSavedViewDTO;
const id = `storybook-${source}-created-${created.length + 1}`;
rest.post(
API,
gated(writes, WRITE_ERRORS.create, async (req, res, ctx) => {
const body = (await req.json()) as SavedviewtypesUpdatableSavedViewDTO;
const id = `storybook-${source}-created-${created.length + 1}`;
created.push(createdSavedView(source, id, body.spec));
created.push(createdSavedView(source, id, body.spec));
return res(ctx.status(201), ctx.json({ status: 'success', data: { id } }));
}),
return res(ctx.status(201), ctx.json({ status: 'success', data: { id } }));
}),
),
rest.get(
API,
response.json(() => {
const list = savedViewsListResponse(source, createdByMe, createdByOthers);
const list = savedViewsListResponse(
source,
createdByMe,
createdByOthers,
viewQueries,
);
return {
...list,
@@ -194,22 +248,28 @@ const definition = defineStoryMocks({
return response.json(() => savedViewResponse(view))(req, res, ctx);
}),
rest.put(`${API}/:id`, async (req, res, ctx) => {
const body = (await req.json()) as SavedviewtypesUpdatableSavedViewDTO;
rest.put(
`${API}/:id`,
gated(writes, WRITE_ERRORS.update, async (req, res, ctx) => {
const body = (await req.json()) as SavedviewtypesUpdatableSavedViewDTO;
updated.set(String(req.params.id), {
spec: body.spec,
source: body.source,
});
updated.set(String(req.params.id), {
spec: body.spec,
source: body.source,
});
return res(ctx.status(204));
}),
return res(ctx.status(204));
}),
),
rest.delete(`${API}/:id`, (req, res, ctx) => {
deleted.add(String(req.params.id));
rest.delete(
`${API}/:id`,
gated(writes, WRITE_ERRORS.delete, (req, res, ctx) => {
deleted.add(String(req.params.id));
return res(ctx.status(204));
}),
return res(ctx.status(204));
}),
),
...(values.unreadableView
? [
@@ -237,8 +297,8 @@ const definition = defineStoryMocks({
: []),
];
},
config: ({ source, openView }) => ({
route: savedViewRoute(source, openView),
config: ({ source, openView, viewQueries }) => ({
route: savedViewRoute(source, openView, viewQueries),
}),
effect: () => {
remove(LOCALSTORAGE.LAST_USED_SAVED_VIEWS);
@@ -255,6 +315,14 @@ export const savedViewsMocks: StoryMocks<typeof controls> = {
read: (args) => ({ ...authzMocks.read(args), ...definition.read(args) }),
};
export type SavedViewsArgs = PageStoryArgs<typeof savedViewsMocks>;
/** The list renders rows once it loads with at least one view the user may list. */
export const listsViews = (args: SavedViewsArgs): boolean =>
args.dataState === 'loaded' &&
args.createdByMe + args.createdByOthers > 0 &&
grantsAll(args, SavedViewListPermission);
/** The sidebar slot of an explorer without quick filters. */
export const sidebarCanvas = withCanvas({
width: 280,
@@ -334,7 +402,7 @@ export const rowName =
(): HTMLElement =>
within(row).getByTestId('saved-views-row-name');
const hoverRow = async (row: HTMLElement): Promise<HTMLElement> => {
export const hoverRow = async (row: HTMLElement): Promise<HTMLElement> => {
await userEvent.hover(row);
return screen.findByTestId('saved-view-hover-card', undefined, UNTIL_LOADED);
@@ -389,19 +457,6 @@ type PlayContext = {
args: { source: SavedViewSource };
};
export const hoverFirstRow = async ({
canvasElement,
}: PlayContext): Promise<void> => {
const [row] = await findRows(canvasElement);
const card = await hoverRow(row);
await within(card).findByTestId(
'saved-view-hover-card-query',
undefined,
UNTIL_LOADED,
);
};
export const hoverFirstRowLoading = async ({
canvasElement,
}: PlayContext): Promise<void> => {

View File

@@ -1,27 +1,28 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import SavedViewsPanel from '../SavedViewsPanel';
import {
findRows,
hoverFirstRow,
copyFirstViewLink,
deleteFirstView,
hoverFirstRowQuery,
openFirstRowMenu,
showSaveChangesMenu,
} from './__story_mockdata__/savedViews.play';
import {
hoverFirstRowLoading,
openCreateModal,
openDeleteDialog,
openEditDetailsModal,
openRowMenu,
openSaveAsNewModal,
openSaveChangesMenu,
type SavedViewsArgs,
SavedViewsSidebar,
savedViewsMocks,
searchWithNoResults,
sidebarCanvas,
} from './SavedViews.stories.mocks';
type SavedViewsArgs = PageStoryArgs<typeof savedViewsMocks>;
const componentStory = storyMocks(savedViewsMocks);
/**
@@ -68,11 +69,7 @@ export const UnsavedChanges: Story = {
* that view, so revoking either disables its item.
*/
export const RowMenu: Story = {
play: async ({ canvasElement }): Promise<void> => {
const [row] = await findRows(canvasElement);
await openRowMenu(row);
},
play: openFirstRowMenu,
};
/**
@@ -81,9 +78,7 @@ export const RowMenu: Story = {
*/
export const SaveChangesMenu: Story = {
args: { openView: 'unsaved-changes' },
play: async ({ canvasElement }): Promise<void> => {
await openSaveChangesMenu(canvasElement);
},
play: showSaveChangesMenu,
};
/**
@@ -96,7 +91,19 @@ export const LongNames: Story = {
/** The hover card of the first row: its query, who updated it and when. */
export const HoverCard: Story = {
play: hoverFirstRow,
play: hoverFirstRowQuery,
};
/** The hover card of a view saved without a filter: No filters in place of the query. */
export const HoverCardNoFilters: Story = {
args: { viewQueries: 'no-filters' },
play: hoverFirstRowQuery,
};
/** The hover card of a view with two queries, each filter under its query name. */
export const HoverCardMultiQuery: Story = {
args: { viewQueries: 'multi-query' },
play: hoverFirstRowQuery,
};
/** The hover card while its view is still loading: a skeleton in place of the query. */
@@ -130,3 +137,26 @@ export const SaveAsNewModal: Story = {
export const DeleteDialog: Story = {
play: openDeleteDialog,
};
/** Copy link from a row's menu raises the Link copied toast. */
export const LinkCopiedToast: Story = {
play: copyFirstViewLink,
};
/** A confirmed delete the server refuses: the failure toast, the dialog still open. */
export const DeleteFailedToast: Story = {
args: { writes: 'error' },
parameters: { allowConsoleErrors: true },
play: deleteFirstView,
};
/** The list while it loads: skeleton rows under the search. */
export const Loading: Story = {
args: { dataState: 'loading' },
};
/** A list that failed to load: Could not load views, with Retry. */
export const Error: Story = {
args: { dataState: 'error' },
parameters: { allowConsoleErrors: true },
};

View File

@@ -0,0 +1,180 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
buildSavedViewDeletePermission,
buildSavedViewReadPermission,
} from 'lib/authz/hooks/useAuthZ/permissions/saved-view.permissions';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import {
byTestId,
expectDisabled,
expectPending,
findRows,
hoverRow,
listsViews,
openRowMenu,
openSaveChangesMenu,
rowMenuItem,
type SavedViewsArgs,
UNTIL_LOADED,
} from '../SavedViews.stories.mocks';
import { OPEN_VIEW_ERRORS, unreadableViewId, WRITE_ERRORS } from './savedViews';
interface PlayContext {
canvasElement: HTMLElement;
args: SavedViewsArgs;
}
const DELETE_TOAST = {
success: 'View deleted',
error: WRITE_ERRORS.delete.error.message,
} as const;
const firstRow = async (canvasElement: HTMLElement): Promise<HTMLElement> => {
const [row] = await findRows(canvasElement);
return row;
};
const viewIdOf = (row: HTMLElement): string =>
row.getAttribute('data-view-id') ?? '';
const expectToast = (text: string): Promise<void> =>
waitFor(
async () => expect(screen.getByText(text)).toBeVisible(),
UNTIL_LOADED,
);
export const openFirstRowMenu = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsViews(args)) {
return;
}
await openRowMenu(await firstRow(canvasElement));
};
/** The ✓ menu exists only while the open view loads and differs from the url. */
export const showSaveChangesMenu = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (
args.openView !== 'unsaved-changes' ||
args.dataState !== 'loaded' ||
args.authzState !== 'loaded' ||
args.viewPending
) {
return;
}
await openSaveChangesMenu(canvasElement);
};
/**
* The hover card shows the query only when the view loads and its read is
* granted; otherwise it holds the skeleton, the error or the permission callout.
*/
export const hoverFirstRowQuery = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsViews(args) || args.viewPending || OPEN_VIEW_ERRORS[args.openView]) {
return;
}
const row = await firstRow(canvasElement);
const id = viewIdOf(row);
if (
(args.unreadableView && id === unreadableViewId(args.source)) ||
!grantsAll(args, buildSavedViewReadPermission(id))
) {
return;
}
const card = await hoverRow(row);
const query = await within(card).findByTestId(
'saved-view-hover-card-query',
undefined,
UNTIL_LOADED,
);
const expected = {
filtered: [],
'no-filters': ['No filters'],
'multi-query': ['A', 'B'],
}[args.viewQueries];
await waitFor(async () => {
for (const text of expected) {
await expect(within(query).getByText(text)).toBeVisible();
}
}, UNTIL_LOADED);
};
export const copyFirstViewLink = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsViews(args)) {
return;
}
const row = await firstRow(canvasElement);
await openRowMenu(row);
await userEvent.click(rowMenuItem('copyLink')());
await userEvent.unhover(row);
await expectToast('Link copied');
};
/**
* Confirms the first view's delete. The Writes control decides the outcome: a
* toast for success or failure, the confirm button spinning while it never
* answers.
*/
export const deleteFirstView = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsViews(args)) {
return;
}
const row = await firstRow(canvasElement);
if (!grantsAll(args, buildSavedViewDeletePermission(viewIdOf(row)))) {
return;
}
await openRowMenu(row);
await expectDisabled(rowMenuItem('delete'), false);
await userEvent.click(rowMenuItem('delete')());
await userEvent.click(
await screen.findByTestId(
'delete-saved-view-confirm',
undefined,
UNTIL_LOADED,
),
);
if (args.writes === 'loading') {
await expectPending(byTestId('delete-saved-view-confirm'));
return;
}
await expectToast(DELETE_TOAST[args.writes]);
if (args.writes === 'error') {
await expect(screen.getByTestId('delete-saved-view-confirm')).toBeVisible();
}
};

View File

@@ -49,6 +49,14 @@ export type OpenView = (typeof OPEN_VIEWS)[number];
export const SAVED_VIEWS_MAX = 8;
export const VIEW_QUERIES = ['filtered', 'no-filters', 'multi-query'] as const;
export type ViewQuery = (typeof VIEW_QUERIES)[number];
export const WRITE_STATES = ['success', 'loading', 'error'] as const;
export type WriteState = (typeof WRITE_STATES)[number];
/** The user the story app context signs in as, so "Created by me" follows it. */
const STORY_USER_EMAIL = createAppContextMock(USER_ROLES.ADMIN).user.email;
@@ -101,22 +109,31 @@ const EXPLORER_ROUTE: Record<SavedViewSource, string> = {
meter: ROUTES.METER_EXPLORER,
};
const queryWith = (source: SavedViewSource, expression: string): Query => {
const queryWith = (
source: SavedViewSource,
expression: string,
shape: ViewQuery = 'filtered',
): Query => {
const base = BASE_QUERY[source];
const [first] = base.builder.queryData;
const filtered = (queryName: string, filter: string): typeof first => ({
...first,
queryName,
expression: queryName,
filter: { expression: filter },
aggregations: [{ expression: 'count()' }],
});
return {
...base,
builder: {
...base.builder,
queryData: [
{
...base.builder.queryData[0],
filter: { expression },
aggregations: [{ expression: 'count()' }],
},
],
},
} as Query;
const queryData = {
filtered: [filtered(first.queryName, expression)],
'no-filters': [filtered(first.queryName, '')],
'multi-query': [
filtered('A', expression),
filtered('B', "deployment.environment = 'staging' AND has_error = true"),
],
}[shape];
return { ...base, builder: { ...base.builder, queryData } } as Query;
};
type Author = 'mine' | 'others';
@@ -135,6 +152,7 @@ const savedView = (
source: SavedViewSource,
author: Author,
index: number,
shape: ViewQuery = 'filtered',
): SavedviewtypesSavedViewDTO => {
const displayName = (author === 'mine' ? MY_VIEW_NAMES : OTHER_VIEW_NAMES)[
index
@@ -158,6 +176,7 @@ const savedView = (
query: queryWith(
source,
EXPRESSIONS[(index + (author === 'mine' ? 0 : 3)) % EXPRESSIONS.length],
shape,
),
panelType: PANEL_TYPES.LIST,
displayName,
@@ -169,30 +188,33 @@ const savedViews = (
source: SavedViewSource,
author: Author,
count: number,
shape: ViewQuery,
): SavedviewtypesSavedViewDTO[] =>
Array.from({ length: Math.min(count, SAVED_VIEWS_MAX) }, (_, index) =>
savedView(source, author, index),
savedView(source, author, index, shape),
);
export const savedViewsListResponse = (
source: SavedViewSource,
createdByMe: number,
createdByOthers: number,
shape: ViewQuery = 'filtered',
): ListSavedViews200 => ({
status: 'success',
data: [
...savedViews(source, 'mine', createdByMe),
...savedViews(source, 'others', createdByOthers),
...savedViews(source, 'mine', createdByMe, shape),
...savedViews(source, 'others', createdByOthers, shape),
],
});
/** Every view the workspace has, whatever the list control trims it to. */
export const savedViewById = (
id: string,
shape: ViewQuery = 'filtered',
): SavedviewtypesSavedViewDTO | undefined =>
SAVED_VIEW_SOURCES.flatMap((source) => [
...savedViews(source, 'mine', SAVED_VIEWS_MAX),
...savedViews(source, 'others', SAVED_VIEWS_MAX),
...savedViews(source, 'mine', SAVED_VIEWS_MAX, shape),
...savedViews(source, 'others', SAVED_VIEWS_MAX, shape),
]).find((view) => view.id === id);
/** A view the panel itself created, owned by the story user. */
@@ -269,6 +291,24 @@ export const OPEN_VIEW_ERRORS: Partial<
},
};
const internalError = (message: string): RenderErrorResponseDTO => ({
status: 'error',
error: {
code: 'internal',
message,
errors: [],
suggestions: [],
type: 'internal',
},
});
/** What a failed write answers with; the panel's error toast shows the message. */
export const WRITE_ERRORS = {
create: internalError('Failed to create the saved view'),
update: internalError('Failed to update the saved view'),
delete: internalError('Failed to delete the saved view'),
};
const openViewId = (source: SavedViewSource, open: OpenView): string | null => {
if (open === 'none') {
return null;
@@ -294,12 +334,13 @@ const openViewId = (source: SavedViewSource, open: OpenView): string | null => {
export const savedViewRoute = (
source: SavedViewSource,
open: OpenView,
shape: ViewQuery = 'filtered',
): string => {
const params = new URLSearchParams({ relativeTime: '15m' });
const id = openViewId(source, open);
if (id) {
const view = savedViewById(id);
const view = savedViewById(id, shape);
const query = view
? getSavedViewQuery(view)
: queryWith(source, EXPRESSIONS[0]);

View File

@@ -13,7 +13,7 @@ import { FontSize, type LogViewMode } from 'container/OptionsMenu/types';
import { rest } from 'msw';
import { defaultFeatureFlags } from 'tests/fixtures/appContextMock';
import type {
BaseBuilderQuery,
BuilderQuery,
QueryRangeRequestV5,
} from 'types/api/v5/queryRange';
@@ -24,11 +24,13 @@ import {
toggleControl,
} from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { logsSavedViewsResponse } from '../../stories/__story_mockdata__/savedViews';
import {
attributeValuesResponse,
dashboardsResponse,
infraMetricsResponse,
logFieldKeysResponse,
logFieldValuesResponse,
logHistogramResponse,
@@ -152,6 +154,13 @@ export const liveLogsMocks = defineStoryMocks({
response.json(async (req) => {
const body = (await req.json()) as QueryRangeRequestV5;
const timeWindow = { start: body.start, end: body.end };
const spec = body.compositeQuery?.queries?.[0]?.spec as
| BuilderQuery
| undefined;
if (spec?.signal === 'metrics') {
return infraMetricsResponse(body);
}
if (body.requestType === 'raw') {
return logRowsResponse(values.liveLogs, values.severities, body.end, {
@@ -159,9 +168,6 @@ export const liveLogsMocks = defineStoryMocks({
});
}
const spec = body.compositeQuery?.queries?.[0]?.spec as
| BaseBuilderQuery
| undefined;
const bySeverity = (spec?.groupBy ?? []).some(
(key) => key.name === 'severity_text',
);
@@ -242,3 +248,5 @@ export const liveLogsMocks = defineStoryMocks({
);
},
});
export type LiveLogsArgs = PageStoryArgs<typeof liveLogsMocks>;

View File

@@ -1,42 +1,18 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { liveLogsMocks } from './LiveLogs.stories.mocks';
import { type LiveLogsArgs, liveLogsMocks } from './LiveLogs.stories.mocks';
import {
copyLiveLogLink,
openLiveLogDetails,
tailLive,
} from './__story_mockdata__/liveLogs.play';
import LogsModulePage from '../../LogsModulePage';
type LiveLogsArgs = PageStoryArgs<typeof liveLogsMocks>;
const pageStory = storyMocks(liveLogsMocks, { layout: 'app' });
/** The page connects before it renders a line, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** Live tail is reached through the time picker, which owns the `Live` option. */
const goLive = async (canvasElement: HTMLElement): Promise<void> => {
const canvas = within(canvasElement);
const timePicker = await waitFor(() => {
const input = canvasElement.querySelector<HTMLElement>(
'.timeSelection-input',
);
if (!input) {
throw new Error('Time picker did not render');
}
return input;
}, untilLoaded);
await userEvent.click(timePicker);
await userEvent.click(
await canvas.findByRole('button', { name: 'Live' }, untilLoaded),
);
};
/**
* Live tail: the explorer following a filter as lines arrive, over the log
* stream at `/api/v3/logs/livetail` rather than a query. It is a mode of the
@@ -49,20 +25,7 @@ const meta = {
title: 'Pages/Logs/Live Tail',
tags: ['play'],
component: LogsModulePage,
play: async ({ mount, args, canvasElement }): Promise<void> => {
await mount();
await goLive(canvasElement);
// The stream answers after a connect delay, so without this the story is
// captured on `Fetching live logs...` rather than on the lines it names.
if (args.liveLogs > 0) {
await within(canvasElement).findAllByText(
/order 8412 placed/,
undefined,
untilLoaded,
);
}
},
play: tailLive,
...pageStory,
// The stream mock answers in one piece, so the polyfill reads its end as a
// dropped connection and logs the error it would on any reconnect; that is the
@@ -95,30 +58,10 @@ export const JsonBody: Story = {
/** Row actions render on hover, so a streamed line is hovered before its copy link is pressed. */
export const LogLinkCopiedToast: Story = {
play: async ({ mount, canvasElement }): Promise<void> => {
await mount();
await goLive(canvasElement);
const [line] = await within(canvasElement).findAllByText(
/order 8412 placed/,
undefined,
untilLoaded,
);
await userEvent.hover(line);
await userEvent.click(
await waitFor(() => {
const button = canvasElement.querySelector<HTMLElement>('.copy-log-btn');
if (!button) {
throw new Error('Row actions did not render');
}
return button;
}, untilLoaded),
);
await waitFor(() =>
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
);
},
play: copyLiveLogLink,
};
/** A streamed line opened in the log detail drawer. */
export const LiveLogDetails: Story = {
play: openLiveLogDetails,
};

View File

@@ -0,0 +1,120 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import type { LiveLogsArgs } from '../LiveLogs.stories.mocks';
interface PlayContext {
mount: () => Promise<unknown>;
canvasElement: HTMLElement;
args: LiveLogsArgs;
}
/** The page connects before it renders a line, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
const LINE_TEXT = /order 8412 placed/;
/** Each streamed line takes a severity, so no severity means no line. */
const streamsLines = (args: LiveLogsArgs): boolean =>
args.liveLogs > 0 && args.severities.length > 0;
/** Live tail is reached through the time picker, which owns the `Live` option. */
const goLive = async (canvasElement: HTMLElement): Promise<void> => {
const timePicker = await waitFor(() => {
const input = canvasElement.querySelector<HTMLElement>(
'.timeSelection-input',
);
if (!input) {
throw new Error('Time picker did not render');
}
return input;
}, untilLoaded);
await userEvent.click(timePicker);
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Live' },
untilLoaded,
),
);
};
const firstLine = async (canvasElement: HTMLElement): Promise<HTMLElement> => {
const [line] = await within(canvasElement).findAllByText(
LINE_TEXT,
undefined,
untilLoaded,
);
return line;
};
/**
* The stream answers after a connect delay, so without waiting on a line the
* story is captured on `Fetching live logs...` rather than on the lines it names.
*/
export const tailLive = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await goLive(canvasElement);
if (streamsLines(args)) {
await firstLine(canvasElement);
}
};
/** Row actions render on hover, so a streamed line is hovered first. */
export const copyLiveLogLink = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await goLive(canvasElement);
if (!streamsLines(args)) {
return;
}
await userEvent.hover(await firstLine(canvasElement));
await userEvent.click(
await waitFor(() => {
const button = canvasElement.querySelector<HTMLElement>('.copy-log-btn');
if (!button) {
throw new Error('Row actions did not render');
}
return button;
}, untilLoaded),
);
await waitFor(() =>
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
);
};
export const openLiveLogDetails = async ({
mount,
args,
canvasElement,
}: PlayContext): Promise<void> => {
await mount();
await goLive(canvasElement);
if (!streamsLines(args)) {
return;
}
await userEvent.click(await firstLine(canvasElement));
await screen.findByTestId('log-detail-drawer', undefined, untilLoaded);
};

View File

@@ -6,13 +6,18 @@
import ROUTES from 'constants/routes';
import { rest } from 'msw';
import type { ILog } from 'types/api/logs/log';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import type {
BuilderQuery,
QueryRangeRequestV5,
} from 'types/api/v5/queryRange';
import { choiceControl, countControl } from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import { queryRangeV5ScalarResponse } from '@/storybook/msw/__story_mockdata__/queryRange';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
infraMetricsResponse,
logFieldKeysResponse,
logFieldValuesResponse,
LOG_SEVERITIES,
@@ -104,6 +109,14 @@ export const pipelinesMocks = defineStoryMocks({
'http://localhost/api/v5/query_range',
response.json(async (req) => {
const body = (await req.json()) as QueryRangeRequestV5;
const spec = body.compositeQuery?.queries?.[0]?.spec as
| BuilderQuery
| undefined;
// The preview's log detail drawer asks for its infra charts here.
if (spec?.signal === 'metrics') {
return infraMetricsResponse(body);
}
if (body.requestType === 'scalar') {
return queryRangeV5ScalarResponse(4213);
@@ -136,3 +149,5 @@ export const pipelinesMocks = defineStoryMocks({
reduxState: timeRangeState(),
}),
});
export type PipelinesArgs = PageStoryArgs<typeof pipelinesMocks>;

View File

@@ -1,15 +1,24 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { pipelinesMocks } from './Pipelines.stories.mocks';
import { type PipelinesArgs, pipelinesMocks } from './Pipelines.stories.mocks';
import {
expandProcessors,
openAddPipeline,
openAddProcessor,
openChangeHistory,
openEditMode,
openEditPipeline,
openPreviewLogDetails,
openProcessingPreview,
openSeverityParserProcessor,
suggestPipelineFilterKeys,
suggestPipelineFilterValues,
} from './__story_mockdata__/pipelines.play';
import LogsModulePage from '../../LogsModulePage';
type PipelinesArgs = PageStoryArgs<typeof pipelinesMocks>;
const pageStory = storyMocks(pipelinesMocks, { layout: 'app' });
/**
@@ -30,37 +39,6 @@ export default meta;
type Story = StoryObj<PipelinesArgs>;
/** The page fetches before it renders a row, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** Row actions repeat per pipeline, so a story that opens one takes the first. */
const clickFirst = async (
canvasElement: HTMLElement,
testId: string,
): Promise<void> => {
const [action] = await within(canvasElement).findAllByTestId(
testId,
undefined,
untilLoaded,
);
await userEvent.click(action);
};
/**
* Editing is a mode the whole table is in: the row actions, the drag handles and
* the save bar only exist inside it.
*/
const enterEditMode = async (canvasElement: HTMLElement): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/enter edit mode/i,
undefined,
untilLoaded,
),
);
};
/**
* The pipelines tab: the processors the org runs over logs before storing them,
* in the order they run, with the version that is deployed on the collector.
@@ -74,46 +52,42 @@ export const NoPipelines: Story = {
/** A pipeline opened up: the operators it runs, in order. */
export const ExpandedProcessors: Story = {
play: async ({ canvasElement }): Promise<void> => {
await clickFirst(canvasElement, 'pipeline-row-expand');
},
play: expandProcessors,
};
/** Edit mode: rows can be reordered, switched off, edited and deleted. */
export const EditMode: Story = {
play: async ({ canvasElement }): Promise<void> => {
await enterEditMode(canvasElement);
},
play: openEditMode,
};
/** The form a new pipeline is written in: what it matches and what to call it. */
export const AddPipeline: Story = {
play: async ({ canvasElement }): Promise<void> => {
await enterEditMode(canvasElement);
await userEvent.click(
await within(canvasElement).findByText(/add a new pipeline/i),
);
await screen.findByText(/create new pipeline/i);
},
play: openAddPipeline,
};
/** The new pipeline's filter focused: the keys it can match on. */
export const AddPipelineFilterKeys: Story = {
play: suggestPipelineFilterKeys,
};
/** A key and an operator typed into the filter: the values that key holds. */
export const AddPipelineFilterValues: Story = {
play: suggestPipelineFilterValues,
};
/** The same form over an existing pipeline, filter included. */
export const EditPipeline: Story = {
play: async ({ canvasElement }): Promise<void> => {
await enterEditMode(canvasElement);
await clickFirst(canvasElement, 'pipeline-edit-action');
await screen.findByText(/edit pipeline/i);
},
play: openEditPipeline,
};
/** Adding an operator to a pipeline: the type decides the rest of the form. */
export const AddProcessor: Story = {
play: async ({ canvasElement }): Promise<void> => {
await enterEditMode(canvasElement);
await clickFirst(canvasElement, 'pipeline-row-expand');
await userEvent.click(await screen.findByText(/add processor/i));
await screen.findByText(/create new processor/i);
},
play: openAddProcessor,
};
/** Severity Parser is the type whose mapping fields are CSV inputs. */
export const AddSeverityParserProcessor: Story = {
play: openSeverityParserProcessor,
};
/**
@@ -121,22 +95,17 @@ export const AddProcessor: Story = {
* simulation of its processors one click away.
*/
export const ProcessingPreview: Story = {
play: async ({ canvasElement }): Promise<void> => {
await clickFirst(canvasElement, 'pipeline-preview-action');
await screen.findByText(/processed output/i, undefined, untilLoaded);
},
play: openProcessingPreview,
};
/** A sample log from the preview opened in the log detail drawer. */
export const PreviewLogDetails: Story = {
play: openPreviewLogDetails,
};
/** Every config version the org deployed, and how each deployment went. */
export const ChangeHistory: Story = {
play: async ({ canvasElement }): Promise<void> => {
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByText(/change history/i, undefined, untilLoaded),
);
await canvas.findByText('Deployment Stage', undefined, untilLoaded);
},
play: openChangeHistory,
};
/** A deployment the collector has not finished, which the page polls for. */

View File

@@ -0,0 +1,239 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { screen, userEvent, within } from 'storybook/test';
import type { PipelinesArgs } from '../Pipelines.stories.mocks';
interface PlayContext {
canvasElement: HTMLElement;
args: PipelinesArgs;
}
/** The page fetches before it renders a row, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** Every play starts from a pipeline row, which only a loaded, non-empty list has. */
const listsPipelines = (args: PipelinesArgs): boolean =>
args.dataState === 'loaded' && args.pipelines > 0;
/** A pipeline without processors has no preview action. */
const previewsPipelines = (args: PipelinesArgs): boolean =>
listsPipelines(args) && args.processors > 0;
/** Row actions repeat per pipeline, so a play that opens one takes the first. */
const clickFirst = async (
canvasElement: HTMLElement,
testId: string,
): Promise<void> => {
const [action] = await within(canvasElement).findAllByTestId(
testId,
undefined,
untilLoaded,
);
await userEvent.click(action);
};
/**
* Editing is a mode the whole table is in: the row actions, the drag handles and
* the save bar only exist inside it.
*/
const enterEditMode = async (canvasElement: HTMLElement): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByText(
/enter edit mode/i,
undefined,
untilLoaded,
),
);
};
const openNewPipelineForm = async (
canvasElement: HTMLElement,
): Promise<void> => {
await enterEditMode(canvasElement);
await userEvent.click(
await within(canvasElement).findByText(/add a new pipeline/i),
);
await screen.findByText(/create new pipeline/i);
};
const openNewProcessorForm = async (
canvasElement: HTMLElement,
): Promise<void> => {
await enterEditMode(canvasElement);
await clickFirst(canvasElement, 'pipeline-row-expand');
await userEvent.click(await screen.findByText(/add processor/i));
await screen.findByText(/create new processor/i);
};
const openPreview = async (canvasElement: HTMLElement): Promise<void> => {
await clickFirst(canvasElement, 'pipeline-preview-action');
await screen.findByText(/processed output/i, undefined, untilLoaded);
};
/** The filter is an antd select: focusing its input opens the suggestions. */
const focusPipelineFilter = async (): Promise<HTMLElement> => {
const [filter] = await screen.findAllByTestId('qb-search-select');
const input = within(filter).getByRole('combobox');
await userEvent.click(input);
return input;
};
export const expandProcessors = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await clickFirst(canvasElement, 'pipeline-row-expand');
};
export const openEditMode = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await enterEditMode(canvasElement);
};
export const openAddPipeline = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await openNewPipelineForm(canvasElement);
};
export const suggestPipelineFilterKeys = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await openNewPipelineForm(canvasElement);
await focusPipelineFilter();
await screen.findAllByText('service.name', undefined, untilLoaded);
};
export const suggestPipelineFilterValues = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await openNewPipelineForm(canvasElement);
await userEvent.type(await focusPipelineFilter(), 'service.name = ');
await screen.findAllByText('checkout', undefined, untilLoaded);
};
export const openEditPipeline = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await enterEditMode(canvasElement);
await clickFirst(canvasElement, 'pipeline-edit-action');
await screen.findByText(/edit pipeline/i);
};
export const openAddProcessor = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await openNewProcessorForm(canvasElement);
};
/** Severity Parser is the type whose mapping fields are CSV inputs. */
export const openSeverityParserProcessor = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsPipelines(args)) {
return;
}
await openNewProcessorForm(canvasElement);
await userEvent.click(await screen.findByText('Grok'));
await userEvent.click(await screen.findByTitle('Severity Parser'));
await screen.findByText('Parse Severity Value From');
};
export const openProcessingPreview = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!previewsPipelines(args)) {
return;
}
await openPreview(canvasElement);
};
/** Each sample log in the preview opens in the log detail drawer. */
export const openPreviewLogDetails = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!previewsPipelines(args) || args.sampleLogs === 0) {
return;
}
await openPreview(canvasElement);
const [log] = await screen.findAllByTestId(
'pipeline-preview-log',
undefined,
untilLoaded,
);
const expand = log.querySelector<HTMLElement>(
'.logs-preview-list-item-expand',
);
if (!expand) {
throw new Error('Preview log has no expand control');
}
await userEvent.click(expand);
await screen.findByTestId('log-detail-drawer', undefined, untilLoaded);
};
export const openChangeHistory = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.dataState !== 'loaded') {
return;
}
const canvas = within(canvasElement);
await userEvent.click(
await canvas.findByText(/change history/i, undefined, untilLoaded),
);
await canvas.findByText('Deployment Stage', undefined, untilLoaded);
};

View File

@@ -14,7 +14,7 @@ import { rest } from 'msw';
import { defaultFeatureFlags } from 'tests/fixtures/appContextMock';
import type { Warning } from 'types/api';
import type {
BaseBuilderQuery,
BuilderQuery,
QueryRangeRequestV5,
} from 'types/api/v5/queryRange';
@@ -39,6 +39,9 @@ import {
import {
attributeValuesResponse,
dashboardsResponse,
INFRA_RESOURCES,
type InfraResource,
infraMetricsResponse,
logCountResponse,
logFieldKeysResponse,
logFieldValuesResponse,
@@ -54,6 +57,9 @@ import {
recentFiltersStorage,
RELATIVE_TIME,
timeRangeState,
URL_FILTERS,
type UrlFilter,
urlFilterQuery,
} from './__story_mockdata__/logs';
const EXPLORER = 'Logs · explorer';
@@ -93,10 +99,14 @@ const QUERY_WARNING: Warning = {
],
};
const explorerRoute = (view: ExplorerView): string => {
const explorerRoute = (view: ExplorerView, urlFilter: UrlFilter): string => {
const panelType = encodeURIComponent(JSON.stringify(VIEW_PANEL_TYPES[view]));
const query = urlFilterQuery(urlFilter);
const compositeQuery = query
? `&${QueryParams.compositeQuery}=${encodeURIComponent(JSON.stringify(query))}`
: '';
return `${ROUTES.LOGS_EXPLORER}?${QueryParams.panelTypes}=${panelType}&${QueryParams.relativeTime}=${RELATIVE_TIME}`;
return `${ROUTES.LOGS_EXPLORER}?${QueryParams.panelTypes}=${panelType}&${QueryParams.relativeTime}=${RELATIVE_TIME}${compositeQuery}`;
};
export const logsMocks = defineStoryMocks({
@@ -154,6 +164,13 @@ export const logsMocks = defineStoryMocks({
'`use_json_body`: the service logs JSON and the backend hands the body over parsed, so the body is a tree and its keys are queryable as `body.x`.',
value: false,
}),
infraResource: choiceControl<InfraResource>('Infra resource', {
group: LIST,
description:
"The k8s resource each log carries, which picks the charts on the log detail's Metrics tab.",
options: INFRA_RESOURCES,
value: 'pod',
}),
bodyColumns: toggleControl('Body field columns', {
group: LIST,
description:
@@ -172,6 +189,13 @@ export const logsMocks = defineStoryMocks({
value: QUICK_FILTER_MAX,
max: QUICK_FILTER_MAX,
}),
urlFilter: choiceControl<UrlFilter>('Linked filter', {
group: FILTERS,
description:
"A filter the explorer opened on from a link: a saved view's `service.name`, or a span's `trace_id`. With no log matching, the list says the search found nothing instead of offering to send logs.",
options: URL_FILTERS,
value: 'none',
}),
filterValues: choiceControl<ResponseState>('Filter values', {
group: FILTERS,
description:
@@ -202,28 +226,38 @@ export const logsMocks = defineStoryMocks({
response.json(async (req) => {
const body = (await req.json()) as QueryRangeRequestV5;
const timeWindow = { start: body.start, end: body.end };
// Each log takes a severity: no log or no severity means nothing matches.
const matching = values.logs === 0 ? [] : values.severities;
const spec = body.compositeQuery?.queries?.[0]?.spec as
| BuilderQuery
| undefined;
if (spec?.signal === 'metrics') {
return infraMetricsResponse(body);
}
if (body.requestType === 'time_series') {
// The frequency chart asks for counts grouped by severity; the
// timeseries view asks the same aggregation without a group by.
const spec = body.compositeQuery?.queries?.[0]?.spec as
| BaseBuilderQuery
| undefined;
const bySeverity = (spec?.groupBy ?? []).some(
(key) => key.name === 'severity_text',
);
return bySeverity
? logHistogramResponse(values.severities, timeWindow, { warning })
: logTimeseriesResponse(timeWindow, { warning });
? logHistogramResponse(matching, timeWindow, { warning })
: logTimeseriesResponse(timeWindow, {
warning,
empty: matching.length === 0,
});
}
if (body.requestType === 'scalar') {
return logCountResponse(values.severities);
return logCountResponse(matching);
}
return logRowsResponse(values.logs, values.severities, body.end, {
jsonBody: values.jsonBody,
infraResource: values.infraResource,
warning,
});
}),
@@ -274,8 +308,8 @@ export const logsMocks = defineStoryMocks({
),
];
},
config: ({ view, jsonBody }) => ({
route: explorerRoute(view),
config: ({ view, urlFilter, jsonBody }) => ({
route: explorerRoute(view, urlFilter),
reduxState: timeRangeState(),
appContext: jsonBody
? {

View File

@@ -4,14 +4,21 @@ import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import { type LogsArgs, logsMocks } from './LogsModulePage.stories.mocks';
import {
cancelQuery,
completeFilter,
copyLog,
copyLogDetailsLink,
copyLogLinkFromRow,
dirtyQuickFiltersSettings,
openDownloadMenu,
openEditColumns,
openFormatFontSize,
openFormatMenu,
openLogContext,
openLogContextFilters,
openLogDetails,
openLogDetailsMenu,
openLogMetrics,
openQuickFiltersSettings,
showFilterSyntaxError,
stepToNextLog,
@@ -62,6 +69,27 @@ export const NoLogs: Story = {
args: { logs: 0 },
};
/**
* A filter the explorer opened on from a link, with nothing matching it: the
* list says the search came up empty rather than offering to send logs.
*/
export const NoMatchingLogs: Story = {
args: { logs: 0, urlFilter: 'service' },
};
/**
* A span's "View logs" with no log carrying its trace: why the logs may be
* missing, and a way to drop the filter.
*/
export const NoLogsForTrace: Story = {
args: { logs: 0, urlFilter: 'trace' },
};
/** The timeseries view over a linked filter that matches nothing. */
export const TimeseriesNoMatchingLogs: Story = {
args: { view: 'timeseries', logs: 0, urlFilter: 'service' },
};
/** One aggregated line over the selected range instead of the log lines. */
export const TimeseriesView: Story = {
args: { view: 'timeseries' },
@@ -82,6 +110,33 @@ export const RawFormat: Story = {
args: { format: 'raw' },
};
/** The format popover: the format list, the max-lines stepper, and the font-size control. */
export const FormatMenuOpen: Story = {
args: { format: 'raw' },
play: openFormatMenu,
};
/** The format popover switched to its font sizes. */
export const FormatMenuFontSize: Story = {
play: openFormatFontSize,
};
/** The column picker the table format's Edit columns opens. */
export const EditColumns: Story = {
play: openEditColumns,
};
/** The list's download options: format, how many rows, and which columns. */
export const DownloadMenuOpen: Story = {
play: openDownloadMenu,
};
/** The table's download options, which export the aggregated rows it shows. */
export const ExportMenuOpen: Story = {
args: { view: 'table' },
play: openDownloadMenu,
};
/** An explorer with no configured quick filters. */
export const NoQuickFilters: Story = {
args: { quickFilters: 0 },
@@ -132,6 +187,28 @@ export const LogDetailsContext: Story = {
play: openLogContext,
};
/** The context tab with its filter open, to narrow the logs either side. */
export const LogDetailsContextFilters: Story = {
play: openLogContextFilters,
};
/** The pod's CPU, memory, filesystem and network around the log's timestamp. */
export const LogDetailsPodMetrics: Story = {
play: openLogMetrics,
};
/** A log from a node: the node's charts, with its pod's one toggle away. */
export const LogDetailsNodeMetrics: Story = {
args: { infraResource: 'node' },
play: openLogMetrics,
};
/** A log with no pod, node or host to chart. */
export const LogDetailsNoMetrics: Story = {
args: { infraResource: 'none' },
play: openLogMetrics,
};
/** The log detail drawer with its header actions menu open. */
export const LogDetailsMenuOpen: Story = {
play: openLogDetailsMenu,
@@ -147,6 +224,12 @@ export const Loading: Story = {
args: { dataState: 'loading' },
};
/** A query cancelled while in flight, waiting for the next run. */
export const QueryCancelled: Story = {
args: { dataState: 'loading' },
play: cancelQuery,
};
/** A failed logs query. */
export const Failed: Story = {
args: { dataState: 'error' },
@@ -276,6 +359,12 @@ export const LogLinkCopiedToast: Story = {
play: copyLogLinkFromRow,
};
/** The same copy link on a line in the list format. */
export const LogLinkCopiedToastListFormat: Story = {
args: { format: 'list' },
play: copyLogLinkFromRow,
};
/** "Copy log" in the log detail drawer's actions menu. */
export const LogCopiedToast: Story = {
play: copyLog,

View File

@@ -11,6 +11,11 @@ import {
typeFilter,
typeFilterWithCaretBack,
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
import {
nodeWidgetInfo,
podWidgetInfo,
} from 'container/LogDetailedView/InfraMetrics/constants';
import { FontSize } from 'container/OptionsMenu/types';
import { QuickFilterManagePermissions } from 'lib/authz/hooks/useAuthZ/permissions/quick-filter.permissions';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
@@ -32,12 +37,28 @@ const VALUE_SUGGESTIONS = {
error: 'Error loading suggestions',
} satisfies Record<LogsArgs['filterValues'], string>;
/** Each row takes a severity, so no severity means no row. */
const hasLogRows = (args: LogsArgs, count = 1): boolean =>
args.view === 'list' &&
args.dataState === 'loaded' &&
args.logs >= count &&
args.severities.length > 0;
/** The rows a play opens exist only in the list view's table format. */
const listsLogRows = (args: LogsArgs, count = 1): boolean =>
args.view === 'list' &&
args.format === 'table' &&
args.dataState === 'loaded' &&
args.logs >= count;
args.format === 'table' && hasLogRows(args, count);
/** The chart the Metrics tab opens on: a log naming a node opens on the node's. */
const infraChartTitle = (args: LogsArgs): string | undefined => {
switch (args.infraResource) {
case 'pod':
return podWidgetInfo[0].title;
case 'node':
return nodeWidgetInfo[0].title;
default:
return undefined;
}
};
/** The settings control stays enabled when the check itself fails. */
const canManageQuickFilters = (args: LogsArgs): boolean =>
@@ -45,11 +66,14 @@ const canManageQuickFilters = (args: LogsArgs): boolean =>
(args.authzState === 'error' ||
grantsAll(args, ...QuickFilterManagePermissions));
/** Runs `drive` once the filter has its keys, which come with the page's data. */
/**
* Runs `drive` once the filter has its keys, which come with the page's data. A
* linked filter pre-fills the editor, so typed text would land after it.
*/
const onFilter =
(drive: (canvasElement: HTMLElement, args: LogsArgs) => Promise<void>) =>
async ({ canvasElement, args }: PlayContext): Promise<void> => {
if (args.dataState === 'loaded') {
if (args.dataState === 'loaded' && args.urlFilter === 'none') {
await drive(canvasElement, args);
}
};
@@ -122,6 +146,158 @@ export const openLogDetailsMenu = async ({
await screen.findByText('Copy link to log');
};
/** The format options sit in the list view's toolbar. */
export const openFormatMenu = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.view !== 'list') {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'periscope-btn-format-options',
undefined,
untilLoaded,
),
);
await screen.findByTestId('max-lines-per-row', undefined, untilLoaded);
};
export const openFormatFontSize = async (
context: PlayContext,
): Promise<void> => {
if (context.args.view !== 'list') {
return;
}
await openFormatMenu(context);
await userEvent.click(await screen.findByTestId('font-size-select'));
await screen.findByTestId(`font-size-option-${FontSize.LARGE}`);
};
/** Edit columns is offered only for the table format, the one with columns. */
export const openEditColumns = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.view !== 'list' || args.format !== 'table') {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'periscope-btn-format-options',
undefined,
untilLoaded,
),
);
await userEvent.click(await screen.findByTestId('periscope-btn-edit-columns'));
await screen.findByPlaceholderText(
'Search for a field...',
undefined,
untilLoaded,
);
};
/**
* The list exports from the backend and offers rows and columns; the table and
* timeseries export the response they already hold, so they offer only a format.
*/
export const openDownloadMenu = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.dataState !== 'loaded') {
return;
}
if (args.view === 'list') {
await userEvent.click(
await within(canvasElement).findByTestId(
'periscope-btn-download-logs',
undefined,
untilLoaded,
),
);
await screen.findByText('Number of Rows');
return;
}
if (args.logs === 0) {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'export-menu-logs',
undefined,
untilLoaded,
),
);
await screen.findByText('FORMAT');
};
export const openLogContextFilters = async (
context: PlayContext,
): Promise<void> => {
if (!listsLogRows(context.args)) {
return;
}
await openLogContext(context);
await userEvent.click(
await screen.findByRole('button', { name: 'Show Filters' }),
);
await waitFor(() => {
if (!document.querySelector('.log-detail-drawer-query-container')) {
throw new Error('Context filters did not open');
}
}, untilLoaded);
};
export const openLogMetrics = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsLogRows(args)) {
return;
}
await openFirstLog(canvasElement);
const drawer = within(await screen.findByTestId('log-detail-drawer'));
await userEvent.click(await drawer.findByText('Metrics'));
const chartTitle = infraChartTitle(args);
if (chartTitle) {
await screen.findByText(chartTitle, undefined, untilLoaded);
return;
}
await screen.findByText(/No data available/, undefined, untilLoaded);
};
/** The cancel control only exists while the query is in flight. */
export const cancelQuery = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.dataState !== 'loading') {
return;
}
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /cancel/i },
untilLoaded,
),
);
await screen.findByText(/query cancelled/i, undefined, untilLoaded);
};
export const openQuickFiltersSettings = async ({
args,
}: PlayContext): Promise<void> => {
@@ -264,22 +440,31 @@ export const suggestRecentSearches = onFilter(async (canvasElement, args) => {
);
});
/** Row actions render on hover, in every format. */
const ROW_TEST_IDS: Record<LogsArgs['format'], RegExp> = {
table: /^logs-table-row-/,
list: /^logs-list-row-/,
raw: /^logs-raw-row-/,
};
export const copyLogLinkFromRow = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!listsLogRows(args)) {
if (!hasLogRows(args)) {
return;
}
const [row] = await within(canvasElement).findAllByTestId(
/^logs-table-row-/,
ROW_TEST_IDS[args.format],
undefined,
untilLoaded,
);
const [, timestamp] = within(row).getAllByRole('cell');
// The table hangs its hover off the cells; the list off the row itself.
const target =
args.format === 'table' ? within(row).getAllByRole('cell')[1] : row;
await userEvent.hover(timestamp);
await userEvent.hover(target);
await userEvent.click(
await waitFor(() => {
const button = canvasElement.querySelector<HTMLElement>('.copy-log-btn');

View File

@@ -13,6 +13,7 @@ import {
TelemetrytypesFieldDataTypeDTO,
type TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import { initialQueriesMap } from 'constants/queryBuilder';
import { defaultLogsSelectedColumns } from 'container/OptionsMenu/constants';
import type { OptionsQuery } from 'container/OptionsMenu/types';
import { STORAGE_VERSION } from 'lib/recentQueries/constants';
@@ -24,8 +25,15 @@ import type { AppState } from 'store/reducers';
import type { Warning } from 'types/api';
import type { ILogBody } from 'types/api/logs/log';
import type { IAttributeValuesResponse } from 'types/api/queryBuilder/getAttributesValues';
import { DataTypes } from 'types/api/queryBuilder/queryAutocompleteResponse';
import type {
Query,
TagFilterItem,
} from 'types/api/queryBuilder/queryBuilderData';
import type {
BaseBuilderQuery,
MetricRangePayloadV5,
QueryRangeRequestV5,
TelemetryFieldKey,
TimeSeries,
} from 'types/api/v5/queryRange';
@@ -100,6 +108,39 @@ const SERVICES = ['frontend', 'checkout', 'payments', 'cart', 'auth'];
const PODS = ['checkout-7b9f4d', 'payments-5c8a12', 'frontend-9d3e77'];
const NODES = ['ip-10-0-1-14.ec2.internal', 'ip-10-0-2-31.ec2.internal'];
/**
* The resource the log detail's Metrics tab charts: a pod opens on the pod's
* charts, a node opens on the node's with the pod one toggle away, and none
* leaves the tab empty.
*/
export const INFRA_RESOURCES = ['pod', 'node', 'none'] as const;
export type InfraResource = (typeof INFRA_RESOURCES)[number];
const infraResourceAttributes = (
infraResource: InfraResource,
index: number,
): Record<string, string> => {
if (infraResource === 'none') {
return {};
}
const pod = { 'k8s.pod.name': PODS[index % PODS.length] };
if (infraResource === 'pod') {
return pod;
}
return {
...pod,
'k8s.cluster.name': 'us-east-1',
'k8s.node.name': NODES[index % NODES.length],
'host.name': NODES[index % NODES.length],
};
};
interface LogRowData {
id: string;
body: string | ILogBody;
@@ -154,6 +195,7 @@ const jsonBodyAt = (
export interface LogsResponseOptions {
/** `use_json_body`: the body arrives as an object instead of a line. */
jsonBody?: boolean;
infraResource?: InfraResource;
warning?: Warning;
}
@@ -171,6 +213,7 @@ export const logRows = (
severities: readonly LogSeverity[],
endMilli: number,
jsonBody: boolean,
infraResource: InfraResource = 'pod',
): LogRow[] =>
Array.from({ length: severities.length ? count : 0 }, (_unused, index) => {
const severity = severities[index % severities.length];
@@ -198,7 +241,7 @@ export const logRows = (
resources_string: {
'service.name': service,
'deployment.environment': 'production',
'k8s.pod.name': PODS[index % PODS.length],
...infraResourceAttributes(infraResource, index),
},
scope_string: {},
},
@@ -209,10 +252,10 @@ export const logRowsResponse = (
count: number,
severities: readonly LogSeverity[],
endMilli: number,
{ jsonBody = false, warning }: LogsResponseOptions = {},
{ jsonBody = false, infraResource, warning }: LogsResponseOptions = {},
): MetricRangePayloadV5 =>
queryRangeV5RawResponse<LogRowData>(
logRows(count, severities, endMilli, jsonBody),
logRows(count, severities, endMilli, jsonBody, infraResource),
{ warning },
);
@@ -237,23 +280,100 @@ export const logHistogramResponse = (
});
};
/** The timeseries view aggregates without a group by, so it draws one line. */
/**
* The timeseries view aggregates without a group by, so it draws one line, or
* none when no log matches.
*/
export const logTimeseriesResponse = (
window: { start: number; end: number },
{ warning }: Pick<LogsResponseOptions, 'warning'> = {},
{
warning,
empty = false,
}: Pick<LogsResponseOptions, 'warning'> & {
empty?: boolean;
} = {},
): MetricRangePayloadV5 =>
queryRangeV5TimeSeriesResponse(
[
{
queryName: 'A',
series: [
{ values: timeSeriesPoints({ ...window, base: 420, amplitude: 90 }) },
],
series: empty
? []
: [{ values: timeSeriesPoints({ ...window, base: 420, amplitude: 90 }) }],
},
],
{ warning },
);
/**
* The log detail's infra charts: one line per query and formula, named the way
* the request names them, since each chart reads its own.
*/
export const infraMetricsResponse = (
body: QueryRangeRequestV5,
): MetricRangePayloadV5 =>
queryRangeV5TimeSeriesResponse(
(body.compositeQuery?.queries ?? []).map((query, index) => ({
queryName: (query.spec as BaseBuilderQuery).name ?? 'A',
series: [
{
values: timeSeriesPoints({
start: body.start,
end: body.end,
base: 40 + index * 15,
amplitude: 12,
seed: index * 2,
}),
},
],
})),
);
/**
* A filter the explorer opens on from a link rather than the search box, such as
* a saved view or a span's "View logs", which is the only way it arrives as
* filter items.
*/
export const URL_FILTERS = ['none', 'service', 'trace'] as const;
export type UrlFilter = (typeof URL_FILTERS)[number];
const URL_FILTER_ITEMS: Record<Exclude<UrlFilter, 'none'>, TagFilterItem> = {
service: {
id: 'service-name-filter',
key: { key: 'service.name', dataType: DataTypes.String, type: 'resource' },
op: '=',
value: 'checkout',
},
trace: {
id: 'trace-id-filter',
key: { key: 'trace_id', dataType: DataTypes.String, type: '' },
op: '=',
value: hex(1, 32),
},
};
export const urlFilterQuery = (filter: UrlFilter): Query | undefined => {
if (filter === 'none') {
return undefined;
}
const { builder } = initialQueriesMap.logs;
return {
...initialQueriesMap.logs,
builder: {
...builder,
queryData: [
{
...builder.queryData[0],
filters: { items: [URL_FILTER_ITEMS[filter]], op: 'AND' },
},
],
},
};
};
export const logCountResponse = (
severities: readonly LogSeverity[],
): MetricRangePayloadV5 => queryRangeV5ScalarResponse(severities.length * 1284);

View File

@@ -21,6 +21,7 @@ import {
toggleControl,
} from '@/storybook/controls/controls';
import { defineStoryMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import {
fieldKeysResponse,
fieldValuesResponse,
@@ -60,6 +61,10 @@ const EXPORT_STATES = ['success', 'loading', 'error'] as const;
type ExportState = (typeof EXPORT_STATES)[number];
const ANALYTICS_STATES = ['loaded', 'empty', 'loading', 'error'] as const;
type AnalyticsState = (typeof ANALYTICS_STATES)[number];
const PANEL_POSITIONS = [
SpanDetailVariant.DOCKED_RIGHT,
SpanDetailVariant.DOCKED,
@@ -86,11 +91,15 @@ const signalOf = (body: QueryRangeRequestV5): string | undefined => {
return spec && 'signal' in spec ? spec.signal : undefined;
};
const filterOf = (body: QueryRangeRequestV5): string => {
const spec = specOf(body);
return (spec && 'filter' in spec ? spec.filter?.expression : '') ?? '';
};
/** Which of the panel's three log queries this is, read off its filter. */
const spanLogScopeOf = (body: QueryRangeRequestV5): SpanLogScope => {
const spec = specOf(body);
const expression =
(spec && 'filter' in spec ? spec.filter?.expression : '') ?? '';
const expression = filterOf(body);
if (expression.includes('span_id')) {
return 'span';
@@ -156,6 +165,13 @@ export const traceDetailsMocks = defineStoryMocks({
'The span has no logs of its own but the trace does, which is the Logs tab\'s "view logs for the current trace" state.',
value: false,
}),
analytics: choiceControl<AnalyticsState>('Analytics', {
group: TRACE,
description:
'How the aggregations behind the header\'s Analytics panel answer. `empty` has no group to chart, so the panel says "No data".',
options: ANALYTICS_STATES,
value: 'loaded',
}),
exportState: choiceControl<ExportState>('Trace export', {
group: EXPORT,
description:
@@ -212,6 +228,37 @@ export const traceDetailsMocks = defineStoryMocks({
response.json(() => traceFlamegraphResponse(trace)),
),
// `loaded` falls through to the next handler.
rest.post(
'http://localhost/api/v1/traces/:traceId/aggregations',
async (req, res, ctx) => {
switch (values.analytics) {
case 'loading':
return res(ctx.delay('infinite'));
case 'error':
return res(
ctx.status(500),
ctx.json({ status: 'error', error: 'storybook aggregations failure' }),
);
case 'empty': {
const body = (await req.json()) as SpantypesPostableTraceAggregationsDTO;
return res(
ctx.status(200),
ctx.json(
traceAggregationsResponse(body.aggregations ?? [], {
...trace,
spans: 0,
}),
),
);
}
default:
return undefined;
}
},
),
rest.post(
'http://localhost/api/v1/traces/:traceId/aggregations',
response.json(async (req) => {
@@ -276,10 +323,25 @@ export const traceDetailsMocks = defineStoryMocks({
const body = (await req.json()) as QueryRangeRequestV5;
const { start, end, requestType } = body;
if (requestType === 'raw' && signalOf(body) === 'logs') {
return queryRangeV5RawResponse(spanLogRowsFor(body));
}
if (requestType === 'raw') {
return queryRangeV5RawResponse(
signalOf(body) === 'logs' ? spanLogRowsFor(body) : spanMatchRows(trace),
);
const matches = spanMatchRows(trace, filterOf(body));
const payload = queryRangeV5RawResponse(matches);
// The backend sends no rows as null, and the filter says "No results
// found" only for that; an empty array leaves it blank.
return matches.length > 0
? payload
: {
...payload,
data: {
...payload.data,
data: { results: [{ queryName: 'A', nextCursor: '', rows: null }] },
},
};
}
if (requestType === 'scalar') {
@@ -368,3 +430,16 @@ export const startDownload = async (
await userEvent.click(await screen.findByTestId('download-trace-submenu'));
await userEvent.click(await screen.findByTestId('download-trace-csv'));
};
export type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
/** The header actions and the span rows exist once a trace loads. */
export const showsTrace = ({
spans,
dataState,
}: Pick<TraceDetailsArgs, 'spans' | 'dataState'>): boolean =>
spans > 0 && dataState === 'loaded';
/** The span panel opens on the focus span when the control asks for it. */
export const showsSpanPanel = (args: TraceDetailsArgs): boolean =>
showsTrace(args) && args.spanPanel;

View File

@@ -1,33 +1,36 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import ROUTES from 'constants/routes';
import { renderAtRoute } from '@/storybook/renderAtRoute';
import {
expect,
fireEvent,
screen,
userEvent,
waitFor,
within,
} from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { scenarioSpanCount } from './__story_mockdata__/traceDetails';
import {
focusSpanIndex,
scenarioSpanCount,
spanIdAt,
} from './__story_mockdata__/traceDetails';
cancelDownload,
copyPrettyViewValue,
copySpanLink,
copyTraceId,
downloadTrace,
expandFilterBar,
hoverAiSpan,
hoverEventStacktrace,
openPercentile,
openPercentileResourceSelector,
openSpanEvents,
openTraceOptions,
showsAnalyticsState,
showsHighlightedErrors,
showsMissingSpansBanner,
showsTraceOnlyLogs,
showTooltips,
switchDockMode,
} from './__story_mockdata__/traceDetails.play';
import {
openRowMenu,
startDownload,
type TraceDetailsArgs,
traceDetailsMocks,
untilLoaded,
} from './TraceDetailsV3.stories.mocks';
import TraceDetailsV3 from '../index';
type TraceDetailsArgs = PageStoryArgs<typeof traceDetailsMocks>;
const pageStory = storyMocks(traceDetailsMocks, { layout: 'app' });
/**
@@ -80,6 +83,12 @@ export const Loading: Story = {
args: { dataState: 'loading' },
};
/** A trace whose spans have not all arrived: the dismissible banner over the panels. */
export const MissingSpans: Story = {
args: { missingSpans: true },
play: showsMissingSpansBanner,
};
/** The strip over a trace with no failing span: the error icon stays neutral. */
export const BottomStripNoErrors: Story = {
args: { errors: false },
@@ -107,30 +116,15 @@ const AI_SPANS = scenarioSpanCount('ai');
*/
export const AiTrace: Story = {
args: { scenario: 'ai', spans: AI_SPANS },
play: async ({ canvasElement }): Promise<void> => {
const row = await within(canvasElement).findByTestId(
`cell-0-${spanIdAt(focusSpanIndex('ai', AI_SPANS))}`,
undefined,
untilLoaded,
);
await fireEvent.mouseOver(row);
await screen.findByText('Usage Breakdown', undefined, untilLoaded);
},
play: hoverAiSpan,
};
/**
* Turns on Highlight errors, which writes `has_error = true` into the filter and
* expands the bar to show it.
* The agent run with every tooltip held open: the header's and the span panel's
* token usage breakdowns, and the cost labels beside them.
*/
const highlightErrors = async (canvasElement: HTMLElement): Promise<void> => {
const toggle = await within(canvasElement).findByTestId(
'highlight-errors-toggle',
undefined,
untilLoaded,
);
await userEvent.click(within(toggle).getByRole('switch'));
export const AiTraceTooltips: Story = {
args: { scenario: 'ai', spans: AI_SPANS, tooltipsOpen: true },
};
/**
@@ -142,52 +136,7 @@ const highlightErrors = async (canvasElement: HTMLElement): Promise<void> => {
*/
export const Tooltips: Story = {
args: { tooltipsOpen: true },
play: async ({ canvasElement }): Promise<void> => {
await highlightErrors(canvasElement);
// Collapsing puts the filter back behind the pill, which is where it carries
// its popover. Neither expanded action carries a label of its own, so the
// row is located by its container and the collapse is its last button.
const actions = await waitFor(() => {
const found = canvasElement.querySelector<HTMLElement>(
'[class*="expandedActions"]',
);
if (!found) {
throw new Error('Filter row is not expanded');
}
return found;
}, untilLoaded);
const expandedActions = within(actions).getAllByRole('button');
await userEvent.click(expandedActions[expandedActions.length - 1]);
// `userEvent.hover` tracks the pointer, so hovering the dot would fire the
// row's mouseleave and drop the hover card. `mouseOver` is what React reads
// to synthesise mouseenter, and it leaves the previous target alone, so both
// stay open. The dot has no test id.
const [row] = await within(canvasElement).findAllByTestId(
/^cell-0-/,
undefined,
untilLoaded,
);
await fireEvent.mouseOver(row);
await waitFor(async () => {
const dot = canvasElement.querySelector('[class*="eventDot"]');
if (!dot) {
throw new Error('no event dot rendered');
}
await fireEvent.mouseOver(dot);
}, untilLoaded);
// The dot opens its card on a 200ms timer rather than on the event itself.
await screen.findByRole('tooltip', { name: /event details/i }, untilLoaded);
},
play: showTooltips,
};
/**
@@ -197,9 +146,13 @@ export const Tooltips: Story = {
*/
export const TooltipsInFilterBar: Story = {
args: { tooltipsOpen: true },
play: async ({ canvasElement }): Promise<void> => {
await highlightErrors(canvasElement);
},
play: expandFilterBar,
};
/** Highlight errors on a trace with no failing span: the filter finds no results. */
export const HighlightErrorsNoMatches: Story = {
args: { errors: false },
play: showsHighlightedErrors,
};
/**
@@ -208,117 +161,78 @@ export const TooltipsInFilterBar: Story = {
* on.
*/
export const TraceOptionsMenu: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Trace options' },
untilLoaded,
),
);
await screen.findByText('Preview fields');
},
play: openTraceOptions,
};
/** The Analytics panel over a trace with no group to chart. */
export const AnalyticsNoData: Story = {
args: { analytics: 'empty' },
play: showsAnalyticsState,
};
/** The Analytics panel when the aggregations request fails. */
export const AnalyticsError: Story = {
args: { analytics: 'error' },
// The deliberate 500 is the state under test.
parameters: { allowConsoleErrors: true },
play: showsAnalyticsState,
};
/** The span panel moved from the right edge to the bottom through its dock toggle. */
export const DockModeSwitched: Story = {
play: async ({ canvasElement }): Promise<void> => {
// The dock options are icon-only and carry no accessible name.
const option = await within(canvasElement).findByTestId(
'dock-mode-docked',
undefined,
untilLoaded,
);
await userEvent.click(option.querySelector('button') ?? option);
},
play: switchDockMode,
};
/** The span's percentile badge expanded into the distribution it was ranked in. */
export const SpanPercentileOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /^p\d+/ },
untilLoaded,
),
);
await screen.findByText(/This span duration is/);
},
play: openPercentile,
};
/** The percentile's resource attribute picker, which narrows the spans it ranks against. */
export const SpanPercentileResourceSelector: Story = {
play: openPercentileResourceSelector,
};
/** The span panel's Events tab on the failing span: its exception event and attributes. */
export const SpanPanelEvents: Story = {
play: openSpanEvents,
};
/** The Events tab on a span with no events. */
export const SpanPanelNoEvents: Story = {
args: { errors: false },
play: openSpanEvents,
};
/** The exception's stacktrace hovered: the preview popover with its Expand action. */
export const SpanPanelEventAttributePopover: Story = {
play: hoverEventStacktrace,
};
/** The span has no logs of its own but its trace does, so the Logs tab points to the trace's. */
export const SpanPanelTraceOnlyLogs: Story = {
args: { traceOnlyLogs: true },
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole('tab', { name: /Logs/ }, untilLoaded),
);
await expect(
await within(canvasElement).findByText(
'No logs found for selected span. View logs for the current trace.',
undefined,
untilLoaded,
),
).toBeVisible();
},
play: showsTraceOnlyLogs,
};
/** The span panel's trace id copied with its copy button, which turns into a check. */
export const TraceIdCopied: Story = {
play: async ({ canvasElement }): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Copy trace ID' },
untilLoaded,
),
);
await expect(
await within(canvasElement).findByRole('button', { name: 'Copied' }),
).toBeVisible();
},
play: copyTraceId,
};
/** "Copy Value" picked from a row of the span panel's pretty view. */
export const PrettyViewValueCopiedToast: Story = {
play: async ({ canvasElement }): Promise<void> => {
await openRowMenu(canvasElement, 'Copy Value');
await expect(await screen.findByText('Copied to clipboard')).toBeVisible();
},
play: copyPrettyViewValue,
};
/** The copy-link button on a waterfall row, which copies the span's URL. */
export const SpanLinkCopiedToast: Story = {
play: async ({ canvasElement }): Promise<void> => {
const [row] = await within(canvasElement).findAllByTestId(
/^cell-0-/,
undefined,
untilLoaded,
);
await fireEvent.mouseOver(row);
// The hover re-renders the row, so the button has to be looked up after it settles.
await new Promise((resolve) => {
setTimeout(resolve, 300);
});
const [hovered] = within(canvasElement).getAllByTestId(/^cell-0-/);
// The row's hover actions have no accessible name; copy link comes first.
const [link] = within(hovered).getAllByRole('button');
await fireEvent.click(link);
await waitFor(() =>
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
);
},
play: copySpanLink,
};
/** "Download trace" as CSV, finished. */
export const TraceExportedToast: Story = {
play: async ({ canvasElement }): Promise<void> => {
await startDownload(canvasElement);
},
play: downloadTrace,
};
/** "Download trace" whose export request fails. */
@@ -326,16 +240,11 @@ export const TraceExportErrorToast: Story = {
args: { exportState: 'error' },
// The deliberate 500 is the state under test.
parameters: { allowConsoleErrors: true },
play: async ({ canvasElement }): Promise<void> => {
await startDownload(canvasElement);
},
play: downloadTrace,
};
/** "Download trace" cancelled from the download panel while the export runs. */
export const TraceExportCancelledToast: Story = {
args: { exportState: 'loading' },
play: async ({ canvasElement }): Promise<void> => {
await startDownload(canvasElement);
await userEvent.click(await screen.findByTestId('trace-download-cancel'));
},
play: cancelDownload,
};

View File

@@ -0,0 +1,501 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import {
expect,
fireEvent,
screen,
userEvent,
waitFor,
within,
} from 'storybook/test';
import { SpanDetailVariant } from '../../SpanDetailsPanel/constants';
import {
openRowMenu,
showsSpanPanel,
showsTrace,
startDownload,
type TraceDetailsArgs,
untilLoaded,
} from '../TraceDetailsV3.stories.mocks';
import {
focusSpanAttributes,
focusSpanEventCount,
focusSpanIndex,
spanIdAt,
spanMatchRows,
traceHasEvents,
} from './traceDetails';
interface PageContext {
canvasElement: HTMLElement;
args: TraceDetailsArgs;
}
const traceOf = ({
scenario,
spans,
errors,
}: TraceDetailsArgs): Parameters<typeof traceHasEvents>[0] => ({
scenario,
spans,
errors,
traceStart: 0,
});
/**
* Turns on Highlight errors, which writes `has_error = true` into the filter and
* expands the bar to show it.
*/
const highlightErrors = async (canvasElement: HTMLElement): Promise<void> => {
const toggle = await within(canvasElement).findByTestId(
'highlight-errors-toggle',
undefined,
untilLoaded,
);
await userEvent.click(within(toggle).getByRole('switch'));
};
const openPanelTab = async (
canvasElement: HTMLElement,
name: RegExp,
): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole('tab', { name }, untilLoaded),
);
};
const openSpanPercentile = async (
canvasElement: HTMLElement,
): Promise<void> => {
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: /^p\d+/ },
untilLoaded,
),
);
await screen.findByText(/This span duration is/);
};
export const showsMissingSpansBanner = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!args.missingSpans || !showsTrace(args)) {
return;
}
await within(canvasElement).findByTestId(
'missing-spans-banner',
undefined,
untilLoaded,
);
};
/** Only the LLM span the panel opens on carries usage for the card to break down. */
export const hoverAiSpan = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
const focus = focusSpanIndex(args.scenario, args.spans);
if (
!showsTrace(args) ||
!(
'gen_ai.usage.input_tokens' in focusSpanAttributes(args.scenario, args.spans)
)
) {
return;
}
const row = await within(canvasElement).findByTestId(
`cell-0-${spanIdAt(focus)}`,
undefined,
untilLoaded,
);
await fireEvent.mouseOver(row);
// The header's token tooltip carries the same title when tooltips are held open.
await screen.findAllByText('Usage Breakdown', undefined, untilLoaded);
};
export const showTooltips = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await highlightErrors(canvasElement);
// Collapsing puts the filter back behind the pill, which is where it carries
// its popover. Neither expanded action carries a label of its own, so the
// row is located by its container and the collapse is its last button.
const actions = await waitFor(() => {
const found = canvasElement.querySelector<HTMLElement>(
'[class*="expandedActions"]',
);
if (!found) {
throw new Error('Filter row is not expanded');
}
return found;
}, untilLoaded);
const expandedActions = within(actions).getAllByRole('button');
await userEvent.click(expandedActions[expandedActions.length - 1]);
// `userEvent.hover` tracks the pointer, so hovering the dot would fire the
// row's mouseleave and drop the hover card. `mouseOver` is what React reads
// to synthesise mouseenter, and it leaves the previous target alone, so both
// stay open. The dot has no test id.
const [row] = await within(canvasElement).findAllByTestId(
/^cell-0-/,
undefined,
untilLoaded,
);
await fireEvent.mouseOver(row);
if (!traceHasEvents(traceOf(args))) {
return;
}
await waitFor(async () => {
const dot = canvasElement.querySelector('[class*="eventDot"]');
if (!dot) {
throw new Error('no event dot rendered');
}
await fireEvent.mouseOver(dot);
}, untilLoaded);
// The dot opens its card on a 200ms timer rather than on the event itself.
await screen.findByRole('tooltip', { name: /event details/i }, untilLoaded);
};
export const expandFilterBar = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await highlightErrors(canvasElement);
};
/** The filter counts the failing spans, or says it found none. */
export const showsHighlightedErrors = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await highlightErrors(canvasElement);
const failing = spanMatchRows(traceOf(args), 'has_error = true').length;
await within(canvasElement).findByTestId(
failing > 0 ? 'waterfall-filter-count' : 'waterfall-filter-no-results',
undefined,
untilLoaded,
);
};
export const openTraceOptions = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Trace options' },
untilLoaded,
),
);
await screen.findByText('Preview fields');
};
export const switchDockMode = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsSpanPanel(args) || args.panelPosition === SpanDetailVariant.DOCKED) {
return;
}
// The dock options are icon-only and carry no accessible name. The floating
// panel renders outside the canvas.
const option = await screen.findByTestId(
'dock-mode-docked',
undefined,
untilLoaded,
);
await userEvent.click(option.querySelector('button') ?? option);
await waitFor(async () => {
const bottomDock = canvasElement.querySelector<HTMLElement>(
'[class*="dockedSpanDetails"]',
);
await expect(bottomDock).toBeVisible();
await expect(
within(bottomDock as HTMLElement).getByTestId('dock-mode-docked'),
).toHaveAttribute('aria-pressed', 'true');
}, untilLoaded);
};
export const openPercentile = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsSpanPanel(args)) {
return;
}
await openSpanPercentile(canvasElement);
};
export const openPercentileResourceSelector = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsSpanPanel(args)) {
return;
}
await openSpanPercentile(canvasElement);
await userEvent.click(
screen.getByRole('button', { name: 'Toggle resource attributes' }),
);
await screen.findByPlaceholderText('Search resource attributes');
};
export const showsTraceOnlyLogs = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsSpanPanel(args)) {
return;
}
await openPanelTab(canvasElement, /Logs/);
if (args.traceOnlyLogs && args.spanLogs > 0) {
await expect(
await within(canvasElement).findByText(
'No logs found for selected span. View logs for the current trace.',
undefined,
untilLoaded,
),
).toBeVisible();
}
};
export const openSpanEvents = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsSpanPanel(args)) {
return;
}
await openPanelTab(canvasElement, /Events/);
await within(canvasElement).findByText(
focusSpanEventCount(traceOf(args)) > 0
? 'exception.type'
: 'No events found for selected span',
undefined,
untilLoaded,
);
};
/** `exception.stacktrace` is an expandable key, so its value sits behind a popover with Expand. */
export const hoverEventStacktrace = async (
context: PageContext,
): Promise<void> => {
const { canvasElement, args } = context;
if (!showsSpanPanel(args) || focusSpanEventCount(traceOf(args)) === 0) {
return;
}
await openSpanEvents(context);
const key = await within(canvasElement).findByText('exception.stacktrace');
const value = key
.closest('[class*="attributeContainer"]')
?.querySelector<HTMLElement>('[class*="attributeValue"]');
await expect(value).toBeTruthy();
await userEvent.hover(value as HTMLElement);
await waitFor(
() => expect(screen.getByRole('button', { name: 'Expand' })).toBeVisible(),
untilLoaded,
);
};
export const copyTraceId = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsSpanPanel(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Copy trace ID' },
untilLoaded,
),
);
await expect(
await within(canvasElement).findByRole('button', { name: 'Copied' }),
).toBeVisible();
};
/** The row menu is found off the focus span's `rpc.method`, which only checkout's has. */
export const copyPrettyViewValue = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (
!showsSpanPanel(args) ||
!('rpc.method' in focusSpanAttributes(args.scenario, args.spans))
) {
return;
}
await openRowMenu(canvasElement, 'Copy Value');
await expect(await screen.findByText('Copied to clipboard')).toBeVisible();
};
export const copySpanLink = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
const [row] = await within(canvasElement).findAllByTestId(
/^cell-0-/,
undefined,
untilLoaded,
);
await fireEvent.mouseOver(row);
// The hover re-renders the row, so the button has to be looked up after it settles.
await new Promise((resolve) => {
setTimeout(resolve, 300);
});
const [hovered] = within(canvasElement).getAllByTestId(/^cell-0-/);
// The row's hover actions have no accessible name; copy link comes first.
const [link] = within(hovered).getAllByRole('button');
await fireEvent.click(link);
await waitFor(() =>
expect(screen.getByText('Copied to clipboard')).toBeVisible(),
);
};
const EXPORT_TOAST: Partial<Record<TraceDetailsArgs['exportState'], string>> = {
success: 'Export completed successfully',
error: 'Failed to download trace',
};
const expectExportToast = (text: string): Promise<void> =>
waitFor(async () => expect(screen.getByText(text)).toBeVisible(), untilLoaded);
export const downloadTrace = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await startDownload(canvasElement);
const toast = EXPORT_TOAST[args.exportState];
if (toast) {
await expectExportToast(toast);
} else {
await screen.findByTestId('trace-download-cancel', undefined, untilLoaded);
}
};
/** Only an export that never answers leaves the download panel up to cancel. */
export const cancelDownload = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await startDownload(canvasElement);
const toast = EXPORT_TOAST[args.exportState];
if (toast) {
await expectExportToast(toast);
return;
}
await userEvent.click(await screen.findByTestId('trace-download-cancel'));
await expectExportToast('Export cancelled');
};
export const openAnalytics = async ({
canvasElement,
args,
}: PageContext): Promise<void> => {
if (!showsTrace(args)) {
return;
}
await userEvent.click(
await within(canvasElement).findByRole(
'button',
{ name: 'Analytics' },
untilLoaded,
),
);
await screen.findByTestId('trace-analytics-panel', undefined, untilLoaded);
};
const ANALYTICS_TEXT: Partial<Record<TraceDetailsArgs['analytics'], RegExp>> = {
empty: /No data for/,
error: /Couldn't load analytics/,
};
export const showsAnalyticsState = async (
context: PageContext,
): Promise<void> => {
await openAnalytics(context);
const text = ANALYTICS_TEXT[context.args.analytics];
if (showsTrace(context.args) && text) {
await screen.findAllByText(text, undefined, untilLoaded);
}
};

View File

@@ -372,6 +372,15 @@ const buildSpans = ({
return built;
};
const stacktraceOf = (span: BuiltSpan): string =>
[
`UpstreamUnavailable: ${span.template.service} refused the request`,
` at ${span.template.name} (/app/src/${span.template.service}/client.ts:88:13)`,
' at retry (/app/src/lib/retry.ts:41:18)',
' at processTicksAndRejections (node:internal/process/task_queues:95:5)',
' at async handle (/app/src/checkout/handler.ts:127:22)',
].join('\n');
const eventsOf = (span: BuiltSpan): SpantypesWaterfallSpanDTO['events'] =>
span.hasError
? [
@@ -383,12 +392,33 @@ const eventsOf = (span: BuiltSpan): SpantypesWaterfallSpanDTO['events'] =>
attributeMap: {
'exception.type': 'UpstreamUnavailable',
'exception.message': `${span.template.service} refused the request`,
'exception.stacktrace': stacktraceOf(span),
},
isError: true,
},
]
: [];
/** Events on the span the panel opens on, which is what its Events tab lists. */
export const focusSpanEventCount = (options: TraceOptions): number => {
const span =
buildSpans(options)[focusSpanIndex(options.scenario, options.spans)];
return span ? (eventsOf(span)?.length ?? 0) : 0;
};
/** Whether any span carries an event, and with it a dot on its waterfall bar. */
export const traceHasEvents = (options: TraceOptions): boolean =>
buildSpans(options).some((span) => (eventsOf(span)?.length ?? 0) > 0);
export const focusSpanAttributes = (
scenario: TraceScenario,
spans: number,
): SpanTemplate['attributes'] =>
SCENARIO_TEMPLATES[scenario][
focusSpanIndex(scenario, spans) % SCENARIO_TEMPLATES[scenario].length
].attributes;
const resourceOf = (span: BuiltSpan): Record<string, string> => ({
'service.name': span.template.service,
'deployment.environment': 'production',
@@ -684,18 +714,24 @@ export const spanLogRows = (
};
/**
* Span ids for the header's span search. Every span answers, so a filter typed
* in the story highlights the whole trace rather than nothing.
* Span ids for the header's span search. Every span answers a typed filter, so
* it highlights the whole trace rather than nothing; `has_error = true`, which
* Highlight errors writes, answers with the failing spans alone.
*/
export const spanMatchRows = (options: TraceOptions): RawRow[] =>
buildSpans(options).map((span) => ({
timestamp: new Date(span.startMs).toISOString(),
data: {
span_id: span.spanId,
spanID: span.spanId,
timestamp: Math.round(span.startMs * 1_000_000),
},
}));
export const spanMatchRows = (
options: TraceOptions,
expression: string,
): RawRow[] =>
buildSpans(options)
.filter((span) => !/has_error\s*=\s*true/.test(expression) || span.hasError)
.map((span) => ({
timestamp: new Date(span.startMs).toISOString(),
data: {
span_id: span.spanId,
spanID: span.spanId,
timestamp: Math.round(span.startMs * 1_000_000),
},
}));
const TRACE_FIELD_KEYS = [
'service.name',

View File

@@ -9,9 +9,12 @@ import ROUTES from 'constants/routes';
import { USER_PREFERENCES } from 'constants/userPreferences';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { spanPercentilesResponse } from 'pages/TraceDetailsV3/stories/__story_mockdata__/traceDetails';
import type { CreateFunnelPayload } from 'types/api/traceFunnels';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import { USER_ROLES } from 'types/roles';
import { explorerViewToPanelType } from 'utils/explorerUtils';
import { accessFor } from '@/storybook/access/access';
import {
choiceControl,
countControl,
@@ -29,6 +32,7 @@ import {
import {
exportDashboardsResponse,
ORDERS_SPAN_ROWS,
savedTraceViewsResponse,
SPAN_LOGS_STATES,
spanLogRows,
@@ -193,6 +197,36 @@ export const tracesMocks = defineStoryMocks({
response.json(() => traceFunnelsResponse(values.funnels)),
),
// The backend wraps a taken name in a 400, which the dialog shows under the field.
rest.post(
'http://localhost/api/v1/trace-funnels/new',
async (req, res, ctx) => {
const { funnel_name: name } = (await req.json()) as CreateFunnelPayload;
const taken = traceFunnelsResponse(values.funnels).data.some(
({ funnel_name }) => funnel_name === name,
);
return taken
? res(
ctx.status(400),
ctx.json({
status: 'error',
error: {
code: 'invalid_input',
message: `failed to create funnel: a funnel with name '${name}' already exists in this organization`,
},
}),
)
: res(
ctx.status(200),
ctx.json({
status: 'success',
data: { funnel_id: 'storybook-funnel-new' },
}),
);
},
),
rest.get(
'http://localhost/api/v2/users/me/dashboards',
response.json(exportDashboardsResponse),
@@ -357,3 +391,50 @@ export const tracesMocks = defineStoryMocks({
});
export type TracesArgs = PageStoryArgs<typeof tracesMocks>;
/** The span drawer opens from a row of the spans list, so no other view has one. */
export const listsOrdersSpan = (args: TracesArgs): boolean =>
args.tab === 'explorer' &&
args.view === ExplorerViews.LIST &&
args.dataState === 'loaded' &&
args.spans >= ORDERS_SPAN_ROWS;
/** What the drawer's Logs tab settles on, from the two controls that decide it. */
export type DrawerLogs =
| 'waiting'
| 'error'
| 'logs'
| 'trace-only'
| 'none'
| 'span-empty';
export const drawerLogsOf = ({
spanLogs,
traceSummary,
}: Pick<TracesArgs, 'spanLogs' | 'traceSummary'>): DrawerLogs => {
if (traceSummary === 'loading' || spanLogs === 'loading') {
return 'waiting';
}
if (spanLogs === 'error') {
return 'error';
}
if (spanLogs === 'span') {
return 'logs';
}
// Without the trace bounds the drawer never checks the trace's own logs.
if (traceSummary === 'not found') {
return 'span-empty';
}
return spanLogs === 'trace only' ? 'trace-only' : 'none';
};
/** `hasEditPermission`, which every funnel action gates on. */
export const canEditFunnels = (args: TracesArgs): boolean => {
const { legacyRole } = accessFor(args.access, args.permissions, args.revoked);
return legacyRole === USER_ROLES.ADMIN || legacyRole === USER_ROLES.EDITOR;
};

View File

@@ -5,9 +5,14 @@ import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import { type TracesArgs, tracesMocks } from './TracesModulePage.stories.mocks';
import {
cancelQuery,
dirtyQuickFiltersSettings,
loadNextListPage,
openAddToDashboard,
openColumnHeaderMenu,
openPageSize,
openQuickFiltersSettings,
showCreateFunnelNameError,
showRootSpansNextPage,
suggestBooleanValues,
suggestFilterKeys,
@@ -67,6 +72,22 @@ export const ListNextPage: Story = {
play: loadNextListPage,
};
/** The Trace view's page size menu, open over the rows a page can show. */
export const PageSizeOpen: Story = {
args: { view: ExplorerViews.TRACE },
play: openPageSize,
};
/** A spans list column's header menu, open on its Remove column action. */
export const ColumnHeaderMenu: Story = {
play: openColumnHeaderMenu,
};
/** The dashboard picker the toolbar's Add to dashboard action opens. */
export const AddToDashboardDialog: Story = {
play: openAddToDashboard,
};
/** The charted view of the same trace query. */
export const Timeseries: Story = {
args: { view: ExplorerViews.TIMESERIES },
@@ -82,6 +103,19 @@ export const Funnels: Story = {
args: { tab: 'funnels' },
};
/** The Funnels tab with none saved: the empty state and its New funnel action. */
export const FunnelsEmpty: Story = {
args: { tab: 'funnels', funnels: 0 },
};
/** The create dialog after the backend turned down a name already on the list. */
export const CreateFunnelNameError: Story = {
args: { tab: 'funnels' },
// The deliberate 400 is the state under test.
parameters: { allowConsoleErrors: true },
play: showCreateFunnelNameError,
};
/**
* A fresh workspace: nothing ingested in the window and no quick filters
* configured yet, so the table and the filter panel both show their empty
@@ -96,6 +130,12 @@ export const Loading: Story = {
args: { dataState: 'loading' },
};
/** The running query cancelled from the toolbar, which swaps the list for the cancelled notice. */
export const QueryCancelled: Story = {
args: { dataState: 'loading' },
play: cancelQuery,
};
/** A query response carrying the backend's warning details. */
export const QueryWarning: Story = {
args: { warning: true },

View File

@@ -0,0 +1,249 @@
/**
* AI-owned. Generated and maintained by the `signoz-page-story` skill.
* Do not hand-edit: regenerate instead.
*/
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import {
drawerLogsOf,
listsOrdersSpan,
type TracesArgs,
} from '../TracesModulePage.stories.mocks';
import { ORDERS_OPERATION, ORDERS_SPAN_ROWS, spanOperationAt } from './traces';
interface PlayContext {
args: TracesArgs;
}
interface MountContext extends PlayContext {
mount: () => Promise<unknown>;
}
/** The page fetches before it renders its rows, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
// The quick filters list the same span name, so the row is found by its test
// id; the table renders its rows a few at a time, so it waits for this one.
const findOrdersRow = (): Promise<HTMLElement> =>
waitFor(async (): Promise<HTMLElement> => {
const match = screen
.getAllByTestId(/^traces-table-row-/)
.find((candidate) => candidate.textContent?.includes(ORDERS_OPERATION));
await expect(match).toBeDefined();
return match as HTMLElement;
}, untilLoaded);
const openDrawer = async (): Promise<HTMLElement> => {
const row = await findOrdersRow();
await userEvent.click(within(row).getByText(ORDERS_OPERATION));
return screen.findByTestId('span-details-drawer');
};
const openLogsTab = async (): Promise<HTMLElement> => {
const drawer = await openDrawer();
await userEvent.click(within(drawer).getByRole('tab', { name: /Logs/ }));
return drawer;
};
const mountOnLogsTab = async (
mount: MountContext['mount'],
args: TracesArgs,
): Promise<HTMLElement | null> => {
await mount();
return listsOrdersSpan(args) ? openLogsTab() : null;
};
export const showsSpanDetails = async ({
args,
}: PlayContext): Promise<void> => {
if (!listsOrdersSpan(args)) {
return;
}
const drawer = await openDrawer();
// The percentage is read off the trace summary.
if (args.traceSummary === 'found') {
await expect(
await within(drawer).findByText(
/of total exec time/,
undefined,
untilLoaded,
),
).toBeVisible();
}
};
export const openSpanDetails = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
await showsSpanDetails({ args });
};
export const hoverOrdersRow = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
if (!listsOrdersSpan(args)) {
return;
}
await userEvent.hover(await findOrdersRow());
await expect(await screen.findByTestId('span-row-open-trace')).toBeVisible();
};
export const showsSpanLogs = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'logs') {
return;
}
await expect(
(
await within(drawer).findAllByText(
/payment provider timed out/,
undefined,
untilLoaded,
)
)[0],
).toBeVisible();
};
export const showsTraceOnlyLogs = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'trace-only') {
return;
}
await expect(
await within(drawer).findByText(
'No logs found for selected span. View logs for the current trace.',
undefined,
untilLoaded,
),
).toBeVisible();
};
export const showsNoLogs = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'none') {
return;
}
await expect(
await within(drawer).findByText(
'No logs found for this trace.',
undefined,
untilLoaded,
),
).toBeVisible();
};
export const showsWithoutTraceSummary = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer) {
return;
}
if (drawerLogsOf(args) === 'span-empty') {
await expect(
await within(drawer).findByText(
'No logs found for this span.',
undefined,
untilLoaded,
),
).toBeVisible();
}
if (args.traceSummary === 'not found') {
await expect(
within(drawer).queryByText(/of total exec time/),
).not.toBeInTheDocument();
}
};
export const showsTraceSummaryLoading = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || args.traceSummary !== 'loading') {
return;
}
await expect(
await screen.findByTestId('open-in-explorer-button'),
).toHaveAttribute('aria-disabled', 'true');
};
export const showsLogsError = async ({
mount,
args,
}: MountContext): Promise<void> => {
const drawer = await mountOnLogsTab(mount, args);
if (!drawer || drawerLogsOf(args) !== 'error') {
return;
}
await expect(
await within(drawer).findByText(
/Something went wrong/,
undefined,
untilLoaded,
),
).toBeVisible();
};
/** The row under the orders span is the one ArrowDown opens. */
export const stepToNextSpan = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
if (!listsOrdersSpan(args) || args.spans <= ORDERS_SPAN_ROWS) {
return;
}
const drawer = await openDrawer();
await userEvent.keyboard('{ArrowDown}');
await expect(
await within(drawer).findByText(
spanOperationAt(ORDERS_SPAN_ROWS),
undefined,
untilLoaded,
),
).toBeVisible();
};

View File

@@ -15,7 +15,11 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { grantsAll } from '@/storybook/access/access';
import type { TracesArgs } from '../TracesModulePage.stories.mocks';
import {
canEditFunnels,
type TracesArgs,
} from '../TracesModulePage.stories.mocks';
import { traceFunnelsResponse } from './traces';
interface PlayContext {
canvasElement: HTMLElement;
@@ -189,3 +193,158 @@ export const showFilterSyntaxError = async ({
await showFilterErrors(canvasElement, 'has_error = true AND');
};
export const openCreateFunnel = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.tab !== 'funnels' || !canEditFunnels(args)) {
return;
}
// With no funnels the empty state offers the same button beside the header's.
const [newFunnel] = await within(canvasElement).findAllByRole(
'button',
{ name: /new funnel/i },
untilLoaded,
);
await userEvent.click(newFunnel);
await screen.findByRole('dialog', { name: /create new funnel/i });
};
/** Row actions exist only once the list holds a funnel. */
export const openRenameFunnel = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (
args.tab !== 'funnels' ||
args.funnels === 0 ||
args.dataState !== 'loaded' ||
!canEditFunnels(args)
) {
return;
}
const action = await waitFor(() => {
const found = canvasElement.querySelector<HTMLElement>(
'.funnel-item__action-icon',
);
if (!found) {
throw new Error('Funnel row actions are not rendered');
}
return found;
}, untilLoaded);
await userEvent.click(action);
await userEvent.click(await screen.findByRole('button', { name: 'Rename' }));
await screen.findByRole('dialog', { name: /rename funnel/i });
};
export const cancelQuery = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.tab !== 'explorer' || args.dataState !== 'loading') {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'explorer-run-query-btn-cancel',
undefined,
untilLoaded,
),
);
await screen.findByText(/query cancelled/i, undefined, untilLoaded);
};
export const openAddToDashboard = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (args.tab !== 'explorer' || args.dataState !== 'loaded') {
return;
}
// The button stays disabled until the explorer hands it a query; a click on
// it before then is dropped in silence.
const addToDashboard = await waitFor(async () => {
const button = within(canvasElement).getByTestId('explorer-add-to-dashboard');
await expect(button).not.toBeDisabled();
await expect(button).not.toHaveAttribute('aria-disabled', 'true');
return button;
}, untilLoaded);
await userEvent.click(addToDashboard);
await screen.findByTestId('export-panel-dialog', undefined, untilLoaded);
};
/** The trace view pins its columns, so only the spans list offers column actions. */
export const openColumnHeaderMenu = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsView(args, ExplorerViews.LIST) || args.spans === 0) {
return;
}
const [actions] = await within(canvasElement).findAllByRole(
'button',
{ name: /^Column actions for/ },
untilLoaded,
);
await userEvent.click(actions);
await screen.findByRole('button', { name: 'Remove column' });
};
/** Only the trace view pages; the spans list loads more as it scrolls. */
export const openPageSize = async ({
canvasElement,
args,
}: PlayContext): Promise<void> => {
if (!showsView(args, ExplorerViews.TRACE) || args.spans === 0) {
return;
}
await userEvent.click(
await within(canvasElement).findByTestId(
'pagination-page-size',
undefined,
untilLoaded,
),
);
await screen.findByRole('listbox');
};
/** A name the list already holds is the one the backend turns down. */
export const showCreateFunnelNameError = async (
context: PlayContext,
): Promise<void> => {
const { args } = context;
const [taken] = traceFunnelsResponse(args.funnels).data;
if (
args.tab !== 'funnels' ||
!taken ||
args.dataState !== 'loaded' ||
!canEditFunnels(args)
) {
return;
}
await openCreateFunnel(context);
await userEvent.type(
await screen.findByTestId('create-funnel-name-input'),
taken.funnel_name,
);
await userEvent.click(screen.getByRole('button', { name: /create funnel/i }));
await screen.findByTestId('create-funnel-error', undefined, untilLoaded);
};

View File

@@ -108,6 +108,15 @@ const SPANS: SpanShape[] = [
},
];
export const ORDERS_OPERATION = 'POST /api/orders';
/** Rows the list needs before the span the drawer stories open is on it. */
export const ORDERS_SPAN_ROWS =
SPANS.findIndex(({ operation }) => operation === ORDERS_OPERATION) + 1;
export const spanOperationAt = (index: number): string =>
SPANS[index % SPANS.length].operation;
const TRACE_SERVICE_NAMES = SPANS.map(({ service }) => service);
const hex = (prefix: string, index: number): string =>

View File

@@ -1,10 +1,19 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
import { tracesMocks } from '../TracesModulePage.stories.mocks';
import {
hoverOrdersRow,
openSpanDetails,
showsLogsError,
showsNoLogs,
showsSpanLogs,
showsTraceOnlyLogs,
showsTraceSummaryLoading,
showsWithoutTraceSummary,
stepToNextSpan,
} from '../__story_mockdata__/spanDrawer.play';
import TracesModulePage from '../../TracesModulePage';
@@ -31,55 +40,12 @@ export default meta;
type Story = StoryObj<TracesArgs>;
/** The page fetches before it renders its rows, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
// The quick filters list the same span name, so the row is found by its test
// id; the table renders its rows a few at a time, so it waits for this one.
const findOrdersRow = (): Promise<HTMLElement> =>
waitFor((): HTMLElement => {
const match = screen
.getAllByTestId(/^traces-table-row-/)
.find((candidate) => candidate.textContent?.includes('POST /api/orders'));
expect(match).toBeDefined();
return match as HTMLElement;
}, untilLoaded);
const openDrawer = async (): Promise<HTMLElement> => {
const row = await findOrdersRow();
await userEvent.click(within(row).getByText('POST /api/orders'));
return screen.findByTestId('span-details-drawer');
};
const openLogsTab = async (): Promise<HTMLElement> => {
const drawer = await openDrawer();
await userEvent.click(within(drawer).getByRole('tab', { name: /Logs/ }));
return drawer;
};
/**
* The drawer on a failing span: its summary with % exec time, attributes, the
* exception event and a linked span, with up and down stepping through the page.
*/
export const Default: Story = {
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openDrawer();
await expect(
await within(drawer).findByText(
/of total exec time/,
undefined,
untilLoaded,
),
).toBeVisible();
},
play: openSpanDetails,
};
/**
@@ -87,65 +53,30 @@ export const Default: Story = {
* tab, without opening the drawer.
*/
export const OpenTraceIcon: Story = {
play: async ({ mount }): Promise<void> => {
await mount();
await userEvent.hover(await findOrdersRow());
play: hoverOrdersRow,
};
await expect(await screen.findByTestId('span-row-open-trace')).toBeVisible();
},
/** ArrowDown with the drawer open, which moves it to the next span in the list. */
export const ArrowKeyNext: Story = {
play: stepToNextSpan,
};
/** The Logs tab with the span's logs, between the logs just before and after them. */
export const Logs: Story = {
args: { spanLogs: 'span' },
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
(
await within(drawer).findAllByText(
/payment provider timed out/,
undefined,
untilLoaded,
)
)[0],
).toBeVisible();
},
play: showsSpanLogs,
};
/** The span has no logs of its own but its trace does, so the tab points to the trace's. */
export const TraceOnlyLogs: Story = {
args: { spanLogs: 'trace only' },
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for selected span. View logs for the current trace.',
undefined,
untilLoaded,
),
).toBeVisible();
},
play: showsTraceOnlyLogs,
};
/** Neither the span nor its trace has logs. */
export const NoLogs: Story = {
args: { spanLogs: 'none' },
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for this trace.',
undefined,
untilLoaded,
),
).toBeVisible();
},
play: showsNoLogs,
};
/**
@@ -156,34 +87,13 @@ export const WithoutTraceSummary: Story = {
args: { traceSummary: 'not found', spanLogs: 'none' },
// The deliberate 404 is the state under test.
parameters: { allowConsoleErrors: true },
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
'No logs found for this span.',
undefined,
untilLoaded,
),
).toBeVisible();
await expect(
within(drawer).queryByText(/of total exec time/),
).not.toBeInTheDocument();
},
play: showsWithoutTraceSummary,
};
/** The trace summary never answers: the Logs tab waits and its explorer link is off. */
export const TraceSummaryLoading: Story = {
args: { traceSummary: 'loading' },
play: async ({ mount }): Promise<void> => {
await mount();
await openLogsTab();
await expect(
await screen.findByTestId('open-in-explorer-button'),
).toHaveAttribute('aria-disabled', 'true');
},
play: showsTraceSummaryLoading,
};
/** The log queries fail while the rest of the drawer renders. */
@@ -191,16 +101,5 @@ export const LogsError: Story = {
args: { spanLogs: 'error' },
// The deliberate 500 is the state under test.
parameters: { allowConsoleErrors: true },
play: async ({ mount }): Promise<void> => {
await mount();
const drawer = await openLogsTab();
await expect(
await within(drawer).findByText(
/Something went wrong/,
undefined,
untilLoaded,
),
).toBeVisible();
},
play: showsLogsError,
};