Compare commits

...

7 Commits

Author SHA1 Message Date
Aditya Singh
300d0c92e8 feat(traces-explorer): show the missing spans banner in the span drawer 2026-12-03 11:32:27 +05:30
Aditya Singh
f26a07ed42 feat(trace): cache trace queries and cancel them when the trace changes
A trace whose summary reports missing spans may still be ingesting, so its
queries skip the cache. A windowed waterfall response depends on the
expanded nodes, so only a complete trace comes from the cache.
2026-12-03 11:32:20 +05:30
Aditya Singh
a2ee6ab5b5 feat(traces-explorer): show the flame graph and waterfall in the span drawer
The trace page's flame graph, waterfall and span counts now render outside
the trace page. A trace whose summary returns 404 has no trace pane, because
the views read the same summary table.
2026-12-03 11:32:09 +05:30
Aditya Singh
68e54e4280 fix(trace-details): keep the waterfall hover card next to its row
A deep tree is wider than its column, so the card now opens beside the part
of the row on screen. New spans replace the rows, so the card closes and
opens again on the next pointer move.
2026-12-03 11:32:07 +05:30
Aditya Singh
700fa676b5 feat(traces-explorer): open the span drawer from the url
The open span lives in the url, so a refresh or a shared link reopens it.
↑/↓ step from the last row opened from the list. The page closes the drawer
on a new query or view, since the list unmounts on other views.

A span the list does not show loads from the trace. An unknown span falls
back to the trace's root span. An unknown trace shows the trace page's
not-found state.
2026-12-03 11:32:06 +05:30
Aditya Singh
7bd489dac4 refactor(trace-details): share the waterfall data and the selected span id 2026-12-03 11:31:56 +05:30
Aditya Singh
6140cea7dd fix(trace-details): line up the waterfall ruler and keep short bars inside the track 2026-12-03 11:31:47 +05:30
62 changed files with 3057 additions and 543 deletions

View File

@@ -121,6 +121,7 @@ Before writing the clicks, list what has to be on screen for the play's target t
- A second list beside the main one, such as saved views. At 0, loading or failed, its actions are gone.
- Text that depends on an arg. A disabled rule offers Enable, not Disable. A write that fails raises a different toast from one that lands, and one left loading raises none. Pick the expected text from the args.
- Rows that move. A view, a sort or pinning changes which row is locked, pinned or legacy, so find the row by what it is, not by its index.
- A response control that a second request depends on. In the traces explorer span drawer, the `Trace summary` control on `not found` means the trace views would 404 too, so the drawer drops the trace pane, and a span the list doesn't show becomes not found. The Waterfall tab play and the url plays still expected the pane and the span. When one response decides whether another part of the page exists, branch on it too.
Make those checks with the page's own code instead of restating a condition. Build the rows with the builder the handler uses and the view's own filter, and check a permission with the page's own check through `accessFor(...).allows(...)`, or the role against the constant the page gates on, such as `componentPermission.action`. Export the checks from the mocks module, next to the handlers, so a handler change moves them too. The alert rules page has `listedRules`, `hasRowMenu`, `showsNoRulesPage` and `listsSavedViews`; the dashboards list has `listedDashboards`, `canList`, `canCreate` and `canUpdate`.

View File

@@ -0,0 +1,6 @@
// Test stub for the flame graph's layout worker: jest can't parse
// `import.meta.url` (see moduleNameMapper in jest.config.ts). jsdom has no
// Worker, so the hook computes the layout in place and never calls this.
export function createLayoutWorker(): Worker {
throw new Error('No layout worker under jest');
}

View File

@@ -18,6 +18,8 @@ const config: Config.InitialOptions = {
// The icon glob module uses `import.meta.glob` (Vite-only); jest can't parse
// it, so redirect any import of it to a stub.
'(^|/)iconAssets$': '<rootDir>/__mocks__/iconAssetsMock.ts',
// The flame graph's layout worker is built from `import.meta.url` (Vite-only).
'(^|/)createLayoutWorker$': '<rootDir>/__mocks__/createLayoutWorkerMock.ts',
'^@/(.*)$': '<rootDir>/src/$1',
'\\.(css|less|scss)$': '<rootDir>/__mocks__/cssMock.ts',
'\\.module\\.mjs$': '<rootDir>/__mocks__/cssMock.ts',

View File

@@ -8,6 +8,7 @@ import {
const getTraceV4 = async (
props: GetTraceV4PayloadProps,
signal?: AbortSignal,
): Promise<SuccessResponse<GetTraceV4SuccessResponse> | ErrorResponse> => {
let uncollapsedSpans = [...props.uncollapsedSpans];
if (!props.isSelectedSpanIDUnCollapsed) {
@@ -28,6 +29,7 @@ const getTraceV4 = async (
selectedSpanId: props.selectedSpanId,
uncollapsedSpans,
},
signal,
);
// Generated client unwraps the axios response; .data is the waterfall payload.

View File

@@ -1,5 +1,5 @@
import { ReactNode } from 'react';
import { Drawer } from '@signozhq/ui/drawer';
import { Drawer, type DrawerWidthType } from '@signozhq/ui/drawer';
interface DetailsPanelDrawerProps {
isOpen: boolean;
@@ -9,6 +9,7 @@ interface DetailsPanelDrawerProps {
headerSuffix?: ReactNode;
loading?: boolean;
testId?: string;
width?: DrawerWidthType;
}
function DetailsPanelDrawer({
@@ -19,6 +20,7 @@ function DetailsPanelDrawer({
headerSuffix,
loading,
testId,
width,
}: DetailsPanelDrawerProps): JSX.Element {
return (
<Drawer
@@ -27,7 +29,7 @@ function DetailsPanelDrawer({
open={isOpen}
onClose={onClose}
title={title}
width="extra-wide"
width={width}
closePosition="start"
headerSuffix={headerSuffix}
loading={loading}
@@ -42,6 +44,7 @@ DetailsPanelDrawer.defaultProps = {
headerSuffix: undefined,
loading: false,
testId: undefined,
width: 'extra-wide',
};
export default DetailsPanelDrawer;

View File

@@ -115,14 +115,23 @@ function ListView({
queryKeyRef.current = queryKey;
}
const { rows, warning, isFetching, isLoading, isError, error, loadMore } =
useListViewInfiniteQuery({
query: requestQuery,
queryKey,
enabled:
// don't make api call while the time range state in redux is loading
!timeRangeUpdateLoading && !!stagedQuery && panelType === PANEL_TYPES.LIST,
});
const {
rows,
warning,
isFetching,
isLoading,
isIdle,
isNewQueryLoading,
isError,
error,
loadMore,
} = useListViewInfiniteQuery({
query: requestQuery,
queryKey,
enabled:
// don't make api call while the time range state in redux is loading
!timeRangeUpdateLoading && !!stagedQuery && panelType === PANEL_TYPES.LIST,
});
useEffect(() => {
setWarning(warning);
@@ -137,7 +146,7 @@ function ListView({
}, [isLoading, isFetching, setIsLoadingQueries]);
const { tableProps, openTraceColumn, drawerProps, onPressInside } =
useSpanDrawer(rows);
useSpanDrawer(rows, isLoading || isIdle || isNewQueryLoading);
const columns = useMemo<TableColumnDef<TracesTableRow>[]>(() => {
const fields = [

View File

@@ -20,6 +20,10 @@ type UseListViewInfiniteQueryResult = {
rows: TracesTableRow[];
warning: Warning | undefined;
isLoading: boolean;
/** Disabled before its first fetch: no staged query yet, or the time range still loading. */
isIdle: boolean;
/** A new query is loading; `rows` stay empty until it answers. */
isNewQueryLoading: boolean;
isFetching: boolean;
isError: boolean;
error: Error | null;
@@ -36,6 +40,7 @@ export function useListViewInfiniteQuery({
const {
data,
isLoading,
isIdle,
isFetching,
isFetchingNextPage,
isError,
@@ -100,6 +105,8 @@ export function useListViewInfiniteQuery({
rows,
warning: data?.pages[data.pages.length - 1]?.warning,
isLoading,
isIdle,
isNewQueryLoading: !keepRows,
isFetching,
isError,
error: error as Error | null,

View File

@@ -0,0 +1,28 @@
import TraceFlamegraph from 'pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph';
import { NO_FILTERED_SPANS } from './constants';
import { TRACE_VIEW_LOADER } from './TraceViewLoader';
type DrawerFlamegraphProps = {
traceId: string;
totalSpansCount: number | undefined;
};
function DrawerFlamegraph({
traceId,
totalSpansCount,
}: DrawerFlamegraphProps): JSX.Element {
return (
<TraceFlamegraph
traceId={traceId}
filteredSpanIds={NO_FILTERED_SPANS}
isFilterActive={false}
// Only a sampled flame graph reads it, and the drawer never shows one.
selectedSpan={undefined}
totalSpansCount={totalSpansCount ?? 0}
loadingFallback={TRACE_VIEW_LOADER}
/>
);
}
export default DrawerFlamegraph;

View File

@@ -0,0 +1,37 @@
import type { UseTraceWaterfallDataResult } from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import TraceWaterfall from 'pages/TraceDetailsV3/TraceWaterfall/TraceWaterfall';
import { NO_FILTERED_SPANS } from './constants';
import { TRACE_VIEW_LOADER } from './TraceViewLoader';
type DrawerWaterfallProps = {
traceId: string;
waterfall: UseTraceWaterfallDataResult;
};
function DrawerWaterfall({
traceId,
waterfall,
}: DrawerWaterfallProps): JSX.Element {
return (
<TraceWaterfall
traceId={traceId}
traceData={waterfall.traceData}
isFetchingTraceData={waterfall.isFetchingTraceData}
errorFetchingTraceData={waterfall.errorFetchingTraceData}
interestedSpanId={waterfall.interestedSpanId}
setInterestedSpanId={waterfall.setInterestedSpanId}
uncollapsedNodes={waterfall.uncollapsedNodes}
isFullDataLoaded={waterfall.isFullDataLoaded}
localUncollapsedNodes={waterfall.localUncollapsedNodes}
setLocalUncollapsedNodes={waterfall.setLocalUncollapsedNodes}
selectedSpan={waterfall.selectedSpan}
setSelectedSpan={waterfall.setSelectedSpan}
filteredSpanIds={NO_FILTERED_SPANS}
isFilterActive={false}
loadingFallback={TRACE_VIEW_LOADER}
/>
);
}
export default DrawerWaterfall;

View File

@@ -2,7 +2,6 @@ import { useMemo } from 'react';
import { Button } from '@signozhq/ui/button';
import { ButtonGroup } from '@signozhq/ui/button-group';
import { ChevronDown, ChevronUp, CornerUpRight } from '@signozhq/icons';
import { useGetTraceSummary } from 'api/generated/services/tracedetail';
import { HeaderAction } from 'components/DetailsPanel';
import { PANEL_TYPES } from 'constants/queryBuilder';
import type { UseRowNavigationResult } from 'components/TanStackTableView/useRowNavigation';
@@ -12,28 +11,50 @@ import {
} from 'container/TracesExplorer/events';
import { getTraceLink } from 'container/TracesExplorer/ListView/utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import NoData from 'pages/TraceDetailsV3/NoData/NoData';
import { SpanDetailVariant } from 'pages/TraceDetailsV3/SpanDetailsPanel/constants';
import SpanDetailsPanel from 'pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel';
import { useTraceSummary } from 'pages/TraceDetailsV3/TraceDetailsHeader/useTraceSummary';
import { noop } from 'lodash-es';
import { openInNewTab } from 'utils/navigation';
import SpanDrawerTracePane from './SpanDrawerTracePane';
import { useArrowKeyNavigation } from './useArrowKeyNavigation';
import { toSpanV3 } from './utils';
import { useDrawerSpan } from './useDrawerSpan';
import { useDrawerTraceView } from './useDrawerTraceView';
export type SpanDrawerProps = {
traceId: string | null;
spanId: string | null;
/** The list row of the open span, when it is loaded. */
row: TracesTableRow | null;
onClose: () => void;
navigation: UseRowNavigationResult;
/** Null when no list row anchors ↑/↓. */
navigation: UseRowNavigationResult | null;
/** The list's first load; until it settles a missing `row` is not final. */
isListLoading: boolean;
};
function SpanDrawer({
traceId,
spanId,
row,
onClose,
navigation,
isListLoading,
}: SpanDrawerProps): JSX.Element {
const { goToPrev, goToNext, isPrevDisabled, isNextDisabled } = navigation;
const isOpen = row !== null;
const isOpen = !!traceId && !!spanId;
const hasNavigation = navigation !== null;
const goToPrev = navigation?.goToPrev ?? noop;
const goToNext = navigation?.goToNext ?? noop;
const isPrevDisabled = navigation?.isPrevDisabled ?? true;
const isNextDisabled = navigation?.isNextDisabled ?? true;
useArrowKeyNavigation({ enabled: isOpen, onPrev: goToPrev, onNext: goToNext });
useArrowKeyNavigation({
enabled: isOpen && hasNavigation,
onPrev: goToPrev,
onNext: goToNext,
});
const panelState = useMemo(
() => ({ isOpen, open: (): void => {}, close: onClose }),
@@ -41,10 +62,10 @@ function SpanDrawer({
);
const headerActions = useMemo((): HeaderAction[] => {
if (!row) {
if (!traceId || !spanId) {
return [];
}
return [
const actions: HeaderAction[] = [
{
key: 'view-full-trace',
component: (
@@ -55,7 +76,7 @@ function SpanDrawer({
prefix={<CornerUpRight />}
onClick={(): void => {
logOpenTraceClicked(PANEL_TYPES.LIST, OpenTraceSource.SpanDrawer);
openInNewTab(getTraceLink(row));
openInNewTab(getTraceLink({ trace_id: traceId, span_id: spanId }));
}}
testId="span-drawer-view-full-trace"
>
@@ -63,6 +84,12 @@ function SpanDrawer({
</Button>
),
},
];
if (!hasNavigation) {
return actions;
}
return [
...actions,
{
key: 'nav',
component: (
@@ -93,16 +120,37 @@ function SpanDrawer({
),
},
];
}, [row, goToPrev, goToNext, isPrevDisabled, isNextDisabled]);
}, [
traceId,
spanId,
hasNavigation,
goToPrev,
goToNext,
isPrevDisabled,
isNextDisabled,
]);
const span = useMemo(() => (row ? toSpanV3(row) : undefined), [row]);
// Each trace's own summary: the counts and the 404 must not describe the last one.
const {
data: traceSummary,
isLoading: isTraceBoundsLoading,
isNotFound: isSummaryNotFound,
} = useTraceSummary(traceId ?? '', { keepPreviousData: false, retry: false });
const totalSpansCount = traceSummary?.totalSpansCount;
const traceView = useDrawerTraceView({
traceId,
totalSpansCount,
isSummaryLoading: isTraceBoundsLoading,
});
const traceId = span?.trace_id ?? '';
const { data: traceSummary, isLoading: isTraceBoundsLoading } =
useGetTraceSummary(
{ traceID: traceId },
{ query: { enabled: !!traceId, retry: false } },
);
const { span, isStale, isTraceMissing, waterfall } = useDrawerSpan({
traceId,
spanId,
row,
isListLoading,
isWaterfallShown: traceView.isWaterfallShown,
isSummaryNotFound,
});
return (
<SpanDetailsPanel
@@ -110,9 +158,24 @@ function SpanDrawer({
selectedSpan={span}
variant={SpanDetailVariant.DRAWER}
headerActions={headerActions}
traceStartTime={traceSummary?.data?.startTimestampMillis}
traceEndTime={traceSummary?.data?.endTimestampMillis}
isTraceBoundsLoading={isTraceBoundsLoading}
traceStartTime={traceSummary?.startTimestampMillis}
traceEndTime={traceSummary?.endTimestampMillis}
// The bounds are for the next span; hold the stale one's logs.
isTraceBoundsLoading={isTraceBoundsLoading || isStale}
isStale={isStale}
emptyState={isTraceMissing ? <NoData /> : undefined}
tracePane={
traceId && !isTraceMissing && !isSummaryNotFound ? (
<SpanDrawerTracePane
traceId={traceId}
traceView={traceView}
waterfall={waterfall}
totalSpansCount={totalSpansCount}
totalErrorSpansCount={traceSummary?.totalErrorSpansCount}
hasMissingSpans={!!traceSummary?.hasMissingSpans}
/>
) : null
}
/>
);
}

View File

@@ -0,0 +1,36 @@
// Fixed above the scrolling span details.
.pane {
flex-shrink: 0;
border-bottom: 1px solid var(--l2-border);
background: var(--l2-background);
}
.toolbar {
display: flex;
align-items: center;
gap: var(--spacing-4);
height: 44px;
padding: 0 var(--spacing-4) 0 var(--spacing-6);
border-bottom: 1px solid var(--l2-border);
}
.views {
// The trace views paint their own surfaces in --l1-background; the drawer is --l2.
--l1-background: var(--l2-background);
}
.banner {
padding-top: var(--spacing-6);
}
.spacer {
flex: 1;
}
.viewLoader {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: var(--l2-foreground);
}

View File

@@ -0,0 +1,110 @@
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { ChartNoAxesGantt, Flame } from '@signozhq/icons';
import type { UseTraceWaterfallDataResult } from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import TraceStoreSync from 'pages/TraceDetailsV3/stores/TraceStoreSync';
import TraceCounts from 'pages/TraceDetailsV3/TraceCounts/TraceCounts';
import MissingSpansBanner from 'pages/TraceDetailsV3/TraceDetailsHeader/MissingSpansBanner';
import { ResizableBox } from 'periscope/components/ResizableBox';
import { FLAMEGRAPH_UNAVAILABLE_TOOLTIP, TRACE_PANE_HEIGHT } from './constants';
import DrawerFlamegraph from './DrawerFlamegraph';
import DrawerWaterfall from './DrawerWaterfall';
import TraceViewLoader from './TraceViewLoader';
import type { UseDrawerTraceViewResult } from './useDrawerTraceView';
import styles from './SpanDrawerTracePane.module.scss';
type SpanDrawerTracePaneProps = {
traceId: string;
traceView: UseDrawerTraceViewResult;
waterfall: UseTraceWaterfallDataResult;
totalSpansCount: number | undefined;
totalErrorSpansCount: number | undefined;
hasMissingSpans: boolean;
};
/** One trace view above the span details, each scrolling on its own. */
function SpanDrawerTracePane({
traceId,
traceView,
waterfall,
totalSpansCount,
totalErrorSpansCount,
hasMissingSpans,
}: SpanDrawerTracePaneProps): JSX.Element {
const { view, setView, isPending, areTabsShown, hasFlamegraph } = traceView;
// Keyed by trace: the views keep the last trace's data while the next loads.
let content = <TraceViewLoader />;
if (!isPending) {
content =
view === 'waterfall' ? (
<DrawerWaterfall key={traceId} traceId={traceId} waterfall={waterfall} />
) : (
<DrawerFlamegraph
key={traceId}
traceId={traceId}
totalSpansCount={totalSpansCount}
/>
);
}
return (
<TraceStoreSync>
<div className={styles.pane} data-testid="span-drawer-trace-pane">
<div className={styles.toolbar}>
{areTabsShown && (
<ToggleGroup
variant="outlined"
color="secondary"
type="single"
size="sm"
value={view}
onChange={(next: string): void => {
if (next === 'flamegraph' || next === 'waterfall') {
setView(next);
}
}}
testId="span-drawer-trace-view"
items={[
{
value: 'flamegraph',
label: 'Flame Graph',
prefix: <Flame size={12} />,
disabled: !hasFlamegraph,
disabledTooltip: FLAMEGRAPH_UNAVAILABLE_TOOLTIP,
},
{
value: 'waterfall',
label: 'Waterfall',
prefix: <ChartNoAxesGantt size={12} />,
},
]}
/>
)}
<span className={styles.spacer} />
<TraceCounts
totalSpansCount={totalSpansCount}
totalErrorSpansCount={totalErrorSpansCount}
/>
</div>
{hasMissingSpans && (
<div className={styles.banner}>
{/* A dismissal holds for this trace only. */}
<MissingSpansBanner key={traceId} />
</div>
)}
<ResizableBox
className={styles.views}
defaultHeight={TRACE_PANE_HEIGHT.default}
minHeight={TRACE_PANE_HEIGHT.min}
maxHeight={TRACE_PANE_HEIGHT.max}
>
{content}
</ResizableBox>
</div>
</TraceStoreSync>
);
}
export default SpanDrawerTracePane;

View File

@@ -0,0 +1,21 @@
import { Spinner } from '@signozhq/ui/spinner';
import styles from './SpanDrawerTracePane.module.scss';
/** Holds a trace view's place from the span count until the view has its data. */
function TraceViewLoader(): JSX.Element {
return (
<output
className={styles.viewLoader}
aria-label="Loading trace"
data-testid="span-drawer-trace-loading"
>
<Spinner size={20} />
</output>
);
}
/** One element, so the views' memoised content doesn't rebuild on each render. */
export const TRACE_VIEW_LOADER = <TraceViewLoader />;
export default TraceViewLoader;

View File

@@ -0,0 +1,82 @@
import { ReactNode } from 'react';
import { initialQueriesMap } from 'constants/queryBuilder';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { AllTheProviders, renderHook } from 'tests/test-utils';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { useCloseSpanDrawerOnQueryChange } from '../useCloseSpanDrawerOnQueryChange';
import { useSpanDrawerParams } from '../useSpanDrawerParams';
type HarnessProps = { view: ExplorerViews; queryId: string | null };
const stagedQueryOf = (queryId: string | null): Query | null =>
queryId ? { ...initialQueriesMap.traces, id: queryId } : null;
const renderDrawer = (initialProps: HarnessProps) => {
let queryId = initialProps.queryId;
const utils = renderHook(
({ view }: HarnessProps) => {
useCloseSpanDrawerOnQueryChange(view);
return useSpanDrawerParams()[0];
},
{
initialProps,
wrapper: function Wrapper({ children }: { children: ReactNode }) {
return (
<AllTheProviders
initialRoute="/?traceId=trace-1&spanId=span-a"
queryBuilderOverrides={{ stagedQuery: stagedQueryOf(queryId) }}
>
{children}
</AllTheProviders>
);
},
},
);
return {
...utils,
rerender: (props: HarnessProps): void => {
queryId = props.queryId;
utils.rerender(props);
},
};
};
const OPEN = { traceId: 'trace-1', spanId: 'span-a' };
const CLOSED = { traceId: null, spanId: null };
describe('useCloseSpanDrawerOnQueryChange', () => {
it('closes the drawer on a new query', () => {
const { result, rerender } = renderDrawer({
view: ExplorerViews.LIST,
queryId: 'query-1',
});
rerender({ view: ExplorerViews.LIST, queryId: 'query-2' });
expect(result.current).toStrictEqual(CLOSED);
});
it('closes the drawer on another view, where the list is not mounted', () => {
const { result, rerender } = renderDrawer({
view: ExplorerViews.LIST,
queryId: 'query-1',
});
rerender({ view: ExplorerViews.TIMESERIES, queryId: 'query-1' });
expect(result.current).toStrictEqual(CLOSED);
});
it('keeps a linked drawer open while the staged query resets and loads', () => {
const { result, rerender } = renderDrawer({
view: ExplorerViews.LIST,
queryId: 'previous-page-query',
});
rerender({ view: ExplorerViews.LIST, queryId: null });
rerender({ view: ExplorerViews.LIST, queryId: 'query-1' });
expect(result.current).toStrictEqual(OPEN);
});
});

View File

@@ -0,0 +1,233 @@
import { ReactNode } from 'react';
import type {
GetWaterfallV4200,
SpantypesWaterfallSpanDTO,
} from 'api/generated/services/sigNoz.schemas';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { rest, server } from 'mocks-server/server';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import { AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
import { useDrawerSpan } from '../useDrawerSpan';
const span = (
spanId: string,
parentSpanId: string,
): SpantypesWaterfallSpanDTO => ({
span_id: spanId,
parent_span_id: parentSpanId,
trace_id: 'trace-1',
level: parentSpanId ? 1 : 0,
has_children: !parentSpanId,
name: spanId,
time_unix: 1_700_000_000_000,
duration_nano: 1_000_000,
references: [],
});
const listRow: TracesTableRow = {
id: 'row-a',
trace_id: 'trace-1',
span_id: 'span-a',
name: 'span-a',
timestamp: '2026-11-19T13:28:21.309Z',
};
let requestedTraceIds: string[];
let totalSpansCount: number;
beforeEach(() => {
requestedTraceIds = [];
totalSpansCount = 2;
server.use(
rest.post('*/api/v4/traces/:traceId/waterfall', (req, res, ctx) => {
const traceId = String(req.params.traceId);
requestedTraceIds.push(traceId);
if (traceId === 'failing-trace') {
return res(ctx.status(500), ctx.json({ status: 'error' }));
}
if (traceId !== 'trace-1') {
return res(ctx.status(404), ctx.json({ status: 'error' }));
}
const body: GetWaterfallV4200 = {
status: 'success',
data: {
spans: [span('root', ''), span('child', 'root')],
totalSpansCount,
uncollapsedSpans: [],
startTimestampMillis: 0,
endTimestampMillis: 1,
},
};
return res(ctx.delay(20), ctx.status(200), ctx.json(body));
}),
);
});
type HarnessProps = {
traceId: string;
row: TracesTableRow | null;
isListLoading?: boolean;
isWaterfallShown?: boolean;
isSummaryNotFound?: boolean;
};
const renderDrawerSpan = (initialProps: HarnessProps, spanId: string) =>
renderHook(
({
traceId,
row,
isListLoading = false,
isWaterfallShown = false,
isSummaryNotFound = false,
}: HarnessProps) => {
const [urlSpanId] = useSelectedSpanId();
return {
urlSpanId,
...useDrawerSpan({
traceId,
spanId: urlSpanId,
row,
isListLoading,
isWaterfallShown,
isSummaryNotFound,
}),
};
},
{
initialProps,
wrapper: function Wrapper({ children }: { children: ReactNode }) {
return (
<AllTheProviders initialRoute={`/?spanId=${spanId}`}>
{children}
</AllTheProviders>
);
},
},
);
describe('useDrawerSpan', () => {
it('shows a list row without fetching the trace', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: listRow },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.isFetchingTraceData).toBe(false),
);
expect(result.current.span?.span_id).toBe('span-a');
expect(requestedTraceIds).toStrictEqual([]);
});
it('waits for the list before fetching the trace', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null, isListLoading: true },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.isFetchingTraceData).toBe(false),
);
expect(requestedTraceIds).toStrictEqual([]);
});
it('fetches the trace for a list row while the waterfall shows', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: listRow, isWaterfallShown: true },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.allSpans).toHaveLength(2),
);
expect(requestedTraceIds).toStrictEqual(['trace-1']);
expect(result.current.span?.span_id).toBe('span-a');
});
it('shows a span outside the list from the trace', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null },
'child',
);
await waitFor(() => expect(result.current.span?.span_id).toBe('child'));
expect(result.current.isStale).toBe(false);
});
it('keeps the last span dimmed while the next one loads', () => {
const { result, rerender } = renderDrawerSpan(
{ traceId: 'trace-1', row: listRow },
'span-a',
);
rerender({ traceId: 'trace-1', row: null });
expect(result.current.span?.span_id).toBe('span-a');
expect(result.current.isStale).toBe(true);
});
it('falls back to the root span when the trace has no such span', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null },
'no-such-span',
);
await waitFor(() => expect(result.current.urlSpanId).toBe('root'));
expect(result.current.span?.span_id).toBe('root');
});
it('falls back to the root span of a windowed trace', async () => {
totalSpansCount = 500;
const { result } = renderDrawerSpan(
{ traceId: 'trace-1', row: null },
'no-such-span',
);
await waitFor(() => expect(result.current.urlSpanId).toBe('root'));
expect(result.current.span?.span_id).toBe('root');
});
it('reports a trace that does not exist', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'no-such-trace', row: null },
'span-a',
);
await waitFor(() => expect(result.current.isTraceMissing).toBe(true));
expect(result.current.span).toBeUndefined();
});
it('keeps a trace whose request fails for another reason', async () => {
const { result } = renderDrawerSpan(
{ traceId: 'failing-trace', row: null },
'span-a',
);
await waitFor(() =>
expect(result.current.waterfall.errorFetchingTraceData).toBeTruthy(),
);
expect(result.current.isTraceMissing).toBe(false);
});
it('reports a trace without a summary as missing once the list settles, without fetching it', async () => {
const { result, rerender } = renderDrawerSpan(
{
traceId: 'trace-1',
row: null,
isListLoading: true,
isSummaryNotFound: true,
},
'span-a',
);
expect(result.current.isTraceMissing).toBe(false);
rerender({ traceId: 'trace-1', row: null, isSummaryNotFound: true });
expect(result.current.isTraceMissing).toBe(true);
await waitFor(() =>
expect(result.current.waterfall.isFetchingTraceData).toBe(false),
);
expect(requestedTraceIds).toStrictEqual([]);
});
});

View File

@@ -0,0 +1,116 @@
import { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
import { act, renderHook } from 'tests/test-utils';
import { useDrawerTraceView } from '../useDrawerTraceView';
type Props = Parameters<typeof useDrawerTraceView>[0];
const SMALL_TRACE: Props = {
traceId: 'trace-1',
totalSpansCount: 10,
isSummaryLoading: false,
};
const BIG_TRACE: Props = {
traceId: 'trace-big',
totalSpansCount: FLAMEGRAPH_SPAN_LIMIT + 1,
isSummaryLoading: false,
};
const LOADING_TRACE: Props = {
traceId: 'trace-2',
totalSpansCount: undefined,
isSummaryLoading: true,
};
const renderTraceView = (initialProps: Props) =>
renderHook((props: Props) => useDrawerTraceView(props), { initialProps });
describe('useDrawerTraceView', () => {
it('opens on the flame graph', () => {
const { result } = renderTraceView(SMALL_TRACE);
expect(result.current).toMatchObject({
view: 'flamegraph',
hasFlamegraph: true,
isWaterfallShown: false,
});
});
it('shows the waterfall above the flame graph limit', () => {
const { result } = renderTraceView(BIG_TRACE);
expect(result.current).toMatchObject({
view: 'waterfall',
hasFlamegraph: false,
isWaterfallShown: true,
});
});
it('keeps the flame graph at the limit', () => {
const { result } = renderTraceView({
...BIG_TRACE,
totalSpansCount: FLAMEGRAPH_SPAN_LIMIT,
});
expect(result.current).toMatchObject({
view: 'flamegraph',
hasFlamegraph: true,
});
});
it('offers the flame graph when the span count fails to load', () => {
const { result } = renderTraceView({
...LOADING_TRACE,
isSummaryLoading: false,
});
expect(result.current).toMatchObject({
view: 'flamegraph',
isPending: false,
areTabsShown: true,
hasFlamegraph: true,
});
});
it('hides the tabs once the drawer closes', () => {
const { result, rerender } = renderTraceView(BIG_TRACE);
rerender({ ...BIG_TRACE, traceId: null });
expect(result.current).toMatchObject({
isPending: false,
areTabsShown: false,
hasFlamegraph: true,
});
});
it('mounts no view until the span count loads', () => {
const { result } = renderTraceView(LOADING_TRACE);
expect(result.current).toMatchObject({
isPending: true,
areTabsShown: false,
isWaterfallShown: false,
});
});
it("keeps the last trace's tabs while the next span count loads", () => {
const { result, rerender } = renderTraceView(BIG_TRACE);
rerender(LOADING_TRACE);
expect(result.current).toMatchObject({
isPending: true,
areTabsShown: true,
hasFlamegraph: false,
});
});
it('keeps the chosen tab on the next trace', () => {
const { result, rerender } = renderTraceView(SMALL_TRACE);
act(() => result.current.setView('waterfall'));
rerender({ ...SMALL_TRACE, traceId: 'trace-3' });
expect(result.current.view).toBe('waterfall');
});
});

View File

@@ -1,44 +0,0 @@
import { act, renderHook } from 'tests/test-utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { useSpanDrawer } from '../useSpanDrawer';
let mockQueryId = 'query-1';
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): unknown => ({ stagedQuery: { id: mockQueryId } }),
}));
const rows: TracesTableRow[] = [{ id: 'span-a' }, { id: 'span-b' }];
describe('useSpanDrawer', () => {
beforeEach(() => {
mockQueryId = 'query-1';
});
it('does not reopen a span that a refetch dropped and a later one brings back', () => {
const { result, rerender } = renderHook(
({ current }: { current: TracesTableRow[] }) => useSpanDrawer(current),
{ initialProps: { current: rows } },
);
act(() => result.current.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawerProps?.row).toBe(rows[1]);
rerender({ current: [rows[0]] });
expect(result.current.drawerProps?.row).toBeNull();
rerender({ current: rows });
expect(result.current.drawerProps?.row).toBeNull();
});
it('closes on a new query while the old rows are still shown', () => {
const { result, rerender } = renderHook(() => useSpanDrawer(rows));
act(() => result.current.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawerProps?.row).toBe(rows[1]);
mockQueryId = 'query-2';
rerender();
expect(result.current.drawerProps?.row).toBeNull();
});
});

View File

@@ -0,0 +1,96 @@
import { ReactNode } from 'react';
import { act, AllTheProviders, renderHook } from 'tests/test-utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import { useSpanDrawer } from '../useSpanDrawer';
const rows: TracesTableRow[] = [
{ id: 'row-a', trace_id: 'trace-1', span_id: 'span-a' },
{ id: 'row-b', trace_id: 'trace-1', span_id: 'span-b' },
];
const renderSpanDrawer = (initialRows: TracesTableRow[], initialRoute = '/') =>
renderHook(
({ current }: { current: TracesTableRow[] }) => ({
drawer: useSpanDrawer(current, false),
setSpanId: useSelectedSpanId()[1],
}),
{
initialProps: { current: initialRows },
wrapper: function Wrapper({ children }: { children: ReactNode }) {
return (
<AllTheProviders initialRoute={initialRoute}>{children}</AllTheProviders>
);
},
},
);
describe('useSpanDrawer', () => {
it('opens the span the url names, with ↑/↓ from its row', () => {
const { result } = renderSpanDrawer(rows, '/?traceId=trace-1&spanId=span-b');
expect(result.current.drawer.drawerProps.row).toBe(rows[1]);
expect(result.current.drawer.tableProps.activeRowIndex).toBe(1);
act(() => result.current.drawer.drawerProps.navigation?.goToPrev());
expect(result.current.drawer.drawerProps.spanId).toBe('span-a');
});
it('keeps a span open after its row leaves the list, without ↑/↓', () => {
const { result, rerender } = renderSpanDrawer(rows);
act(() => result.current.drawer.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawer.drawerProps.navigation).not.toBeNull();
rerender({ current: [rows[0]] });
expect(result.current.drawer.drawerProps).toMatchObject({
traceId: 'trace-1',
spanId: 'span-b',
row: null,
navigation: null,
});
});
it('keeps ↑/↓ on the last list row while the url names a span outside the list', () => {
const { result } = renderSpanDrawer(rows);
act(() => result.current.drawer.tableProps.onRowClick?.(rows[0]));
act(() => result.current.setSpanId('span-b'));
act(() => result.current.setSpanId('span-outside'));
expect(result.current.drawer.drawerProps.row).toBeNull();
expect(result.current.drawer.tableProps.activeRowIndex).toBe(1);
act(() => result.current.drawer.drawerProps.navigation?.goToPrev());
expect(result.current.drawer.drawerProps.spanId).toBe('span-a');
});
it('steps past a span stored twice', () => {
const withDuplicate: TracesTableRow[] = [
{ id: 'row-a', trace_id: 'trace-1', span_id: 'span-a' },
{ id: 'row-a-copy', trace_id: 'trace-1', span_id: 'span-a' },
{ id: 'row-b', trace_id: 'trace-1', span_id: 'span-b' },
];
const { result } = renderSpanDrawer(withDuplicate);
act(() => result.current.drawer.tableProps.onRowClick?.(withDuplicate[0]));
act(() => result.current.drawer.drawerProps.navigation?.goToNext());
expect(result.current.drawer.tableProps.activeRowIndex).toBe(1);
act(() => result.current.drawer.drawerProps.navigation?.goToNext());
expect(result.current.drawer.drawerProps.spanId).toBe('span-b');
});
it('forgets the ↑/↓ row once the url closes the drawer', () => {
const { result } = renderSpanDrawer(rows);
act(() => result.current.drawer.tableProps.onRowClick?.(rows[1]));
act(() => result.current.setSpanId(null));
act(() => result.current.setSpanId('span-outside'));
expect(result.current.drawer.drawerProps.spanId).toBe('span-outside');
expect(result.current.drawer.tableProps.activeRowIndex).toBe(-1);
expect(result.current.drawer.drawerProps.navigation).toBeNull();
});
});

View File

@@ -0,0 +1,9 @@
import { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
export const FLAMEGRAPH_UNAVAILABLE_TOOLTIP = `Flame graph is not available for traces over ${Math.floor(FLAMEGRAPH_SPAN_LIMIT / 1000)}k spans`;
/** Pixels; the pane resizes between `min` and `max`. */
export const TRACE_PANE_HEIGHT = { default: 320, min: 120, max: 640 };
/** The drawer's trace views have no span filter. */
export const NO_FILTERED_SPANS: string[] = [];

View File

@@ -0,0 +1,28 @@
import { useEffect, useRef } from 'react';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
import { useSpanDrawerParams } from './useSpanDrawerParams';
/**
* Closes the span drawer when the query or the explorer view changes. It runs at
* page level because the list that hosts the drawer unmounts on another view.
*/
export function useCloseSpanDrawerOnQueryChange(view: ExplorerViews): void {
const [{ traceId, spanId }, setSpanDrawerParams] = useSpanDrawerParams();
const isOpen = !!traceId || !!spanId;
const { stagedQuery } = useQueryBuilder();
const queryId = stagedQuery?.id;
const lastRef = useRef({ queryId, view });
useEffect(() => {
const last = lastRef.current;
// The provider clears the staged query on a route change, so only one query id
// replacing another is a new query.
const isNewQuery = !!last.queryId && !!queryId && last.queryId !== queryId;
if (isOpen && (isNewQuery || last.view !== view)) {
void setSpanDrawerParams({ traceId: null, spanId: null });
}
lastRef.current = { queryId, view };
}, [queryId, view, isOpen, setSpanDrawerParams]);
}

View File

@@ -0,0 +1,113 @@
import { useEffect, useMemo } from 'react';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { StatusCodes } from 'http-status-codes';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import {
useTraceWaterfallData,
UseTraceWaterfallDataResult,
} from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { useLastShownSpan } from './useLastShownSpan';
import { toSpanV3 } from './utils';
type UseDrawerSpanParams = {
traceId: string | null;
spanId: string | null;
/** The list row of the open span, when it is loaded. */
row: TracesTableRow | null;
/** The list's first load; until it settles a missing `row` is not final. */
isListLoading: boolean;
isWaterfallShown: boolean;
/** The trace views read the same summary, so they 404 too. */
isSummaryNotFound: boolean;
};
type UseDrawerSpanResult = {
span: SpanV3 | undefined;
/** `span` is the previously shown one; the requested span is still loading. */
isStale: boolean;
isTraceMissing: boolean;
/** Fetched while shown, or for a span that is not a list row. */
waterfall: UseTraceWaterfallDataResult;
};
/**
* Picks the span to show: the waterfall's copy, else the list row's, else the
* last span shown until the requested one loads. A span id the trace doesn't
* have falls back to the trace's root span.
*/
export function useDrawerSpan({
traceId,
spanId,
row,
isListLoading,
isWaterfallShown,
isSummaryNotFound,
}: UseDrawerSpanParams): UseDrawerSpanResult {
const isOpen = !!traceId && !!spanId;
const isOutsideList = !row && !isListLoading;
const isWaterfallNeeded =
isOpen && !isSummaryNotFound && (isWaterfallShown || isOutsideList);
const waterfall = useTraceWaterfallData(traceId ?? '', {
enabled: isWaterfallNeeded,
});
const {
traceData,
allSpans,
isFetchingTraceData,
isPreviousData,
errorFetchingTraceData,
isFullDataLoaded,
interestedSpanId,
} = waterfall;
const [, setSpanId] = useSelectedSpanId();
const loadedSpan = useMemo(
() => allSpans.find((s) => s.span_id === spanId),
[allSpans, spanId],
);
const rowSpan = useMemo(() => (row ? toSpanV3(row) : undefined), [row]);
const currentSpan = loadedSpan ?? rowSpan;
const isSettled = isWaterfallNeeded && !isFetchingTraceData && !isPreviousData;
// Other errors keep the pane, whose views show their own error state.
const isTraceMissing = isSummaryNotFound
? isOutsideList
: isSettled &&
(errorFetchingTraceData?.response?.status === StatusCodes.NOT_FOUND ||
(!!traceData && allSpans.length === 0));
// A windowed response centres on the span it was asked for, so it is final
// only once that request has returned.
const rootSpanId =
isSettled &&
!currentSpan &&
allSpans.length > 0 &&
(isFullDataLoaded || interestedSpanId.spanId === spanId)
? allSpans[0].span_id
: null;
useEffect(() => {
if (rootSpanId) {
setSpanId(rootSpanId);
}
}, [rootSpanId, setSpanId]);
const lastShownSpan = useLastShownSpan(currentSpan, isOpen);
if (currentSpan) {
return {
span: currentSpan,
isStale: false,
isTraceMissing: false,
waterfall,
};
}
const isStale = !isTraceMissing && isOpen && !!lastShownSpan;
return {
span: isStale ? lastShownSpan : undefined,
isStale,
isTraceMissing,
waterfall,
};
}

View File

@@ -0,0 +1,60 @@
import { useState } from 'react';
import { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
export type TraceView = 'flamegraph' | 'waterfall';
type UseDrawerTraceViewParams = {
traceId: string | null;
/** Undefined until the open trace's summary has loaded. */
totalSpansCount: number | undefined;
isSummaryLoading: boolean;
};
export type UseDrawerTraceViewResult = {
/** The view on screen; the waterfall when the flame graph is unavailable. */
view: TraceView;
setView: (view: TraceView) => void;
/** The span count hasn't loaded, so no view is mounted yet. */
isPending: boolean;
/** False until a span count has loaded since the drawer opened. */
areTabsShown: boolean;
/** False above the flame graph limit. */
hasFlamegraph: boolean;
isWaterfallShown: boolean;
};
/** The trace view the drawer shows: Flame Graph first, one view at a time. */
export function useDrawerTraceView({
traceId,
totalSpansCount,
isSummaryLoading,
}: UseDrawerTraceViewParams): UseDrawerTraceViewResult {
const [chosenView, setView] = useState<TraceView>('flamegraph');
const loadedHasFlamegraph = isSummaryLoading
? undefined
: (totalSpansCount ?? 0) <= FLAMEGRAPH_SPAN_LIMIT;
// Moving to another trace keeps the last trace's tabs until its count loads.
const [heldHasFlamegraph, setHeldHasFlamegraph] =
useState(loadedHasFlamegraph);
const tabsHasFlamegraph = traceId
? (loadedHasFlamegraph ?? heldHasFlamegraph)
: undefined;
if (tabsHasFlamegraph !== heldHasFlamegraph) {
setHeldHasFlamegraph(tabsHasFlamegraph);
}
const isPending = !!traceId && loadedHasFlamegraph === undefined;
const hasFlamegraph = tabsHasFlamegraph ?? true;
const view: TraceView = hasFlamegraph ? chosenView : 'waterfall';
return {
view,
setView,
isPending,
areTabsShown: tabsHasFlamegraph !== undefined,
hasFlamegraph,
isWaterfallShown: !isPending && view === 'waterfall',
};
}

View File

@@ -0,0 +1,16 @@
import { useState } from 'react';
import { SpanV3 } from 'types/api/trace/getTraceV3';
/** The span shown last while the drawer is open, held until the next one loads. */
export function useLastShownSpan(
currentSpan: SpanV3 | undefined,
isOpen: boolean,
): SpanV3 | undefined {
const [lastShownSpan, setLastShownSpan] = useState<SpanV3>();
if (currentSpan && currentSpan !== lastShownSpan) {
setLastShownSpan(currentSpan);
} else if (!isOpen && lastShownSpan) {
setLastShownSpan(undefined);
}
return lastShownSpan;
}

View File

@@ -1,22 +1,21 @@
import {
PointerEvent,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { PointerEvent, useCallback, useMemo, useState } from 'react';
import type { TableColumnDef } from 'components/TanStackTableView/types';
import { useRowNavigation } from 'components/TanStackTableView/useRowNavigation';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import type { TracesTableProps } from 'container/TracesExplorer/TracesTable/TracesTable';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useCloseOnOutsidePress } from 'hooks/useCloseOnOutsidePress';
import { OPEN_TRACE_COLUMN } from './openTraceColumn';
import type { SpanDrawerProps } from './SpanDrawer';
import { useSpanDrawerParams } from './useSpanDrawerParams';
import { findSpanRow } from './utils';
type ActiveSpan = { id: string; index: number };
/**
* The highlighted row that ↑/↓ step from: the last row opened from the list. It
* stays while the drawer shows a span outside the list. The index tells
* duplicate rows apart.
*/
type Anchor = { traceId: string; spanId: string; index: number };
type UseSpanDrawerResult = {
tableProps: Pick<
@@ -30,78 +29,95 @@ type UseSpanDrawerResult = {
onPressInside: (event: PointerEvent) => void;
};
export function useSpanDrawer(rows: TracesTableRow[]): UseSpanDrawerResult {
// The index lets navigation step past a duplicate span; the id survives a refetch.
const [activeSpan, setActiveSpan] = useState<ActiveSpan | null>(null);
const toAnchor = (row: TracesTableRow, index: number): Anchor => ({
traceId: String(row.trace_id),
spanId: String(row.span_id),
index,
});
const activeRowIndex = useMemo(() => {
if (!activeSpan) {
export function useSpanDrawer(
rows: TracesTableRow[],
isListLoading: boolean,
): UseSpanDrawerResult {
const [{ traceId, spanId }, setSpanDrawerParams] = useSpanDrawerParams();
const isOpen = !!traceId && !!spanId;
const [anchor, setAnchor] = useState<Anchor | null>(null);
// The url can close the drawer too (Back, a new query).
if (!isOpen && anchor) {
setAnchor(null);
}
const anchorRowIndex = useMemo(
() => (anchor ? findSpanRow(rows, anchor, anchor.index) : -1),
[rows, anchor],
);
const openRowIndex = useMemo(() => {
if (!traceId || !spanId) {
return -1;
}
return rows[activeSpan.index]?.id === activeSpan.id
? activeSpan.index
: rows.findIndex((row) => row.id === activeSpan.id);
}, [rows, activeSpan]);
if (anchor?.traceId === traceId && anchor.spanId === spanId) {
return anchorRowIndex;
}
return findSpanRow(rows, { traceId, spanId });
}, [rows, traceId, spanId, anchor, anchorRowIndex]);
// A span opened from the url (a link, a refresh) anchors ↑/↓ once its row loads.
if (openRowIndex !== -1 && openRowIndex !== anchorRowIndex) {
setAnchor(toAnchor(rows[openRowIndex], openRowIndex));
}
let activeRowIndex = -1;
if (isOpen) {
activeRowIndex = openRowIndex === -1 ? anchorRowIndex : openRowIndex;
}
const isRowActive = useCallback(
(row: TracesTableRow): boolean => row === rows[activeRowIndex],
[rows, activeRowIndex],
);
const handleNavigate = useCallback(
const openSpan = useCallback(
(row: TracesTableRow, index: number): void => {
setActiveSpan({ id: row.id, index });
const next = toAnchor(row, index);
setAnchor(next);
void setSpanDrawerParams({ traceId: next.traceId, spanId: next.spanId });
},
[],
[setSpanDrawerParams],
);
const selectRow = useCallback(
(row: TracesTableRow): void => handleNavigate(row, rows.indexOf(row)),
[handleNavigate, rows],
const openRow = useCallback(
(row: TracesTableRow): void => openSpan(row, rows.indexOf(row)),
[openSpan, rows],
);
const clearActiveSpan = useCallback((): void => setActiveSpan(null), []);
const closeDrawer = useCallback((): void => {
setAnchor(null);
void setSpanDrawerParams({ traceId: null, spanId: null });
}, [setSpanDrawerParams]);
// A refetch can drop the open span; forget it so a later page can't reopen it.
useEffect(() => {
if (activeSpan && activeRowIndex === -1) {
setActiveSpan(null);
}
}, [activeSpan, activeRowIndex]);
// A new query closes the drawer at once instead of waiting for its rows.
const { stagedQuery } = useQueryBuilder();
const queryId = stagedQuery?.id;
const lastQueryIdRef = useRef(queryId);
useEffect(() => {
if (lastQueryIdRef.current && lastQueryIdRef.current !== queryId) {
setActiveSpan(null);
}
lastQueryIdRef.current = queryId;
}, [queryId]);
const onPressInside = useCloseOnOutsidePress(
activeRowIndex !== -1,
clearActiveSpan,
);
const onPressInside = useCloseOnOutsidePress(isOpen, closeDrawer);
const navigation = useRowNavigation({
rows,
activeIndex: activeRowIndex,
onNavigate: handleNavigate,
onNavigate: openSpan,
});
return {
tableProps: {
onRowClick: selectRow,
onRowClick: openRow,
isRowActive,
activeRowIndex,
},
openTraceColumn: OPEN_TRACE_COLUMN,
drawerProps: {
row: rows[activeRowIndex] ?? null,
onClose: clearActiveSpan,
navigation,
traceId: isOpen ? traceId : null,
spanId: isOpen ? spanId : null,
row: rows[openRowIndex] ?? null,
onClose: closeDrawer,
navigation: activeRowIndex === -1 ? null : navigation,
isListLoading,
},
onPressInside,
};

View File

@@ -0,0 +1,13 @@
import { parseAsString, useQueryStates, UseQueryStatesReturn } from 'nuqs';
import { SELECTED_SPAN_ID_PARAM } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
// `spanId` is shared with the trace views (useSelectedSpanId); same options.
const spanDrawerParams = {
traceId: parseAsString,
[SELECTED_SPAN_ID_PARAM]: parseAsString,
};
/** The url params of the span open in the drawer. */
export const useSpanDrawerParams = (): UseQueryStatesReturn<
typeof spanDrawerParams
> => useQueryStates(spanDrawerParams, { shallow: false });

View File

@@ -38,3 +38,14 @@ export const toSpanV3 = (row: TracesTableRow): SpanV3 => {
),
} as unknown as SpanV3;
};
/** Index of the row for this span; `hintIndex` wins when it is a copy of it. */
export const findSpanRow = (
rows: TracesTableRow[],
{ traceId, spanId }: { traceId: string; spanId: string },
hintIndex = -1,
): number => {
const isSpan = (row: TracesTableRow | undefined): boolean =>
row?.trace_id === traceId && row?.span_id === spanId;
return isSpan(rows[hintIndex]) ? hintIndex : rows.findIndex(isSpan);
};

View File

@@ -0,0 +1,115 @@
import {
getFlamegraph,
getGetTraceSummaryQueryKey,
} from 'api/generated/services/tracedetail';
import type {
GetFlamegraph200,
GetTraceSummary200,
} from 'api/generated/services/sigNoz.schemas';
import {
AllTheProviders,
queryClient,
renderHook,
waitFor,
} from 'tests/test-utils';
import useGetTraceFlamegraphV3 from '../useGetTraceFlamegraphV3';
jest.mock('api/generated/services/tracedetail', () => ({
__esModule: true,
getFlamegraph: jest.fn(),
getGetTraceSummaryQueryKey: jest.requireActual(
'api/generated/services/tracedetail',
).getGetTraceSummaryQueryKey,
}));
const mockGetFlamegraph = jest.mocked(getFlamegraph);
const flamegraphResponse: GetFlamegraph200 = {
status: 'success',
data: {
spans: [],
hasMore: false,
startTimestampMillis: 0,
endTimestampMillis: 0,
},
};
const summaryWithMissingSpans: GetTraceSummary200 = {
status: 'success',
data: {
hasMissingSpans: true,
rootServiceName: 'frontend',
rootServiceEntryPoint: 'GET /',
rootSpanStatusCode: 'Unset',
startTimestampMillis: 0,
endTimestampMillis: 0,
totalSpansCount: 1,
totalErrorSpansCount: 0,
},
};
const requestSignal = (call: number): AbortSignal | undefined =>
mockGetFlamegraph.mock.calls[call][2];
describe('useGetTraceFlamegraphV3', () => {
beforeEach(() => {
mockGetFlamegraph.mockReset();
});
it('cancels the request for the previous trace when the trace changes', async () => {
mockGetFlamegraph.mockReturnValue(new Promise(() => {}));
const { rerender } = renderHook(
({ traceId }) => useGetTraceFlamegraphV3({ traceId, enabled: true }),
{ wrapper: AllTheProviders, initialProps: { traceId: 't1' } },
);
await waitFor(() => expect(mockGetFlamegraph).toHaveBeenCalledTimes(1));
expect(requestSignal(0)?.aborted).toBe(false);
rerender({ traceId: 't2' });
await waitFor(() => expect(mockGetFlamegraph).toHaveBeenCalledTimes(2));
expect(requestSignal(0)?.aborted).toBe(true);
expect(requestSignal(1)?.aborted).toBe(false);
});
it('serves a reopened trace from the cache', async () => {
mockGetFlamegraph.mockResolvedValue(flamegraphResponse);
const wrapper = AllTheProviders;
const first = renderHook(
() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }),
{ wrapper },
);
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
const second = renderHook(
() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }),
{ wrapper },
);
expect(second.result.current.data).toStrictEqual(flamegraphResponse.data);
expect(mockGetFlamegraph).toHaveBeenCalledTimes(1);
});
it('refetches a reopened trace whose summary reports missing spans', async () => {
mockGetFlamegraph.mockResolvedValue(flamegraphResponse);
queryClient.setQueryData(
getGetTraceSummaryQueryKey({ traceID: 't1' }),
summaryWithMissingSpans,
);
const wrapper = AllTheProviders;
const first = renderHook(
() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }),
{ wrapper },
);
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
renderHook(() => useGetTraceFlamegraphV3({ traceId: 't1', enabled: true }), {
wrapper,
});
await waitFor(() => expect(mockGetFlamegraph).toHaveBeenCalledTimes(2));
});
});

View File

@@ -0,0 +1,157 @@
import {
getGetTraceSummaryQueryKey,
getWaterfallV4,
} from 'api/generated/services/tracedetail';
import type {
GetTraceSummary200,
GetWaterfallV4200,
SpantypesWaterfallSpanDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
AllTheProviders,
queryClient,
renderHook,
waitFor,
} from 'tests/test-utils';
import { GetTraceV4PayloadProps } from 'types/api/trace/getTraceV3';
import useGetTraceV4 from '../useGetTraceV4';
jest.mock('api/generated/services/tracedetail', () => ({
__esModule: true,
getWaterfallV4: jest.fn(),
getGetTraceSummaryQueryKey: jest.requireActual(
'api/generated/services/tracedetail',
).getGetTraceSummaryQueryKey,
}));
const mockGetWaterfallV4 = jest.mocked(getWaterfallV4);
const rootSpan: SpantypesWaterfallSpanDTO = {
span_id: 'root',
parent_span_id: '',
trace_id: 't1',
level: 0,
has_children: false,
name: 'root',
time_unix: 0,
duration_nano: 1,
references: [],
};
const waterfallResponse = (totalSpansCount: number): GetWaterfallV4200 => ({
status: 'success',
data: {
spans: [rootSpan],
totalSpansCount,
startTimestampMillis: 0,
endTimestampMillis: 0,
},
});
const payload = (traceId: string): GetTraceV4PayloadProps => ({
traceId,
selectedSpanId: '',
uncollapsedSpans: [],
isSelectedSpanIDUnCollapsed: false,
});
const summaryWithMissingSpans: GetTraceSummary200 = {
status: 'success',
data: {
hasMissingSpans: true,
rootServiceName: 'frontend',
rootServiceEntryPoint: 'GET /',
rootSpanStatusCode: 'Unset',
startTimestampMillis: 0,
endTimestampMillis: 0,
totalSpansCount: 1,
totalErrorSpansCount: 0,
},
};
const requestSignal = (call: number): AbortSignal | undefined =>
mockGetWaterfallV4.mock.calls[call][2];
describe('useGetTraceV4', () => {
beforeEach(() => {
mockGetWaterfallV4.mockReset();
});
it('cancels the request for the previous trace when the trace changes', async () => {
mockGetWaterfallV4.mockReturnValue(new Promise(() => {}));
const { rerender } = renderHook(
({ traceId }) => useGetTraceV4(payload(traceId)),
{ wrapper: AllTheProviders, initialProps: { traceId: 't1' } },
);
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(1));
expect(requestSignal(0)?.aborted).toBe(false);
rerender({ traceId: 't2' });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
expect(requestSignal(0)?.aborted).toBe(true);
expect(requestSignal(1)?.aborted).toBe(false);
});
it('serves a reopened trace from the cache', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(1));
const wrapper = AllTheProviders;
const first = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
const second = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
expect(second.result.current.isSuccess).toBe(true);
expect(mockGetWaterfallV4).toHaveBeenCalledTimes(1);
});
it('refetches a reopened windowed trace', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(20_000));
const wrapper = AllTheProviders;
const first = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
});
it('refetches a reopened trace whose summary reports missing spans', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(1));
queryClient.setQueryData(
getGetTraceSummaryQueryKey({ traceID: 't1' }),
summaryWithMissingSpans,
);
const wrapper = AllTheProviders;
const first = renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(first.result.current.isSuccess).toBe(true));
first.unmount();
renderHook(() => useGetTraceV4(payload('t1')), { wrapper });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
});
it('refetches a trace with missing spans when switching back to it', async () => {
mockGetWaterfallV4.mockResolvedValue(waterfallResponse(1));
queryClient.setQueryData(
getGetTraceSummaryQueryKey({ traceID: 't1' }),
summaryWithMissingSpans,
);
const { result, rerender } = renderHook(
({ traceId }) => useGetTraceV4(payload(traceId)),
{ wrapper: AllTheProviders, initialProps: { traceId: 't1' } },
);
await waitFor(() => expect(result.current.isSuccess).toBe(true));
rerender({ traceId: 't2' });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(2));
rerender({ traceId: 't1' });
await waitFor(() => expect(mockGetWaterfallV4).toHaveBeenCalledTimes(3));
expect(mockGetWaterfallV4.mock.calls[2][0]).toStrictEqual({ traceID: 't1' });
});
});

View File

@@ -7,6 +7,8 @@ import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { useQuery, UseQueryResult } from 'react-query';
import { TelemetryFieldKey } from 'types/api/v5/queryRange';
import { useTraceQueryStaleTime } from './useTraceQueryStaleTime';
export interface GetTraceFlamegraphV3Props {
traceId: string;
selectedSpanId?: string;
@@ -16,9 +18,10 @@ export interface GetTraceFlamegraphV3Props {
const useGetTraceFlamegraphV3 = (
props: GetTraceFlamegraphV3Props,
): UseQueryResult<SpantypesGettableFlamegraphTraceDTO, unknown> =>
useQuery({
queryFn: () =>
): UseQueryResult<SpantypesGettableFlamegraphTraceDTO, unknown> => {
const staleTime = useTraceQueryStaleTime(props.traceId);
return useQuery({
queryFn: ({ signal }) =>
getFlamegraph(
{ traceID: props.traceId },
{
@@ -27,6 +30,7 @@ const useGetTraceFlamegraphV3 = (
// the literal-union vs enum nominal types differ
selectFields: props.selectFields as TelemetrytypesTelemetryFieldKeyDTO[],
},
signal,
).then((res) => res.data),
queryKey: [
REACT_QUERY_KEY.GET_TRACE_V3_FLAMEGRAPH,
@@ -37,6 +41,8 @@ const useGetTraceFlamegraphV3 = (
enabled: props.enabled,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime,
});
};
export default useGetTraceFlamegraphV3;

View File

@@ -1,4 +1,6 @@
import { useQuery, UseQueryResult } from 'react-query';
import { useQuery, useQueryClient, UseQueryResult } from 'react-query';
import type { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
import type { ErrorType } from 'api/generatedAPIInstance';
import getTraceV4 from 'api/trace/getTraceV4';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { ErrorResponse, SuccessResponse } from 'types/api';
@@ -7,23 +9,50 @@ import {
GetTraceV4SuccessResponse,
} from 'types/api/trace/getTraceV3';
const useGetTraceV4 = (props: GetTraceV4PayloadProps): UseTraceV4 =>
useQuery({
queryFn: () => getTraceV4(props),
queryKey: [
REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL,
props.traceId,
props.selectedSpanId,
props.isSelectedSpanIDUnCollapsed,
],
enabled: !!props.traceId,
import { useTraceQueryStaleTime } from './useTraceQueryStaleTime';
type UseGetTraceV4Options = {
/** Defaults to true; the query also needs a trace id. */
enabled?: boolean;
};
const useGetTraceV4 = (
props: GetTraceV4PayloadProps,
{ enabled = true }: UseGetTraceV4Options = {},
): UseTraceV4 => {
const traceStaleTime = useTraceQueryStaleTime(props.traceId);
const queryClient = useQueryClient();
const queryKey = [
REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL,
props.traceId,
props.selectedSpanId,
props.isSelectedSpanIDUnCollapsed,
];
// A windowed response depends on `uncollapsedSpans`, which the key leaves out: each
// response's list feeds the next request, so keying on it would fetch twice.
const isCachedTraceComplete = isCompleteTrace(
queryClient.getQueryData<UseTraceV4['data']>(queryKey),
);
return useQuery({
queryFn: ({ signal }) => getTraceV4(props, signal),
queryKey,
enabled: enabled && !!props.traceId,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: isCachedTraceComplete ? traceStaleTime : 0,
});
};
const isCompleteTrace = (data: UseTraceV4['data']): boolean => {
const totalSpansCount = data?.payload?.totalSpansCount ?? 0;
return (
totalSpansCount > 0 && totalSpansCount <= (data?.payload?.spans.length ?? 0)
);
};
type UseTraceV4 = UseQueryResult<
SuccessResponse<GetTraceV4SuccessResponse> | ErrorResponse,
unknown
ErrorType<RenderErrorResponseDTO>
>;
export default useGetTraceV4;

View File

@@ -0,0 +1,17 @@
import { useQueryClient } from 'react-query';
import type { GetTraceSummary200 } from 'api/generated/services/sigNoz.schemas';
import { getGetTraceSummaryQueryKey } from 'api/generated/services/tracedetail';
const TRACE_QUERY_STALE_TIME_MS = 5 * 60 * 1000;
/**
* A trace whose cached summary reports missing spans may still be ingesting,
* so its queries refetch on each open instead of serving the cache.
*/
export function useTraceQueryStaleTime(traceId: string): number {
const queryClient = useQueryClient();
const summary = queryClient.getQueryData<GetTraceSummary200>(
getGetTraceSummaryQueryKey({ traceID: traceId }),
);
return summary?.data?.hasMissingSpans ? 0 : TRACE_QUERY_STALE_TIME_MS;
}

View File

@@ -9,6 +9,20 @@
}
}
.drawerContent {
display: flex;
flex-direction: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
.stale {
opacity: 0.5;
pointer-events: none;
transition: opacity 0.15s ease-in;
}
.panelBody {
padding: 12px;
display: flex;

View File

@@ -1,5 +1,6 @@
import { useCallback, useMemo, useState } from 'react';
import { ReactNode, useCallback, useMemo, useState } from 'react';
import { Badge } from '@signozhq/ui/badge';
import { Skeleton as DrawerSkeleton } from '@signozhq/ui/skeleton';
import { Tabs, type TabsItemProps } from '@signozhq/ui/tabs';
import { Bookmark, ChartColumnBig, List, ScrollText } from '@signozhq/icons';
import { Skeleton } from 'antd';
@@ -66,6 +67,12 @@ interface SpanDetailsPanelProps {
traceEndTime?: number;
/** The trace bounds are still being fetched; logs wait for them. */
isTraceBoundsLoading?: boolean;
/** `selectedSpan` is the previous span, kept dimmed while the next one loads. */
isStale?: boolean;
/** Shown in place of the span when there is none to show. */
emptyState?: ReactNode;
/** Drawer only: shown above the span details, which scroll on their own. */
tracePane?: ReactNode;
}
// At/above this panel width the summary moves inside the Overview tab (bottom
@@ -436,6 +443,9 @@ function SpanDetailsPanel({
traceStartTime,
traceEndTime,
isTraceBoundsLoading,
isStale = false,
emptyState,
tracePane,
}: SpanDetailsPanelProps): JSX.Element {
const headerActions = useMemo((): HeaderAction[] => {
const actions: HeaderAction[] = [
@@ -483,7 +493,9 @@ function SpanDetailsPanel({
traceEndTime={traceEndTime}
isTraceBoundsLoading={isTraceBoundsLoading}
/>
) : null;
) : (
emptyState
);
const content = (
<>
@@ -521,10 +533,21 @@ function SpanDetailsPanel({
<HeaderActions actions={headerActions} />
) : undefined
}
loading={!selectedSpan}
// The trace pane loads on its own; only the span details wait.
loading={!spanContent && !tracePane}
testId="span-details-drawer"
width="entity"
>
<div className={cx(styles.panel, styles.drawerPanel)}>{spanContent}</div>
<div className={cx(styles.panel, styles.drawerPanel)}>
{tracePane}
<div className={cx(styles.drawerContent, { [styles.stale]: isStale })}>
{spanContent ?? (
<div className={styles.panelBody}>
<DrawerSkeleton testId="span-details-drawer-skeleton" />
</div>
)}
</div>
</div>
</DetailsPanelDrawer>
);
}

View File

@@ -147,6 +147,9 @@ export function SpanHoverCard({
side="right"
align="start"
handle={handle}
// Inside a drawer a popover portals into the drawer's transformed panel, which
// offsets a card placed against a row; the body keeps it next to the row.
container={document.body}
// The card is a preview; the pointer and the keyboard stay where they were.
initialFocus={false}
finalFocus={false}

View File

@@ -0,0 +1,16 @@
.counts {
display: flex;
gap: var(--spacing-6);
align-items: center;
color: var(--l2-foreground);
}
.countItem {
display: inline-flex;
align-items: center;
gap: var(--spacing-2);
}
.hasErrors {
color: var(--destructive);
}

View File

@@ -0,0 +1,58 @@
import { ChartNoAxesGantt, TriangleAlert } from '@signozhq/icons';
import { Typography } from '@signozhq/ui/typography';
import cx from 'classnames';
import styles from './TraceCounts.module.scss';
type TraceCountsProps = {
totalSpansCount: number | undefined;
totalErrorSpansCount: number | undefined;
};
/** The trace's span and error counts. */
function TraceCounts({
totalSpansCount,
totalErrorSpansCount,
}: TraceCountsProps): JSX.Element | null {
if (!totalSpansCount) {
return null;
}
return (
<span className={styles.counts} data-testid="trace-counts">
<span className={styles.countItem}>
<ChartNoAxesGantt size={13} />
<Typography
variant="paragraph"
size="small"
weight="regular"
color="inherit"
as="span"
textOverflow="visible"
>
Spans: {totalSpansCount}
</Typography>
</span>
<span
className={cx(styles.countItem, {
[styles.hasErrors]: (totalErrorSpansCount ?? 0) > 0,
})}
>
<TriangleAlert size={13} />
<Typography
variant="paragraph"
size="small"
weight="regular"
color="inherit"
as="span"
textOverflow="visible"
>
Errors:{' '}
{totalErrorSpansCount ?? <span className="translate-safe">{0}</span>}
</Typography>
</span>
</span>
);
}
export default TraceCounts;

View File

@@ -19,7 +19,11 @@ import { useTraceSummary } from '../useTraceSummary';
jest.mock('api/common/logEvent');
jest.mock('../useTraceSummary', () => ({
useTraceSummary: jest.fn(() => ({ data: undefined, isLoading: false })),
useTraceSummary: jest.fn(() => ({
data: undefined,
isLoading: false,
isNotFound: false,
})),
}));
const mockBack = jest.fn();
@@ -124,19 +128,19 @@ describe('TraceDetailsHeader – action cluster', () => {
beforeEach(() => {
jest
.mocked(useTraceSummary)
.mockReturnValue({ data: SUMMARY, isLoading: false });
.mockReturnValue({ data: SUMMARY, isLoading: false, isNotFound: false });
});
afterEach(() => {
jest
.mocked(useTraceSummary)
.mockReturnValue({ data: undefined, isLoading: false });
.mockReturnValue({ data: undefined, isLoading: false, isNotFound: false });
});
it('does not render the action buttons until the summary loads', () => {
jest
.mocked(useTraceSummary)
.mockReturnValue({ data: undefined, isLoading: true });
.mockReturnValue({ data: undefined, isLoading: true, isNotFound: false });
render(<TraceDetailsHeader {...baseProps} showTraceDetailsHeaderOptions />);
expect(
@@ -210,7 +214,9 @@ describe('TraceDetailsHeader – trace metadata row', () => {
};
const mockSummary = (data?: SpantypesGettableTraceSummaryDTO): void => {
jest.mocked(useTraceSummary).mockReturnValue({ data, isLoading: false });
jest
.mocked(useTraceSummary)
.mockReturnValue({ data, isLoading: false, isNotFound: false });
};
afterEach(() => {
@@ -345,13 +351,14 @@ describe('TraceDetailsHeader – tabs', () => {
hasMissingSpans: true,
},
isLoading: false,
isNotFound: false,
});
});
afterEach(() => {
jest
.mocked(useTraceSummary)
.mockReturnValue({ data: undefined, isLoading: false });
.mockReturnValue({ data: undefined, isLoading: false, isNotFound: false });
});
// In-memory URL state, so a tab switch can't leak into the next test.
@@ -416,6 +423,7 @@ describe('TraceDetailsHeader – tabs', () => {
},
},
isLoading: false,
isNotFound: false,
});
renderHeader();
expect(

View File

@@ -0,0 +1,64 @@
import type { GetTraceSummary200 } from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import {
AllTheProviders,
queryClient,
renderHook,
waitFor,
} from 'tests/test-utils';
import { useTraceSummary } from '../useTraceSummary';
const summaryResponse = (hasMissingSpans: boolean): GetTraceSummary200 => ({
status: 'success',
data: {
hasMissingSpans,
rootServiceName: 'frontend',
rootServiceEntryPoint: 'GET /',
rootSpanStatusCode: 'Unset',
startTimestampMillis: 0,
endTimestampMillis: 0,
totalSpansCount: 1,
totalErrorSpansCount: 0,
},
});
type OnRequest = jest.MockedFunction<() => void>;
const serveSummary = (hasMissingSpans: boolean): OnRequest => {
const onRequest = jest.fn() as OnRequest;
server.use(
rest.get('*/api/v1/traces/:traceId/summary', (_req, res, ctx) => {
onRequest();
return res(ctx.status(200), ctx.json(summaryResponse(hasMissingSpans)));
}),
);
return onRequest;
};
const openAndReopen = async (): Promise<void> => {
const wrapper = AllTheProviders;
const first = renderHook(() => useTraceSummary('t1'), { wrapper });
await waitFor(() => expect(first.result.current.data).toBeDefined());
first.unmount();
renderHook(() => useTraceSummary('t1'), { wrapper });
};
describe('useTraceSummary', () => {
it('serves a reopened trace from the cache', async () => {
const onRequest = serveSummary(false);
await openAndReopen();
expect(queryClient.isFetching()).toBe(0);
expect(onRequest).toHaveBeenCalledTimes(1);
});
it('refetches a reopened trace that has missing spans', async () => {
const onRequest = serveSummary(true);
await openAndReopen();
await waitFor(() => expect(onRequest).toHaveBeenCalledTimes(2));
});
});

View File

@@ -1,16 +1,41 @@
import { useGetTraceSummary } from 'api/generated/services/tracedetail';
import type { SpantypesGettableTraceSummaryDTO } from 'api/generated/services/sigNoz.schemas';
import { useTraceQueryStaleTime } from 'hooks/trace/useTraceQueryStaleTime';
import { StatusCodes } from 'http-status-codes';
interface UseTraceSummaryOptions {
/** Show the last trace's summary while the next one loads. Defaults to true. */
keepPreviousData?: boolean;
retry?: boolean;
}
interface UseTraceSummaryResult {
data: SpantypesGettableTraceSummaryDTO | undefined;
isLoading: boolean;
/** The trace views read the same summary table, so they 404 too. */
isNotFound: boolean;
}
export function useTraceSummary(traceId: string): UseTraceSummaryResult {
const { data, isLoading } = useGetTraceSummary(
export function useTraceSummary(
traceId: string,
{ keepPreviousData = true, retry }: UseTraceSummaryOptions = {},
): UseTraceSummaryResult {
const staleTime = useTraceQueryStaleTime(traceId);
const { data, isLoading, error } = useGetTraceSummary(
{ traceID: traceId },
{ query: { enabled: !!traceId, keepPreviousData: true } },
{
query: {
enabled: !!traceId,
keepPreviousData,
retry,
staleTime,
},
},
);
return { data: data?.data, isLoading };
return {
data: data?.data,
isLoading,
isNotFound: error?.response?.status === StatusCodes.NOT_FOUND,
};
}

View File

@@ -60,24 +60,6 @@
gap: 6px;
}
.collapseCount {
display: flex;
gap: 12px;
align-items: center;
font-size: 12px;
color: var(--l2-foreground);
}
.collapseCountItem {
display: inline-flex;
align-items: center;
gap: 4px;
}
.hasErrors {
color: var(--destructive);
}
.flameCollapse {
flex-shrink: 0;

View File

@@ -1,42 +1,24 @@
/* eslint-disable sonarjs/cognitive-complexity */
import {
MutableRefObject,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { MutableRefObject, useCallback, useEffect, useState } from 'react';
import { useAppParams } from 'lib/router/useAppParams';
import {
ChartNoAxesGantt,
ChevronDown,
ChevronRight,
Info,
TriangleAlert,
} from '@signozhq/icons';
import { ChevronDown, ChevronRight, Info } from '@signozhq/icons';
import getLocalStorageKey from 'api/browser/localstorage/get';
import { Collapse } from 'antd';
import { useDetailsPanel } from 'components/DetailsPanel';
import WarningPopover from 'components/WarningPopover/WarningPopover';
import { LOCALSTORAGE } from 'constants/localStorage';
import useGetTraceV4 from 'hooks/trace/useGetTraceV4';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import useUrlQuery from 'hooks/useUrlQuery';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { ResizableBox } from 'periscope/components/ResizableBox';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { TraceDetailsTab } from '../constants';
import { TraceDetailEventKeys, TraceDetailEvents } from '../events';
import { useSpanDetailsOpenedEvent } from '../hooks/useSpanDetailsOpenedEvent';
import { useSelectedSpanId } from '../hooks/useSelectedSpanId';
import { useSpanDetailVariant } from '../hooks/useSpanDetailVariant';
import { useTraceDetailLogEvent } from '../hooks/useTraceDetailLogEvent';
import { useTraceWaterfallData } from '../hooks/useTraceWaterfallData';
import NoData from '../NoData/NoData';
import {
setTraceStoreAvailableColorByFields,
useTraceStore,
} from '../stores/traceStore';
import TraceCounts from '../TraceCounts/TraceCounts';
import { useTraceStore } from '../stores/traceStore';
import {
SPAN_DETAILS_PANEL_MIN_WIDTH,
SpanDetailVariant,
@@ -45,9 +27,6 @@ import SpanDetailsPanel from '../SpanDetailsPanel/SpanDetailsPanel';
import { FLAMEGRAPH_SPAN_LIMIT } from '../TraceFlamegraph/constants';
import TraceFlamegraph from '../TraceFlamegraph/TraceFlamegraph';
import TraceWaterfall from '../TraceWaterfall/TraceWaterfall';
import { IInterestedSpan } from '../TraceWaterfall/types';
import { getAncestorSpanIds } from '../TraceWaterfall/utils';
import { getAvailableColorByFieldNames } from '../utils';
import cx from 'classnames';
@@ -77,21 +56,23 @@ function TraceDetailsOverview({
dataLoadedFiredForRef,
}: TraceDetailsOverviewProps): JSX.Element {
const { id: traceId } = useAppParams<'id'>();
const urlQuery = useUrlQuery();
const [interestedSpanId, setInterestedSpanId] = useState<IInterestedSpan>(
() => ({
spanId: urlQuery.get('spanId') || '',
isUncollapsed: urlQuery.get('spanId') !== '',
}),
);
const [uncollapsedNodes, setUncollapsedNodes] = useState<string[]>([]);
const [localUncollapsedNodes, setLocalUncollapsedNodes] = useState<
Set<string>
>(new Set());
const [selectedSpan, setSelectedSpan] = useState<SpanV3>();
const selectedSpanId = urlQuery.get('spanId') || undefined;
const { safeNavigate } = useSafeNavigate();
const {
traceData,
isFetchingTraceData,
errorFetchingTraceData,
allSpans,
totalSpansCount,
isFullDataLoaded,
interestedSpanId,
setInterestedSpanId,
uncollapsedNodes,
localUncollapsedNodes,
setLocalUncollapsedNodes,
selectedSpan,
setSelectedSpan,
selectedSpanId,
} = useTraceWaterfallData(traceId || '');
const [, setSelectedSpanId] = useSelectedSpanId();
const logTraceEvent = useTraceDetailLogEvent('v3', traceId || '');
const colorByField = useTraceStore((s) => s.colorByField);
@@ -99,10 +80,8 @@ function TraceDetailsOverview({
const userPrefsReady = useTraceStore((s) => s.userPreferences !== null);
const handleSpanDetailsClose = useCallback((): void => {
const params = getUnstableCurrentSearchParams();
params.delete('spanId');
safeNavigate({ search: params.toString() }, { replace: true });
}, [safeNavigate]);
setSelectedSpanId(null);
}, [setSelectedSpanId]);
const panelState = useDetailsPanel({
entityId: selectedSpanId,
@@ -115,83 +94,6 @@ function TraceDetailsOverview({
logTraceEvent,
});
const allSpansRef = useRef<SpanV3[]>([]);
const deepLinkResolvedRef = useRef(false);
// Refetch only when the URL target isn't already loaded. Keeps row clicks
// and other in-window URL navigation from triggering a backend window slide.
useEffect(() => {
const spanId = urlQuery.get('spanId') || '';
if (!spanId) {
return;
}
const idx = allSpansRef.current.findIndex((s) => s.span_id === spanId);
if (idx !== -1) {
setSelectedSpan(allSpansRef.current[idx]);
return;
}
setInterestedSpanId({ spanId, isUncollapsed: true });
}, [urlQuery]);
// Once all spans are loaded (frontend mode), freeze query params so
// subsequent interestedSpanId changes don't trigger unnecessary refetches.
const fullDataLoadedRef = useRef(false);
const frozenParamsRef = useRef({
selectedSpanId: interestedSpanId.spanId,
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
uncollapsedSpans: uncollapsedNodes,
});
const queryParams = fullDataLoadedRef.current
? frozenParamsRef.current
: {
selectedSpanId: interestedSpanId.spanId,
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
uncollapsedSpans: uncollapsedNodes,
};
const {
data: traceData,
isFetching: isFetchingTraceData,
error: errorFetchingTraceData,
} = useGetTraceV4({
traceId: traceId || '',
uncollapsedSpans: queryParams.uncollapsedSpans,
selectedSpanId: queryParams.selectedSpanId,
isSelectedSpanIDUnCollapsed: queryParams.isSelectedSpanIDUnCollapsed,
});
const allSpans = traceData?.payload?.spans || [];
const totalSpansCount = traceData?.payload?.totalSpansCount || 0;
const isFullDataLoaded =
totalSpansCount > 0 && totalSpansCount <= allSpans.length;
// Color-by options, gated on fields in loaded spans. Resource attrs are
// trace-wide, so any window has the full set — no need to accumulate.
const availableColorByFields = useMemo(() => {
const spans = traceData?.payload?.spans;
return spans?.length ? getAvailableColorByFieldNames(spans) : undefined;
}, [traceData?.payload?.spans]);
useEffect(() => {
setTraceStoreAvailableColorByFields(availableColorByFields);
}, [availableColorByFields]);
// Lock the ref once we confirm all data is loaded
if (isFullDataLoaded && !fullDataLoadedRef.current) {
fullDataLoadedRef.current = true;
frozenParamsRef.current = {
selectedSpanId: interestedSpanId.spanId,
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
uncollapsedSpans: uncollapsedNodes,
};
}
useEffect(() => {
allSpansRef.current = allSpans;
}, [allSpans]);
useEffect(() => {
if (
!traceId ||
@@ -232,82 +134,6 @@ function TraceDetailsOverview({
dataLoadedFiredForRef,
]);
// Frontend mode: expand all parents by default when full data arrives
useEffect(() => {
if (isFullDataLoaded && allSpans.length > 0) {
const parentIds = new Set(
allSpans.filter((s) => s.has_children).map((s) => s.span_id),
);
setLocalUncollapsedNodes(parentIds);
}
}, [isFullDataLoaded, allSpans]);
// Backend mode: sync uncollapsed state from API response
useEffect(() => {
if (
!isFullDataLoaded &&
traceData &&
traceData.payload &&
traceData.payload.uncollapsedSpans
) {
setUncollapsedNodes(traceData.payload.uncollapsedSpans);
}
}, [traceData, isFullDataLoaded]);
// Tracks whether we've already done the initial URL→selectedSpan handoff
//Lets `interestedSpanId` stay purely as the refetch trigger in frontend mode.
useEffect(() => {
if (deepLinkResolvedRef.current) {
return;
}
if (allSpans.length === 0) {
return;
}
if (selectedSpanId) {
const span = allSpans.find((s) => s.span_id === selectedSpanId);
if (!span) {
// Span not in the current window — wait for more data (backend
// pagination) before marking resolved.
return;
}
setSelectedSpan(span);
} else {
setSelectedSpan((prev) => prev ?? allSpans[0]);
}
deepLinkResolvedRef.current = true;
}, [selectedSpanId, allSpans]);
// Frontend mode: auto-expand ancestors of the URL-targeted span so it's
// visible. Keyed on URL `spanId`(selectedSpanId).
useEffect(() => {
if (!isFullDataLoaded || !selectedSpanId || allSpans.length === 0) {
return;
}
const ancestors = getAncestorSpanIds(allSpans, selectedSpanId);
if (ancestors.size === 0) {
return;
}
setLocalUncollapsedNodes((prev) => {
// Check if all ancestors are already expanded — avoid unnecessary state update
let allPresent = true;
for (const id of ancestors) {
if (!prev.has(id)) {
allPresent = false;
break;
}
}
if (allPresent) {
return prev;
}
const next = new Set(prev);
for (const id of ancestors) {
next.add(id);
}
return next;
});
}, [isFullDataLoaded, selectedSpanId, allSpans]);
const [activeKeys, setActiveKeys] = useState<string[]>(['flame', 'waterfall']);
const handleCollapseChange = (key: string): void => {
@@ -406,25 +232,10 @@ function TraceDetailsOverview({
</WarningPopover>
)}
</span>
{traceData?.payload?.totalSpansCount ? (
<span className={styles.collapseCount}>
<span className={styles.collapseCountItem}>
<ChartNoAxesGantt size={13} />
Spans: {traceData.payload.totalSpansCount}
</span>
<span
className={cx(styles.collapseCountItem, {
[styles.hasErrors]: traceData.payload.totalErrorSpansCount > 0,
})}
>
<TriangleAlert size={13} />
Errors:{' '}
{traceData.payload.totalErrorSpansCount ?? (
<span className="translate-safe">{0}</span>
)}
</span>
</span>
) : null}
<TraceCounts
totalSpansCount={traceData?.payload?.totalSpansCount}
totalErrorSpansCount={traceData?.payload?.totalErrorSpansCount}
/>
</div>
),
children: (

View File

@@ -229,7 +229,7 @@ function FlamegraphCanvas(props: FlamegraphCanvasProps): JSX.Element {
: null;
return (
<div className={styles.root}>
<div className={styles.root} data-testid="flamegraph-canvas">
{tooltipElement}
<TimelineV3
startTimestamp={viewStartTs}

View File

@@ -1,13 +1,11 @@
import { useCallback, useEffect, useMemo, useState } from 'react';
import { navigate } from 'lib/router/navigation';
import { ReactNode, useCallback, useEffect, useMemo, useState } from 'react';
import { useAppParams } from 'lib/router/useAppParams';
import { Skeleton } from 'antd';
import useGetTraceFlamegraphV3 from 'hooks/trace/useGetTraceFlamegraphV3';
import useUrlQuery from 'hooks/useUrlQuery';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { COLOR_BY_FIELDS } from '../constants';
import { useSelectedSpanId } from '../hooks/useSelectedSpanId';
import { useTraceStore } from '../stores/traceStore';
import Error from '../TraceWaterfall/TraceWaterfallStates/Error/Error';
import { mergeTelemetryFieldKeys } from '../utils/previewFields';
@@ -20,6 +18,10 @@ interface TraceFlamegraphProps {
isFilterActive: boolean;
selectedSpan: SpanV3 | undefined;
totalSpansCount: number;
/** Defaults to the trace in the route. */
traceId?: string;
/** Replaces the loading skeleton. */
loadingFallback?: ReactNode;
}
function TraceFlamegraph({
@@ -27,26 +29,29 @@ function TraceFlamegraph({
isFilterActive,
selectedSpan,
totalSpansCount,
traceId: traceIdProp,
loadingFallback,
}: TraceFlamegraphProps): JSX.Element {
const { id: traceId } = useAppParams<'id'>();
const urlQuery = useUrlQuery();
const { id: routeTraceId } = useAppParams<'id'>();
const traceId = traceIdProp ?? routeTraceId;
const [selectedSpanId, setSelectedSpanId] = useSelectedSpanId();
const [firstSpanAtFetchLevel, setFirstSpanAtFetchLevel] = useState<string>(
urlQuery.get('spanId') || '',
selectedSpanId || '',
);
useEffect(() => {
setFirstSpanAtFetchLevel(urlQuery.get('spanId') || '');
}, [urlQuery]);
setFirstSpanAtFetchLevel(selectedSpanId || '');
}, [selectedSpanId]);
const handleSpanClick = useCallback((spanId: string): void => {
setFirstSpanAtFetchLevel(spanId);
const searchParams = getUnstableCurrentSearchParams();
//tood: use from query params constants
if (searchParams.get('spanId') !== spanId) {
searchParams.set('spanId', spanId);
navigate({ search: searchParams.toString() }, { replace: true });
}
}, []);
const handleSpanClick = useCallback(
(spanId: string): void => {
setFirstSpanAtFetchLevel(spanId);
if (selectedSpanId !== spanId) {
setSelectedSpanId(spanId);
}
},
[selectedSpanId, setSelectedSpanId],
);
const previewFields = useTraceStore((s) => s.previewFields);
// Gate the fetch until prefs load, else selectFields (in the query key)
@@ -103,6 +108,9 @@ function TraceFlamegraph({
/>
);
}
if (loadingFallback) {
return loadingFallback;
}
return (
<div style={{ width: '100%', height: '100%', padding: '8px 12px' }}>
<Skeleton
@@ -149,6 +157,7 @@ function TraceFlamegraph({
isFilterActive,
isFetching,
layout,
loadingFallback,
traceId,
workerError,
]);

View File

@@ -0,0 +1,5 @@
export function createLayoutWorker(): Worker {
return new Worker(new URL('../visualLayout.worker.ts', import.meta.url), {
type: 'module',
});
}

View File

@@ -3,6 +3,7 @@ import { SpantypesFlamegraphSpanDTO as FlamegraphSpan } from 'api/generated/serv
import { computeVisualLayout, VisualLayout } from '../computeVisualLayout';
import { LayoutWorkerResponse } from '../visualLayoutWorkerTypes';
import { createLayoutWorker } from './createLayoutWorker';
const EMPTY_LAYOUT: VisualLayout = {
visualRows: [],
@@ -15,12 +16,6 @@ function computeLayoutOrEmpty(spans: FlamegraphSpan[][]): VisualLayout {
return spans.length ? computeVisualLayout(spans) : EMPTY_LAYOUT;
}
function createLayoutWorker(): Worker {
return new Worker(new URL('../visualLayout.worker.ts', import.meta.url), {
type: 'module',
});
}
export function useVisualLayoutWorker(spans: FlamegraphSpan[][]): {
layout: VisualLayout;
isComputing: boolean;

View File

@@ -1,9 +1,9 @@
import { Dispatch, SetStateAction, useMemo } from 'react';
import { Dispatch, ReactNode, SetStateAction, useMemo } from 'react';
import { Skeleton } from 'antd';
import { AxiosError } from 'axios';
import Spinner from 'components/Spinner';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { GetTraceV4SuccessResponse, SpanV3 } from 'types/api/trace/getTraceV3';
import type { UseTraceWaterfallDataResult } from '../hooks/useTraceWaterfallData';
import { TraceWaterfallStates } from './constants';
import Error from './TraceWaterfallStates/Error/Error';
@@ -26,13 +26,15 @@ interface ITraceWaterfallProps {
| ErrorResponse
| undefined;
isFetchingTraceData: boolean;
errorFetchingTraceData: unknown;
errorFetchingTraceData: UseTraceWaterfallDataResult['errorFetchingTraceData'];
interestedSpanId: IInterestedSpan;
setInterestedSpanId: Dispatch<SetStateAction<IInterestedSpan>>;
selectedSpan: SpanV3 | undefined;
setSelectedSpan: Dispatch<SetStateAction<SpanV3 | undefined>>;
filteredSpanIds: string[];
isFilterActive: boolean;
/** Replaces the loading skeleton. */
loadingFallback?: ReactNode;
}
function TraceWaterfall(props: ITraceWaterfallProps): JSX.Element {
@@ -51,6 +53,7 @@ function TraceWaterfall(props: ITraceWaterfallProps): JSX.Element {
selectedSpan,
filteredSpanIds,
isFilterActive,
loadingFallback,
} = props;
// get the current state of trace waterfall based on the API lifecycle
const traceWaterfallState = useMemo(() => {
@@ -99,13 +102,16 @@ function TraceWaterfall(props: ITraceWaterfallProps): JSX.Element {
const getContent = useMemo(() => {
switch (traceWaterfallState) {
case TraceWaterfallStates.LOADING:
if (loadingFallback) {
return loadingFallback;
}
return (
<div className={styles.loadingSkeleton}>
<Skeleton active paragraph={{ rows: 6 }} />
</div>
);
case TraceWaterfallStates.ERROR:
return <Error error={errorFetchingTraceData as AxiosError} />;
return errorFetchingTraceData && <Error error={errorFetchingTraceData} />;
case TraceWaterfallStates.NO_DATA:
return <NoData id={traceId} />;
case TraceWaterfallStates.SUCCESS:
@@ -144,6 +150,7 @@ function TraceWaterfall(props: ITraceWaterfallProps): JSX.Element {
interestedSpanId,
isFilterActive,
isFullDataLoaded,
loadingFallback,
localUncollapsedNodes,
setLocalUncollapsedNodes,
selectedSpan,

View File

@@ -1,5 +1,4 @@
import { useCallback, useMemo, useRef, useState } from 'react';
import { navigate } from 'lib/router/navigation';
import { ArrowRightFromLine, Search, X } from '@signozhq/icons';
import { Switch } from '@signozhq/ui/switch';
import { ToggleGroup } from '@signozhq/ui/toggle-group';
@@ -11,7 +10,7 @@ import QuerySearch from 'components/QueryBuilderV2/QueryV2/QuerySearch/QuerySear
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { uniqBy } from 'lodash-es';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import NozButton from 'pages/TraceDetailsV3/TraceDetailsHeader/NozButton';
import CopyButton from 'periscope/components/CopyButton/CopyButton';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
@@ -163,18 +162,13 @@ function Filters({
const { selectedCategory, categories, handleCategoryChange } =
useSpanCategoryFilter(filterProps);
const [, setSelectedSpanId] = useSelectedSpanId();
const handlePrevNext = useCallback(
(index: number, spanId?: string): void => {
const searchParams = getUnstableCurrentSearchParams();
if (spanId) {
searchParams.set('spanId', spanId);
} else {
searchParams.set('spanId', filteredSpanIds[index]);
}
navigate({ search: searchParams.toString() }, { replace: true });
setSelectedSpanId(spanId || filteredSpanIds[index]);
},
[filteredSpanIds],
[filteredSpanIds, setSelectedSpanId],
);
const isFilterActive = committedExpression.trim().length > 0;

View File

@@ -35,6 +35,24 @@
flex-direction: column;
}
// Hosts without antd's reset (the explorer span drawer) default to content-box,
// which widens the padded rows and bars past the ruler.
.splitPanel,
.sidebarHeader,
.timelineHeader,
.sidebar,
.treeCell,
.statusCell,
.timelineRow,
.treeConnector,
.subtreeCountSlot,
.rowActions,
.spanDuration,
.spanBar,
.eventDot {
box-sizing: border-box;
}
.splitPanel {
flex: 1;
min-height: 0;
@@ -63,11 +81,6 @@
border-right: 1px solid var(--l2-border);
}
.resizeHandleHeader {
width: 4px;
flex-shrink: 0;
}
.statusHeader {
width: 50px;
flex-shrink: 0;
@@ -438,14 +451,23 @@
cursor: pointer;
}
$span-bar-padding-x: 8px;
$span-bar-border-width: 1px;
.spanBar {
position: absolute;
// Padding and border set a minimum width; shift short bars near the
// trace end left so they don't overflow the track.
left: min(
var(--span-left),
calc(100% - #{2 * ($span-bar-padding-x + $span-bar-border-width)})
);
height: 18px;
top: 3px;
border-radius: 2px;
display: flex;
align-items: center;
padding: 0 8px;
padding: 0 $span-bar-padding-x;
overflow: hidden;
cursor: pointer;
white-space: nowrap;
@@ -453,7 +475,7 @@
// the darkened light-mode fill. See SpanDuration in Success.tsx.
color: var(--span-text-color);
background-color: var(--span-color);
border: 1px solid transparent;
border: $span-bar-border-width solid transparent;
}
.spanInfo {

View File

@@ -5,6 +5,7 @@ import {
SetStateAction,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
@@ -25,8 +26,7 @@ import TimelineV3 from 'components/TimelineV3/TimelineV3';
import { convertTimeToRelevantUnit } from 'utils/traceUtils';
import { useCopySpanLink } from 'hooks/trace/useCopySpanLink';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { getUnstableCurrentSearchParams } from 'utils/getUnstableCurrentSearchParams';
import { useSelectedSpanId } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import { colorToRgb } from 'lib/uPlotLib/utils/generateColor';
import {
ChevronDown,
@@ -450,8 +450,8 @@ export const SpanDuration = memo(function SpanDuration({
className={styles.spanBar}
style={
{
left: `${leftOffset}%`,
width: `${width}%`,
'--span-left': `${leftOffset}%`,
'--span-color': effectiveColor,
'--span-color-rgb': rgbColor,
'--span-text-color': spanTextColor,
@@ -583,10 +583,20 @@ function Success(props: ISuccessProps): JSX.Element {
if (hoverDelayTimerRef.current) {
clearTimeout(hoverDelayTimerRef.current);
}
hoverDelayTimerRef.current = setTimeout(
() => hoverCard.showAt(row, span),
SPAN_HOVER_CARD_DELAY_MS,
);
hoverDelayTimerRef.current = setTimeout(() => {
// A deep tree is wider than its scrolled column, so the row runs on under the
// timeline; the card goes beside the part of the row on screen.
const rect = row.getBoundingClientRect();
const columnRight = row
.closest(`.${styles.sidebar}`)
?.getBoundingClientRect().right;
hoverCard.showAt(
columnRight !== undefined && rect.right > columnRight
? new DOMRect(rect.left, rect.top, columnRight - rect.left, rect.height)
: row,
span,
);
}, SPAN_HOVER_CARD_DELAY_MS);
},
[applyHoverClass, hoverCard],
);
@@ -610,6 +620,12 @@ function Success(props: ISuccessProps): JSX.Element {
[],
);
// New spans (an expand, a collapse or a window fetch) replace the rows, and a card left on a
// removed row is placed at 0,0. Closed before paint so that frame never shows.
useLayoutEffect(() => {
handleRowMouseLeave();
}, [spans, handleRowMouseLeave]);
const handleCollapseUncollapse = useCallback(
(spanId: string, collapse: boolean) => {
if (isFullDataLoaded) {
@@ -696,19 +712,16 @@ function Success(props: ISuccessProps): JSX.Element {
setSelectedSpanToAddToFunnel(span);
}, []);
const { safeNavigate } = useSafeNavigate();
const [selectedSpanId, setSelectedSpanId] = useSelectedSpanId();
const handleSpanClick = useCallback(
(span: SpanV3): void => {
setSelectedSpan(span);
const params = getUnstableCurrentSearchParams();
if (span?.span_id) {
params.set('spanId', span?.span_id);
if (span?.span_id && span.span_id !== selectedSpanId) {
setSelectedSpanId(span.span_id);
}
safeNavigate({ search: params.toString() }, { replace: true });
},
[setSelectedSpan, safeNavigate],
[setSelectedSpan, selectedSpanId, setSelectedSpanId],
);
// Left side columns using TanStack React Table (extensible for future columns)
@@ -868,7 +881,6 @@ function Success(props: ISuccessProps): JSX.Element {
className={styles.sidebarHeader}
style={{ width: sidebarWidth, flexShrink: 0 }}
/>
<div className={styles.resizeHandleHeader} />
<div className={styles.statusHeader} />
<div className={styles.timelineHeader}>
<TimelineV3

View File

@@ -1,10 +1,9 @@
import React from 'react';
import { getCurrentLocation } from 'lib/router/navigation';
import { TraceDetailsTab } from 'pages/TraceDetailsV3/constants';
import { useTraceDetailsTab } from 'pages/TraceDetailsV3/hooks/useTraceDetailsTab';
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import {
__resetSearchParamsGetter,
__setSearchParamsGetterForTest,
} from 'utils/getUnstableCurrentSearchParams';
// Local identity-proxy mock for this module so `styles.foo` resolves to
// `'foo'` in test assertions. The global `__mocks__/cssMock.ts` stays as
@@ -27,24 +26,11 @@ import successStyles from '../Success.module.scss';
const renderWithTraceProvider: typeof render = (ui, options, customOptions) =>
render(ui, options, customOptions);
// Mock the required hooks with proper typing
const mockSafeNavigate = jest.fn() as jest.MockedFunction<
(params: { search: string }) => void
>;
const mockUrlQuery = new URLSearchParams();
jest.mock('hooks/useSafeNavigate', () => ({
useSafeNavigate: (): { safeNavigate: typeof mockSafeNavigate } => ({
safeNavigate: mockSafeNavigate,
}),
}));
jest.mock('hooks/useUrlQuery', () => (): URLSearchParams => mockUrlQuery);
const getSearchParam = (key: string): string | null =>
new URLSearchParams(getCurrentLocation().search).get(key);
// App provider is already handled by test-utils
// React Router is already globally mocked
// Mock the Filters component that's causing React Query issues
jest.mock('../Filters/Filters', () => {
function Filters(): null {
@@ -226,13 +212,6 @@ describe('Span Click User Flows', () => {
beforeEach(() => {
jest.clearAllMocks();
// Clear all URL parameters
Array.from(mockUrlQuery.keys()).forEach((key) => mockUrlQuery.delete(key));
__setSearchParamsGetterForTest(() => new URLSearchParams(mockUrlQuery));
});
afterEach(() => {
__resetSearchParamsGetter();
});
it('clicking span updates URL with spanId parameter', async () => {
@@ -258,18 +237,13 @@ describe('Span Click User Flows', () => {
);
// Initially URL should not have spanId
expect(mockUrlQuery.get('spanId')).toBeNull();
expect(getSearchParam('spanId')).toBeNull();
// Click on the actual span element (not the wrapper)
const spanElement = screen.getByTestId(FIRST_SPAN_TEST_ID);
await user.click(spanElement);
expect(mockSafeNavigate).toHaveBeenCalledWith(
{
search: expect.stringContaining('spanId=span-1'),
},
{ replace: true },
);
await waitFor(() => expect(getSearchParam('spanId')).toBe('span-1'));
});
it('clicking span duration visually selects the span', async () => {
@@ -360,10 +334,6 @@ describe('Span Click User Flows', () => {
it('preserves existing URL parameters when selecting spans', async () => {
const user = userEvent.setup();
// Pre-populate URL with existing parameters
mockUrlQuery.set('existingParam', 'existingValue');
mockUrlQuery.set('anotherParam', 'anotherValue');
renderWithTraceProvider(
<Success
spans={mockSpans}
@@ -380,54 +350,67 @@ describe('Span Click User Flows', () => {
isFilterActive={false}
/>,
undefined,
{ initialRoute: '/trace' },
{
initialRoute:
'/trace?existingParam=existingValue&anotherParam=anotherValue',
},
);
const spanElement = screen.getByTestId(FIRST_SPAN_TEST_ID);
await user.click(spanElement);
// Verify existing parameters are preserved and spanId is added
expect(mockSafeNavigate).toHaveBeenCalledWith(
{
search: expect.stringMatching(
/existingParam=existingValue.*anotherParam=anotherValue.*spanId=span-1/,
),
},
{ replace: true },
);
await waitFor(() => expect(getSearchParam('spanId')).toBe('span-1'));
expect(getSearchParam('existingParam')).toBe('existingValue');
expect(getSearchParam('anotherParam')).toBe('anotherValue');
});
it('keeps a tab param the router has not seen when selecting spans', async () => {
const user = userEvent.setup();
// nuqs wrote ?tab=thread to the real URL; react-router's copy is stale.
__setSearchParamsGetterForTest(() => new URLSearchParams('tab=thread'));
// Writes `tab` the way the page does: a shallow nuqs write the router doesn't see.
function SelectThreadTab(): JSX.Element {
const [, setTab] = useTraceDetailsTab();
return (
<button
type="button"
aria-label="Select thread tab"
data-testid="select-thread-tab"
onClick={(): void => {
void setTab(TraceDetailsTab.Thread);
}}
/>
);
}
renderWithTraceProvider(
<Success
spans={mockSpans}
traceMetadata={mockTraceMetadata}
interestedSpanId={{ spanId: '', isUncollapsed: false }}
uncollapsedNodes={mockSpans.map((s) => s.span_id)}
isFullDataLoaded={false}
localUncollapsedNodes={new Set()}
setLocalUncollapsedNodes={jest.fn()}
setInterestedSpanId={jest.fn()}
selectedSpan={undefined}
setSelectedSpan={jest.fn()}
filteredSpanIds={[]}
isFilterActive={false}
/>,
<>
<SelectThreadTab />
<Success
spans={mockSpans}
traceMetadata={mockTraceMetadata}
interestedSpanId={{ spanId: '', isUncollapsed: false }}
uncollapsedNodes={mockSpans.map((s) => s.span_id)}
isFullDataLoaded={false}
localUncollapsedNodes={new Set()}
setLocalUncollapsedNodes={jest.fn()}
setInterestedSpanId={jest.fn()}
selectedSpan={undefined}
setSelectedSpan={jest.fn()}
filteredSpanIds={[]}
isFilterActive={false}
/>
</>,
undefined,
{ initialRoute: '/trace' },
);
await user.click(screen.getByTestId('select-thread-tab'));
expect(getSearchParam('tab')).toBeNull();
const spanElement = screen.getByTestId(FIRST_SPAN_TEST_ID);
await user.click(spanElement);
expect(mockSafeNavigate).toHaveBeenCalledWith(
{ search: expect.stringMatching(/tab=thread.*spanId=span-1/) },
{ replace: true },
);
await waitFor(() => expect(getSearchParam('spanId')).toBe('span-1'));
expect(getSearchParam('tab')).toBe(TraceDetailsTab.Thread);
});
});

View File

@@ -0,0 +1,136 @@
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import Success from '../Success';
jest.mock('../Filters/Filters', () => {
function Filters(): null {
return null;
}
return Filters;
});
jest.mock('components/TimelineV3/TimelineV3', () => {
function TimelineV3(): null {
return null;
}
return { __esModule: true, default: TimelineV3 };
});
// jsdom has no layout, so the virtualizer would render no rows.
jest.mock('@tanstack/react-virtual', () => ({
useVirtualizer: ({
count,
}: {
count: number;
}): {
getVirtualItems: () => Array<{
index: number;
key: number;
start: number;
size: number;
}>;
getTotalSize: () => number;
scrollToIndex: () => void;
} => ({
getVirtualItems: () =>
Array.from({ length: count }, (_, i) => ({
index: i,
key: i,
start: i * 54,
size: 54,
})),
getTotalSize: () => count * 54,
scrollToIndex: (): void => {},
}),
}));
const TRACE_START = 1679748225000000;
const span = (spanId: string, level: number, hasChildren: boolean): SpanV3 => ({
span_id: spanId,
trace_id: 'trace-1',
parent_span_id: level === 0 ? '' : 'root',
name: spanId,
'service.name': 'frontend',
timestamp: TRACE_START,
duration_nano: 50000000,
level,
has_error: false,
kind: 1,
kind_string: 'server',
attributes: {},
resource: {},
events: [],
status_message: '',
status_code: 0,
status_code_string: 'OK',
has_children: hasChildren,
has_sibling: false,
sub_tree_node_count: hasChildren ? 2 : 1,
http_method: '',
http_url: '',
http_host: '',
db_name: '',
db_operation: '',
external_http_method: '',
external_http_url: '',
response_status_code: '',
is_remote: '',
flags: 0,
trace_state: '',
});
const renderWaterfall = (spans: SpanV3[]): JSX.Element => (
<Success
spans={spans}
traceMetadata={{
traceId: 'trace-1',
startTime: TRACE_START,
endTime: TRACE_START + 1000000,
hasMissingSpans: false,
}}
interestedSpanId={{ spanId: '', isUncollapsed: false }}
uncollapsedNodes={['root']}
isFullDataLoaded={false}
localUncollapsedNodes={new Set()}
setLocalUncollapsedNodes={(): void => {}}
setInterestedSpanId={(): void => {}}
selectedSpan={undefined}
setSelectedSpan={(): void => {}}
filteredSpanIds={[]}
isFilterActive={false}
/>
);
describe('Waterfall hover card', () => {
afterEach(() => {
jest.useRealTimers();
});
it('closes when new spans replace the rows', async () => {
jest.useFakeTimers();
const user = userEvent.setup({
advanceTimers: (ms) => jest.advanceTimersByTime(ms),
});
const { rerender } = render(
renderWaterfall([span('root', 0, true), span('child', 1, false)]),
undefined,
{ initialRoute: '/trace' },
);
await user.hover(screen.getByTestId('span-overview-root'));
jest.advanceTimersByTime(500);
await expect(
screen.findByTestId('span-hover-card-status'),
).resolves.toBeInTheDocument();
rerender(renderWaterfall([span('root', 0, true), span('other', 1, false)]));
await waitFor(() =>
expect(
screen.queryByTestId('span-hover-card-status'),
).not.toBeInTheDocument(),
);
});
});

View File

@@ -0,0 +1,174 @@
import { ReactNode } from 'react';
import type {
GetWaterfallV4200,
SpantypesPostableWaterfallDTO,
SpantypesWaterfallSpanDTO,
} from 'api/generated/services/sigNoz.schemas';
import { rest, server } from 'mocks-server/server';
import { act, AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
import { useSelectedSpanId } from '../useSelectedSpanId';
import { useTraceWaterfallData } from '../useTraceWaterfallData';
const span = (
spanId: string,
parentSpanId: string,
level: number,
traceId = 't1',
): SpantypesWaterfallSpanDTO => ({
span_id: spanId,
parent_span_id: parentSpanId,
trace_id: traceId,
level,
has_children: level < 2,
name: spanId,
time_unix: 1_700_000_000_000 + level,
duration_nano: 1_000_000,
references: [],
});
const SPANS = [
span('root', '', 0),
span('child', 'root', 1),
span('leaf', 'child', 2),
];
const serveWaterfall = (
totalSpansCount: number,
): SpantypesPostableWaterfallDTO[] => {
const requests: SpantypesPostableWaterfallDTO[] = [];
server.use(
rest.post('*/api/v4/traces/:traceId/waterfall', async (req, res, ctx) => {
requests.push(await req.json());
const body: GetWaterfallV4200 = {
status: 'success',
data: {
spans: SPANS,
totalSpansCount,
uncollapsedSpans: [],
startTimestampMillis: 0,
endTimestampMillis: 1,
},
};
return res(ctx.status(200), ctx.json(body));
}),
);
return requests;
};
const renderWaterfallData = (spanId: string, enabled = true) =>
renderHook(
({ traceId }: { traceId: string }) => ({
data: useTraceWaterfallData(traceId, { enabled }),
setSpanId: useSelectedSpanId()[1],
}),
{
initialProps: { traceId: 't1' },
wrapper: function Wrapper({ children }: { children: ReactNode }) {
return (
<AllTheProviders initialRoute={`/trace/t1?spanId=${spanId}`}>
{children}
</AllTheProviders>
);
},
},
);
describe('useTraceWaterfallData', () => {
it('selects a span from the url without refetching once every span is loaded', async () => {
const requests = serveWaterfall(SPANS.length);
const { result } = renderWaterfallData('root');
await waitFor(() =>
expect(result.current.data.selectedSpan?.span_id).toBe('root'),
);
act(() => result.current.setSpanId('leaf'));
await waitFor(() =>
expect(result.current.data.selectedSpan?.span_id).toBe('leaf'),
);
expect(result.current.data.isFullDataLoaded).toBe(true);
expect(requests).toHaveLength(1);
});
it('selects a span inside the loaded window without refetching', async () => {
const requests = serveWaterfall(100);
const { result } = renderWaterfallData('root');
await waitFor(() =>
expect(result.current.data.selectedSpan?.span_id).toBe('root'),
);
act(() => result.current.setSpanId('child'));
await waitFor(() =>
expect(result.current.data.selectedSpan?.span_id).toBe('child'),
);
expect(result.current.data.isFullDataLoaded).toBe(false);
expect(requests).toHaveLength(1);
});
it('refetches the window around a span outside it', async () => {
const requests = serveWaterfall(100);
const { result } = renderWaterfallData('root');
await waitFor(() => expect(requests).toHaveLength(1));
act(() => result.current.setSpanId('far'));
await waitFor(() => expect(requests).toHaveLength(2));
expect(requests[1]).toStrictEqual({
selectedSpanId: 'far',
uncollapsedSpans: ['far'],
});
});
it('waits for a deep-linked span instead of selecting the root', async () => {
const requests = serveWaterfall(100);
const { result } = renderWaterfallData('far');
await waitFor(() => expect(result.current.data.allSpans).toHaveLength(3));
expect(requests[0].selectedSpanId).toBe('far');
expect(result.current.data.selectedSpan).toBeUndefined();
});
it('sends no request while disabled', async () => {
const requests = serveWaterfall(SPANS.length);
const { result } = renderWaterfallData('root', false);
await waitFor(() =>
expect(result.current.data.isFetchingTraceData).toBe(false),
);
expect(requests).toHaveLength(0);
});
it('starts the next trace from scratch while it loads', async () => {
const requests: SpantypesPostableWaterfallDTO[] = [];
server.use(
rest.post('*/api/v4/traces/:traceId/waterfall', async (req, res, ctx) => {
requests.push(await req.json());
const traceId = String(req.params.traceId);
const body: GetWaterfallV4200 = {
status: 'success',
data: {
spans: [span(`${traceId}-root`, '', 0, traceId)],
totalSpansCount: 1,
uncollapsedSpans: [],
startTimestampMillis: 0,
endTimestampMillis: 1,
},
};
return res(ctx.status(200), ctx.json(body));
}),
);
const { result, rerender } = renderWaterfallData('t1-root');
await waitFor(() => expect(result.current.data.isFullDataLoaded).toBe(true));
act(() => result.current.setSpanId('t2-root'));
rerender({ traceId: 't2' });
expect(result.current.data.allSpans).toStrictEqual([]);
await waitFor(() =>
expect(result.current.data.selectedSpan?.span_id).toBe('t2-root'),
);
expect(requests[1].selectedSpanId).toBe('t2-root');
});
});

View File

@@ -0,0 +1,24 @@
import { useCallback } from 'react';
import { parseAsString, useQueryState } from 'nuqs';
export const SELECTED_SPAN_ID_PARAM = 'spanId';
/** Not shallow: the thread tab reads `spanId` from the router location. */
export function useSelectedSpanId(): [
string | null,
(spanId: string | null) => void,
] {
const [spanId, setSpanIdParam] = useQueryState(
SELECTED_SPAN_ID_PARAM,
parseAsString.withOptions({ shallow: false }),
);
const setSpanId = useCallback(
(next: string | null): void => {
void setSpanIdParam(next);
},
[setSpanIdParam],
);
return [spanId, setSpanId];
}

View File

@@ -0,0 +1,260 @@
import {
Dispatch,
SetStateAction,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import useGetTraceV4 from 'hooks/trace/useGetTraceV4';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { setTraceStoreAvailableColorByFields } from '../stores/traceStore';
import { IInterestedSpan } from '../TraceWaterfall/types';
import { getAncestorSpanIds } from '../TraceWaterfall/utils';
import { getAvailableColorByFieldNames } from '../utils';
import { useSelectedSpanId } from './useSelectedSpanId';
type TraceV4Result = ReturnType<typeof useGetTraceV4>;
export interface UseTraceWaterfallDataResult {
traceData: TraceV4Result['data'];
isFetchingTraceData: boolean;
/** `traceData` answers an earlier request for this trace; the current one hasn't returned. */
isPreviousData: boolean;
errorFetchingTraceData: TraceV4Result['error'];
allSpans: SpanV3[];
totalSpansCount: number;
isFullDataLoaded: boolean;
interestedSpanId: IInterestedSpan;
setInterestedSpanId: Dispatch<SetStateAction<IInterestedSpan>>;
uncollapsedNodes: string[];
localUncollapsedNodes: Set<string>;
setLocalUncollapsedNodes: Dispatch<SetStateAction<Set<string>>>;
selectedSpan: SpanV3 | undefined;
setSelectedSpan: Dispatch<SetStateAction<SpanV3 | undefined>>;
selectedSpanId: string | undefined;
}
type UseTraceWaterfallDataOptions = {
/** False skips the request; cached data for the trace is still returned. */
enabled?: boolean;
};
export function useTraceWaterfallData(
traceId: string,
{ enabled = true }: UseTraceWaterfallDataOptions = {},
): UseTraceWaterfallDataResult {
const [urlSpanId] = useSelectedSpanId();
const [interestedSpanId, setInterestedSpanId] = useState<IInterestedSpan>(
() => ({
spanId: urlSpanId || '',
isUncollapsed: urlSpanId !== '',
}),
);
const [uncollapsedNodes, setUncollapsedNodes] = useState<string[]>([]);
const [localUncollapsedNodes, setLocalUncollapsedNodes] = useState<
Set<string>
>(new Set());
const [selectedSpan, setSelectedSpan] = useState<SpanV3>();
const selectedSpanId = urlSpanId || undefined;
const allSpansRef = useRef<SpanV3[]>([]);
const deepLinkResolvedRef = useRef(false);
const fullDataLoadedRef = useRef(false);
// Hosts stay mounted across traces; each trace starts from scratch. The trace id is
// state, not a ref, so a render React throws away resets again on its retry.
const [resetTraceId, setResetTraceId] = useState(traceId);
if (resetTraceId !== traceId) {
setResetTraceId(traceId);
allSpansRef.current = [];
deepLinkResolvedRef.current = false;
fullDataLoadedRef.current = false;
setInterestedSpanId({
spanId: urlSpanId || '',
isUncollapsed: urlSpanId !== '',
});
setUncollapsedNodes([]);
setLocalUncollapsedNodes(new Set());
setSelectedSpan(undefined);
}
// Refetch only when the URL target isn't already loaded. Keeps row clicks
// and other in-window URL navigation from triggering a backend window slide.
useEffect(() => {
if (!urlSpanId) {
return;
}
const idx = allSpansRef.current.findIndex((s) => s.span_id === urlSpanId);
if (idx !== -1) {
setSelectedSpan(allSpansRef.current[idx]);
return;
}
setInterestedSpanId({ spanId: urlSpanId, isUncollapsed: true });
}, [urlSpanId]);
// Once all spans are loaded (frontend mode), freeze query params so
// subsequent interestedSpanId changes don't trigger unnecessary refetches.
const frozenParamsRef = useRef({
selectedSpanId: interestedSpanId.spanId,
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
uncollapsedSpans: uncollapsedNodes,
});
const queryParams = fullDataLoadedRef.current
? frozenParamsRef.current
: {
selectedSpanId: interestedSpanId.spanId,
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
uncollapsedSpans: uncollapsedNodes,
};
const {
data,
isPreviousData,
isFetching: isFetchingTraceData,
error: errorFetchingTraceData,
} = useGetTraceV4(
{
traceId,
uncollapsedSpans: queryParams.uncollapsedSpans,
selectedSpanId: queryParams.selectedSpanId,
isSelectedSpanIDUnCollapsed: queryParams.isSelectedSpanIDUnCollapsed,
},
{ enabled },
);
// keepPreviousData would otherwise hand the last trace's spans to the next one.
const dataTraceIdRef = useRef<string>();
if (data && !isPreviousData) {
dataTraceIdRef.current = traceId;
}
const traceData = dataTraceIdRef.current === traceId ? data : undefined;
const allSpans = traceData?.payload?.spans || [];
const totalSpansCount = traceData?.payload?.totalSpansCount || 0;
const isFullDataLoaded =
totalSpansCount > 0 && totalSpansCount <= allSpans.length;
// Color-by options, gated on fields in loaded spans. Resource attrs are
// trace-wide, so any window has the full set — no need to accumulate.
const availableColorByFields = useMemo(() => {
const spans = traceData?.payload?.spans;
return spans?.length ? getAvailableColorByFieldNames(spans) : undefined;
}, [traceData?.payload?.spans]);
useEffect(() => {
setTraceStoreAvailableColorByFields(availableColorByFields);
}, [availableColorByFields]);
// Lock the ref once we confirm all data is loaded
if (isFullDataLoaded && !fullDataLoadedRef.current) {
fullDataLoadedRef.current = true;
frozenParamsRef.current = {
selectedSpanId: interestedSpanId.spanId,
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
uncollapsedSpans: uncollapsedNodes,
};
}
useEffect(() => {
allSpansRef.current = allSpans;
}, [allSpans]);
// Frontend mode: expand all parents by default when full data arrives
useEffect(() => {
if (isFullDataLoaded && allSpans.length > 0) {
const parentIds = new Set(
allSpans.filter((s) => s.has_children).map((s) => s.span_id),
);
setLocalUncollapsedNodes(parentIds);
}
}, [isFullDataLoaded, allSpans]);
// Backend mode: sync uncollapsed state from API response
useEffect(() => {
if (
!isFullDataLoaded &&
traceData &&
traceData.payload &&
traceData.payload.uncollapsedSpans
) {
setUncollapsedNodes(traceData.payload.uncollapsedSpans);
}
}, [traceData, isFullDataLoaded]);
// Tracks whether we've already done the initial URL→selectedSpan handoff
//Lets `interestedSpanId` stay purely as the refetch trigger in frontend mode.
useEffect(() => {
if (deepLinkResolvedRef.current) {
return;
}
if (allSpans.length === 0) {
return;
}
if (selectedSpanId) {
const span = allSpans.find((s) => s.span_id === selectedSpanId);
if (!span) {
// Span not in the current window — wait for more data (backend
// pagination) before marking resolved.
return;
}
setSelectedSpan(span);
} else {
setSelectedSpan((prev) => prev ?? allSpans[0]);
}
deepLinkResolvedRef.current = true;
}, [selectedSpanId, allSpans]);
// Frontend mode: auto-expand ancestors of the URL-targeted span so it's
// visible. Keyed on URL `spanId`(selectedSpanId).
useEffect(() => {
if (!isFullDataLoaded || !selectedSpanId || allSpans.length === 0) {
return;
}
const ancestors = getAncestorSpanIds(allSpans, selectedSpanId);
if (ancestors.size === 0) {
return;
}
setLocalUncollapsedNodes((prev) => {
// Check if all ancestors are already expanded — avoid unnecessary state update
let allPresent = true;
for (const id of ancestors) {
if (!prev.has(id)) {
allPresent = false;
break;
}
}
if (allPresent) {
return prev;
}
const next = new Set(prev);
for (const id of ancestors) {
next.add(id);
}
return next;
});
}, [isFullDataLoaded, selectedSpanId, allSpans]);
return {
traceData,
isFetchingTraceData,
isPreviousData,
errorFetchingTraceData,
allSpans,
totalSpansCount,
isFullDataLoaded,
interestedSpanId,
setInterestedSpanId,
uncollapsedNodes,
localUncollapsedNodes,
setLocalUncollapsedNodes,
selectedSpan,
setSelectedSpan,
selectedSpanId,
};
}

View File

@@ -15,7 +15,7 @@ interface TraceStoreSyncProps {
/**
* Bridges React-managed inputs (`userPreferences` from AppContext and the
* user-pref mutation hook) into the Zustand store. `availableColorByFields`
* is pushed by TraceDetailsOverview, which owns the span data.
* is pushed by useTraceWaterfallData, which loads the span data.
*
* Renders nothing until `userPreferences` resolves so the flamegraph never
* paints with the default colour first and then swaps to the user's

View File

@@ -28,6 +28,7 @@ import {
import ListView from 'container/TracesExplorer/ListView';
import { defaultSelectedColumns } from 'container/TracesExplorer/ListView/configs';
import QuerySection from 'container/TracesExplorer/QuerySection';
import { useCloseSpanDrawerOnQueryChange } from 'container/TracesExplorer/SpanDrawer/useCloseSpanDrawerOnQueryChange';
import TableView from 'container/TracesExplorer/TableView';
import TracesView from 'container/TracesExplorer/TracesView';
import { useGetPanelTypesQueryParam } from 'hooks/queryBuilder/useGetPanelTypesQueryParam';
@@ -114,6 +115,7 @@ function TracesExplorer(): JSX.Element {
() => getExplorerViewFromUrl(searchParams, panelTypesFromUrl),
[searchParams, panelTypesFromUrl],
);
useCloseSpanDrawerOnQueryChange(selectedView);
const [warning, setWarning] = useState<Warning | undefined>();
const [isOpen, setOpen] = useState<boolean>(true);

View File

@@ -9,6 +9,7 @@ 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 { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
import type { CreateFunnelPayload } from 'types/api/traceFunnels';
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
import { USER_ROLES } from 'types/roles';
@@ -31,6 +32,11 @@ import {
} from '@/storybook/msw/__story_mockdata__/queryRange';
import {
DRAWER_URL_STATES,
ORDERS_CHILD_OPERATION,
ORDERS_OPERATION,
type DrawerUrlState,
drawerUrlParams,
exportDashboardsResponse,
ORDERS_SPAN_ROWS,
savedTraceViewsResponse,
@@ -40,6 +46,7 @@ import {
type SpanLogsState,
traceFieldKeysResponse,
traceFieldValues,
traceFlamegraphResponse,
traceFunnelsResponse,
traceQuickFiltersResponse,
traceRootSpanRows,
@@ -48,8 +55,11 @@ import {
traceSummaryResponse,
TRACES_EXPLORER_VIEWS,
TRACES_TABS,
TRACE_SIZES,
type TraceSize,
type TraceSummaryState,
type TracesTab,
traceWaterfallResponse,
} from './__story_mockdata__/traces';
const VIEW = 'Traces · view';
@@ -60,9 +70,10 @@ const SAVED = 'Traces · saved';
interface RouteValues {
tab: TracesTab;
view: ExplorerViews;
drawerUrl: DrawerUrlState;
}
const tracesRoute = ({ tab, view }: RouteValues): string => {
const tracesRoute = ({ tab, view, drawerUrl }: RouteValues): string => {
if (tab === 'funnels') {
return ROUTES.TRACES_FUNNELS;
}
@@ -70,6 +81,7 @@ const tracesRoute = ({ tab, view }: RouteValues): string => {
const params = new URLSearchParams({
[QueryParams.panelTypes]: JSON.stringify(explorerViewToPanelType[view]),
[QueryParams.selectedExplorerView]: view,
...drawerUrlParams(drawerUrl),
});
return `${ROUTES.TRACES_EXPLORER}?${params.toString()}`;
@@ -127,6 +139,26 @@ export const tracesMocks = defineStoryMocks({
options: TRACE_SUMMARY_STATES,
value: 'found',
}),
drawerUrl: choiceControl<DrawerUrlState>('Span in the url', {
group: LIST,
description:
'Opens the span drawer from the url: on a list row, on a span of that trace the list does not show, on a span id the trace does not have (falls back to its root span), or on a trace that does not exist.',
options: DRAWER_URL_STATES,
value: 'none',
}),
traceSize: choiceControl<TraceSize>('Trace size', {
group: LIST,
description:
"The span count the trace summary reports. Over the flame graph's limit the drawer offers only the waterfall.",
options: TRACE_SIZES,
value: 'small',
}),
missingSpans: toggleControl('Missing spans', {
group: LIST,
description:
"Sets hasMissingSpans on the trace summary, which shows the missing spans banner above the span drawer's trace views.",
value: false,
}),
spanLogs: choiceControl<SpanLogsState>('Span logs', {
group: LIST,
description:
@@ -243,6 +275,9 @@ export const tracesMocks = defineStoryMocks({
traceId: String(req.params.traceId),
count: values.spans,
...listWindow,
totalSpansCount:
values.traceSize === 'small' ? undefined : FLAMEGRAPH_SPAN_LIMIT + 1,
hasMissingSpans: values.missingSpans,
})
: null;
@@ -252,6 +287,38 @@ export const tracesMocks = defineStoryMocks({
},
),
rest.post(
'http://localhost/api/v4/traces/:traceId/waterfall',
(req, res, ctx) => {
const waterfall = traceWaterfallResponse({
traceId: String(req.params.traceId),
count: values.spans,
errors: values.errors,
...listWindow,
});
return waterfall
? res(ctx.status(200), ctx.json(waterfall))
: res(ctx.status(404), ctx.json({ status: 'error' }));
},
),
rest.post(
'http://localhost/api/v3/traces/:traceId/flamegraph',
(req, res, ctx) => {
const flamegraph = traceFlamegraphResponse({
traceId: String(req.params.traceId),
count: values.spans,
errors: values.errors,
...listWindow,
});
return flamegraph
? res(ctx.status(200), ctx.json(flamegraph))
: res(ctx.status(404), ctx.json({ status: 'error' }));
},
),
// The drawer's percentile panel dereferences this preference without a guard.
rest.get(
'http://localhost/api/v1/user/preferences/:name',
@@ -391,6 +458,28 @@ export const listsOrdersSpan = (args: TracesArgs): boolean =>
args.dataState === 'loaded' &&
args.spans >= ORDERS_SPAN_ROWS;
/** What the drawer shows for the span in the url: its operation, or `not found`. Null when the url opens none. */
export const drawerUrlSpanOf = (args: TracesArgs): string | null => {
if (
args.drawerUrl === 'none' ||
args.tab !== 'explorer' ||
args.view !== ExplorerViews.LIST ||
args.dataState !== 'loaded'
) {
return null;
}
if (args.drawerUrl === 'unknown trace' || args.spans < ORDERS_SPAN_ROWS) {
return 'not found';
}
// Without a summary the trace views 404 too, so only a list row can show the span.
if (args.traceSummary === 'not found' && args.drawerUrl !== 'list row') {
return 'not found';
}
return args.drawerUrl === 'outside the list'
? ORDERS_CHILD_OPERATION
: ORDERS_OPERATION;
};
/** What the drawer's Logs tab settles on, from the two controls that decide it. */
export type DrawerLogs =
| 'waiting'

View File

@@ -7,10 +7,16 @@ import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
import {
drawerLogsOf,
drawerUrlSpanOf,
listsOrdersSpan,
type TracesArgs,
} from '../TracesModulePage.stories.mocks';
import { ORDERS_OPERATION, ORDERS_SPAN_ROWS, spanOperationAt } from './traces';
import {
ORDERS_OPERATION,
ORDERS_SPAN_ROWS,
ordersTraceIds,
spanOperationAt,
} from './traces';
interface PlayContext {
args: TracesArgs;
@@ -23,6 +29,9 @@ interface MountContext extends PlayContext {
/** The page fetches before it renders its rows, which outlasts the 1s default. */
const untilLoaded = { timeout: 15_000 };
/** The card's gap from its row is a few pixels; the panel's offset would push it far past this. */
const MAX_CARD_GAP_PX = 60;
// 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> =>
@@ -44,6 +53,14 @@ const openDrawer = async (): Promise<HTMLElement> => {
return screen.findByTestId('span-details-drawer');
};
/** The waterfall row of a span the list doesn't show. */
const findChildRow = (drawer: HTMLElement): Promise<HTMLElement> =>
within(drawer).findByTestId(
`cell-0-${ordersTraceIds().childSpanId}`,
undefined,
untilLoaded,
);
const openLogsTab = async (): Promise<HTMLElement> => {
const drawer = await openDrawer();
@@ -89,6 +106,17 @@ export const openSpanDetails = async ({
}: MountContext): Promise<void> => {
await mount();
await showsSpanDetails({ args });
// The flame graph is the drawer's first view.
if (
listsOrdersSpan(args) &&
args.traceSummary === 'found' &&
args.traceSize === 'small'
) {
await expect(
await screen.findByTestId('flamegraph-canvas', undefined, untilLoaded),
).toBeVisible();
}
};
export const hoverOrdersRow = async ({
@@ -248,3 +276,134 @@ export const stepToNextSpan = async ({
),
).toBeVisible();
};
export const showsWaterfallTab = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
// The tabs wait for the span count, and a trace without a summary has no pane.
if (!listsOrdersSpan(args) || args.traceSummary !== 'found') {
return;
}
const drawer = await openDrawer();
await userEvent.click(
await within(drawer).findByTestId(
'span-drawer-trace-view-button-waterfall',
undefined,
untilLoaded,
),
);
const childRow = await findChildRow(drawer);
await expect(childRow).toBeVisible();
// The card opens beside the row, not where the drawer's panel offsets it.
await userEvent.hover(childRow);
const card = await screen.findByTestId(
'span-hover-card-duration',
undefined,
untilLoaded,
);
const rowRight = childRow.getBoundingClientRect().right;
const cardLeft = card.getBoundingClientRect().left;
await expect(cardLeft).toBeGreaterThanOrEqual(rowRight);
await expect(cardLeft).toBeLessThan(rowRight + MAX_CARD_GAP_PX);
};
export const showsWaterfallOnly = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
if (
!listsOrdersSpan(args) ||
args.traceSummary !== 'found' ||
args.traceSize === 'small'
) {
return;
}
const drawer = await openDrawer();
await expect(
await within(drawer).findByTestId(
'span-drawer-trace-view-button-flamegraph',
undefined,
untilLoaded,
),
).toHaveAttribute('aria-disabled', 'true');
await expect(await findChildRow(drawer)).toBeVisible();
};
export const showsMissingSpansBanner = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
if (!listsOrdersSpan(args) || args.traceSummary !== 'found') {
return;
}
const pane = await within(await openDrawer()).findByTestId(
'span-drawer-trace-pane',
undefined,
untilLoaded,
);
if (!args.missingSpans) {
// The counts come from the same summary, so the banner would be up by now.
await within(pane).findByTestId('trace-counts', undefined, untilLoaded);
await expect(within(pane).queryByTestId('missing-spans-banner')).toBeNull();
return;
}
await expect(
await within(pane).findByTestId(
'missing-spans-banner',
undefined,
untilLoaded,
),
).toBeVisible();
};
/** No row click: the url opens the drawer. */
export const showsUrlSpan = async ({
mount,
args,
}: MountContext): Promise<void> => {
await mount();
const expected = drawerUrlSpanOf(args);
if (!expected) {
return;
}
const drawer = await screen.findByTestId(
'span-details-drawer',
undefined,
untilLoaded,
);
if (expected === 'not found') {
await expect(
await within(drawer).findByTestId('trace-no-data', undefined, untilLoaded),
).toBeVisible();
return;
}
await expect(
(await within(drawer).findAllByText(expected, undefined, untilLoaded))[0],
).toBeVisible();
// ↑/↓ step from a list row, so a span the list doesn't show has none.
if (args.drawerUrl === 'outside the list') {
await expect(
within(drawer).queryByTestId('span-drawer-nav'),
).not.toBeInTheDocument();
}
};

View File

@@ -16,9 +16,13 @@ import {
TelemetrytypesSignalDTO,
} from 'api/generated/services/sigNoz.schemas';
import type {
GetFlamegraph200,
GetQuickFilters200,
GetTraceSummary200,
GetWaterfallV4200,
ListSavedViews200,
SpantypesFlamegraphSpanDTO,
SpantypesWaterfallSpanDTO,
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import { ExplorerViews } from 'pages/LogsExplorer/utils';
@@ -231,18 +235,30 @@ export type TraceSummaryState = (typeof TRACE_SUMMARY_STATES)[number];
const TRACE_PADDING_MS = 250;
/** Null for a trace the list never showed. */
export const traceSummaryResponse = ({
traceId,
count,
start,
end,
}: Pick<SpanRowsOptions, 'count' | 'start' | 'end'> & {
type TraceOptions = Pick<SpanRowsOptions, 'count' | 'start' | 'end'> & {
traceId: string;
}): GetTraceSummary200 | null => {
const index = rowWindow({ count, offset: 0, limit: count }).find(
};
/** The row whose trace this is, if the list showed it. */
const listedRowOf = ({ traceId, count }: TraceOptions): number | undefined =>
rowWindow({ count, offset: 0, limit: count }).find(
(i) => traceIdAt(i) === traceId,
);
/** Null for a trace the list never showed. */
export const traceSummaryResponse = (
options: TraceOptions & {
totalSpansCount?: number;
hasMissingSpans?: boolean;
},
): GetTraceSummary200 | null => {
const {
start,
end,
totalSpansCount = SPANS.length,
hasMissingSpans = false,
} = options;
const index = listedRowOf(options);
if (index === undefined) {
return null;
}
@@ -257,13 +273,188 @@ export const traceSummaryResponse = ({
rootServiceName: SPANS[0].service,
rootServiceEntryPoint: SPANS[0].operation,
rootSpanStatusCode: '200',
totalSpansCount: SPANS.length,
totalSpansCount,
totalErrorSpansCount: SPANS.filter(({ failing }) => failing).length,
hasMissingSpans: false,
hasMissingSpans,
},
};
};
/** The other spans of a row's trace, which the list never shows. */
const otherSpanIdAt = (index: number, position: number): string =>
hex('b83d5f', index * SPANS.length + position);
interface TraceSpan {
spanId: string;
parentSpanId: string;
shape: SpanShape;
level: number;
startMs: number;
durationMs: number;
hasError: boolean;
}
/**
* A row's trace: the row's span as the root, and one child per other span shape,
* all inside the window its summary reports.
*/
const traceSpansOf = (
index: number,
{ start, end, errors }: Pick<SpanRowsOptions, 'start' | 'end' | 'errors'>,
): TraceSpan[] => {
const rowShape = index % SPANS.length;
const rootId = spanIdAt(index);
const rootStart = new Date(timestampAt(index, start, end)).getTime();
const rootDuration = SPANS[rowShape].durationMs;
return SPANS.map((shape, position) => {
const isRoot = position === rowShape;
const offset = isRoot ? 0 : (rootDuration * (position + 1)) / 20;
return {
spanId: isRoot ? rootId : otherSpanIdAt(index, position),
parentSpanId: isRoot ? '' : rootId,
shape,
level: isRoot ? 0 : 1,
startMs: rootStart + offset,
durationMs: isRoot ? rootDuration : (rootDuration - offset) / 2,
hasError: errors && shape.failing,
};
}).sort((a, b) => a.level - b.level);
};
/** A span of the orders row's trace that the list doesn't show. */
export const ORDERS_CHILD_OPERATION = SPANS[0].operation;
export const ordersTraceIds = (): { traceId: string; childSpanId: string } => ({
traceId: traceIdAt(ORDERS_SPAN_ROWS - 1),
childSpanId: otherSpanIdAt(ORDERS_SPAN_ROWS - 1, 0),
});
const ordersSpanId = (): string => spanIdAt(ORDERS_SPAN_ROWS - 1);
const waterfallSpan = (
traceId: string,
span: TraceSpan,
): SpantypesWaterfallSpanDTO => ({
span_id: span.spanId,
trace_id: traceId,
parent_span_id: span.parentSpanId,
time_unix: Math.round(span.startMs),
duration_nano: Math.round(span.durationMs * 1_000_000),
name: span.shape.operation,
has_error: span.hasError,
status_code_string: span.hasError ? 'Error' : 'Ok',
response_status_code: span.hasError ? '503' : '200',
has_children: span.level === 0,
sub_tree_node_count: span.level === 0 ? SPANS.length - 1 : 0,
level: span.level,
attributes: {},
resource: { 'service.name': span.shape.service },
events: [],
references: [],
http_method: span.shape.method,
});
/** Every span of the trace, which puts the waterfall in its all-loaded mode. Null for a trace the list never showed. */
export const traceWaterfallResponse = (
options: TraceOptions & Pick<SpanRowsOptions, 'errors'>,
): GetWaterfallV4200 | null => {
const index = listedRowOf(options);
if (index === undefined) {
return null;
}
const spans = traceSpansOf(index, options);
const [root] = spans;
return {
status: 'success',
data: {
spans: spans.map((span) => waterfallSpan(options.traceId, span)),
hasMissingSpans: false,
hasMore: false,
uncollapsedSpans: [root.spanId],
startTimestampMillis: Math.round(root.startMs),
endTimestampMillis: Math.round(root.startMs + root.durationMs),
totalSpansCount: spans.length,
totalErrorSpansCount: spans.filter(({ hasError }) => hasError).length,
rootServiceName: root.shape.service,
rootServiceEntryPoint: root.shape.operation,
},
};
};
const flamegraphSpan = (span: TraceSpan): SpantypesFlamegraphSpanDTO => ({
spanId: span.spanId,
parentSpanId: span.parentSpanId,
name: span.shape.operation,
timestamp: Math.round(span.startMs),
durationNano: Math.round(span.durationMs * 1_000_000),
hasError: span.hasError,
level: span.level,
attributes: {},
resource: { 'service.name': span.shape.service },
scope: {},
event: [],
});
/** The flamegraph asks for its spans grouped by level, one array per level. Null for a trace the list never showed. */
export const traceFlamegraphResponse = (
options: TraceOptions & Pick<SpanRowsOptions, 'errors'>,
): GetFlamegraph200 | null => {
const index = listedRowOf(options);
if (index === undefined) {
return null;
}
const spans = traceSpansOf(index, options);
const [root] = spans;
return {
status: 'success',
data: {
spans: [0, 1].map((level) =>
spans.filter((span) => span.level === level).map(flamegraphSpan),
),
hasMore: false,
startTimestampMillis: Math.round(root.startMs),
endTimestampMillis: Math.round(root.startMs + root.durationMs),
},
};
};
export const DRAWER_URL_STATES = [
'none',
'list row',
'outside the list',
'unknown span',
'unknown trace',
] as const;
export type DrawerUrlState = (typeof DRAWER_URL_STATES)[number];
/** The `traceId`/`spanId` params that open the span drawer from the url. */
export const drawerUrlParams = (
state: DrawerUrlState,
): Record<string, string> => {
const { traceId, childSpanId } = ordersTraceIds();
switch (state) {
case 'list row':
return { traceId, spanId: ordersSpanId() };
case 'outside the list':
return { traceId, spanId: childSpanId };
case 'unknown span':
return { traceId, spanId: 'ffffffffffffffff' };
case 'unknown trace':
return { traceId: 'ffffffffffffffffffffffffffffffff', spanId: childSpanId };
default:
return {};
}
};
export const TRACE_SIZES = ['small', 'over the flame graph limit'] as const;
export type TraceSize = (typeof TRACE_SIZES)[number];
export const SPAN_LOGS_STATES = [
'span',
'trace only',

View File

@@ -7,10 +7,14 @@ import {
hoverOrdersRow,
openSpanDetails,
showsLogsError,
showsMissingSpansBanner,
showsNoLogs,
showsSpanLogs,
showsTraceOnlyLogs,
showsTraceSummaryLoading,
showsUrlSpan,
showsWaterfallOnly,
showsWaterfallTab,
showsWithoutTraceSummary,
stepToNextSpan,
} from '../__story_mockdata__/spanDrawer.play';
@@ -22,9 +26,10 @@ type TracesArgs = PageStoryArgs<typeof tracesMocks>;
const pageStory = storyMocks(tracesMocks, { layout: 'app' });
/**
* The span details drawer the explorer list opens on a row, one story per state
* of its trace summary and its Logs tab. Every story opens the same failing
* span; the Trace summary and Span logs controls pick what the drawer gets.
* The span details drawer the explorer list opens on a row, with the span's trace
* as a flame graph or a waterfall above its details. One story per state of the
* trace views, the url, the trace summary and the Logs tab; the controls pick
* what the drawer gets.
*
* Route: `/traces-explorer`.
*/
@@ -61,6 +66,49 @@ export const ArrowKeyNext: Story = {
play: stepToNextSpan,
};
/** The Waterfall tab, which lists the trace's other spans under the open one. */
export const WaterfallTab: Story = {
play: showsWaterfallTab,
};
/** A trace over the flame graph's span limit: only the waterfall is offered. */
export const OverFlamegraphLimit: Story = {
args: { traceSize: 'over the flame graph limit' },
play: showsWaterfallOnly,
};
/** A trace still ingesting: the summary reports missing spans, so a banner sits above the trace views. */
export const MissingSpans: Story = {
args: { missingSpans: true },
play: showsMissingSpansBanner,
};
/** A refresh or a shared link: the url opens the drawer on a list row, with ↑/↓ from it. */
export const OpenedFromUrl: Story = {
args: { drawerUrl: 'list row' },
play: showsUrlSpan,
};
/** The url names a span of the trace that the list doesn't show; it loads from the trace, without ↑/↓. */
export const SpanOutsideList: Story = {
args: { drawerUrl: 'outside the list' },
play: showsUrlSpan,
};
/** The url names a span id the trace doesn't have, so the drawer opens on the trace's root span. */
export const UnknownSpan: Story = {
args: { drawerUrl: 'unknown span' },
play: showsUrlSpan,
};
/** The url names a trace that doesn't exist: the trace page's not-found state. */
export const UnknownTrace: Story = {
args: { drawerUrl: 'unknown trace' },
// The deliberate 404s are the state under test.
parameters: { allowConsoleErrors: true },
play: showsUrlSpan,
};
/** The Logs tab with the span's logs, between the logs just before and after them. */
export const Logs: Story = {
args: { spanLogs: 'span' },
@@ -80,8 +128,9 @@ export const NoLogs: Story = {
};
/**
* The trace summary 404s, so the drawer speaks only for the span: no % exec
* time, logs over the span's own window and no trace-wide logs check.
* The trace summary 404s, so the drawer speaks only for the span: no trace
* views, no % exec time, logs over the span's own window and no trace-wide
* logs check.
*/
export const WithoutTraceSummary: Story = {
args: { traceSummary: 'not found', spanLogs: 'none' },

View File

@@ -34,7 +34,8 @@ class ResizeObserverMock {
global.ResizeObserver = ResizeObserverMock as unknown as typeof ResizeObserver;
const queryClient = new QueryClient({
/** The client `AllTheProviders` mounts, cleared after each test; seed or read its cache through it. */
export const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,

View File

@@ -5,7 +5,7 @@
* A nuqs write defaults to `shallow: true`, which means it calls
* `history.replaceState` and stops there. `nuqs/adapters/react-router/v7` only
* calls the router's `navigate()` when a write opts into `shallow: false`, and
* nothing here does. A `replaceState` made behind the router's back fires no
* most writes don't. A `replaceState` made behind the router's back fires no
* `popstate`, so the router's location does not move. That is nuqs working as
* designed, not a version problem: the v5 -> v6 -> v7 migrations did not change
* it and the adapter swap does not either.