Compare commits

...

3 Commits

Author SHA1 Message Date
Aditya Singh
c8f9bdcacc feat(traces-explorer): show the trace in the span drawer 2026-11-20 12:21:16 +05:30
Aditya Singh
5d9a6a6914 feat(tanstack-table): add an onRowHover row callback 2026-11-20 12:21:13 +05:30
Aditya Singh
bfba7f4853 feat(trace-details): share waterfall data and cache trace queries 2026-11-20 12:21:03 +05:30
38 changed files with 1672 additions and 372 deletions

View File

@@ -35,10 +35,12 @@ function TanStackCustomTableRow<TData, TItemKey = string>({
const setHovered = useSetRowHovered(rowId);
const clearHovered = useClearRowHovered(rowId);
const onRowHover = context?.onRowHover;
const handleMouseEnter = useCallback((): void => {
chromePerformanceTanstackTableBeginHover(rowId);
setHovered();
}, [rowId, setHovered]);
onRowHover?.(rowData);
}, [rowId, setHovered, onRowHover, rowData]);
useLayoutEffect(() => {
chromePerformanceMeasureTanstackTable('Row render', renderStart, {
@@ -142,6 +144,10 @@ function areTableRowPropsEqual<TData, TItemKey = string>(
return false;
}
if (prev.context?.onRowHover !== next.context?.onRowHover) {
return false;
}
if (prev.context !== next.context) {
const prevActive = prev.context?.isRowActive?.(prevData) ?? false;
const nextActive = next.context?.isRowActive?.(nextData) ?? false;

View File

@@ -101,6 +101,7 @@ function TanStackTableInner<TData, TItemKey = string>(
renderRowActions,
onRowClick,
onRowClickNewTab,
onRowHover,
onSort,
activeRowIndex,
renderExpandedRow,
@@ -401,6 +402,7 @@ function TanStackTableInner<TData, TItemKey = string>(
renderRowActions,
onRowClick,
onRowClickNewTab,
onRowHover,
renderExpandedRow,
getRowKeyData,
colCount: visibleColumnsCount,
@@ -419,6 +421,7 @@ function TanStackTableInner<TData, TItemKey = string>(
renderRowActions,
onRowClick,
onRowClickNewTab,
onRowHover,
renderExpandedRow,
getRowKeyData,
visibleColumnsCount,

View File

@@ -96,6 +96,8 @@ export type TableRowContext<TData, TItemKey = string> = {
onRowClick?: (row: TData, itemKey: TItemKey, context: RowClickContext) => void;
/** Called when ctrl+click or cmd+click on a row */
onRowClickNewTab?: (row: TData, itemKey: TItemKey) => void;
/** Called when the pointer enters a row. */
onRowHover?: (row: TData) => void;
renderExpandedRow?: (
row: TData,
rowKey: string,
@@ -190,6 +192,8 @@ export type TanStackTableProps<TData, TItemKey = string> = {
onRowClick?: (row: TData, itemKey: TItemKey, context: RowClickContext) => void;
/** Called when ctrl+click or cmd+click on a row */
onRowClickNewTab?: (row: TData, itemKey: TItemKey) => void;
/** Called when the pointer enters a row. */
onRowHover?: (row: TData) => void;
activeRowIndex?: number;
renderExpandedRow?: (
row: TData,

View File

@@ -48,4 +48,5 @@ export enum LOCALSTORAGE {
ALERT_RULES_LIST_VIEWS = 'ALERT_RULES_LIST_VIEWS',
DASHBOARD_V2_PANEL_COLUMN_WIDTHS = 'DASHBOARD_V2_PANEL_COLUMN_WIDTHS',
LLM_ATTRIBUTE_MAPPING_TEST_SPAN = 'LLM_ATTRIBUTE_MAPPING_TEST_SPAN',
SPAN_DRAWER_TRACE_LAYOUT = 'SPAN_DRAWER_TRACE_LAYOUT',
}

View File

@@ -137,7 +137,7 @@ function ListView({
}, [isLoading, isFetching, setIsLoadingQueries]);
const { tableProps, openTraceColumn, drawerProps, onPressInside } =
useSpanDrawer(rows);
useSpanDrawer(rows, isLoading);
const columns = useMemo<TableColumnDef<TracesTableRow>[]>(() => {
const fields = [

View File

@@ -0,0 +1,60 @@
import type { UseTraceWaterfallDataResult } from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import TraceFlamegraph from 'pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph';
import TraceWaterfall from 'pages/TraceDetailsV3/TraceWaterfall/TraceWaterfall';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import TraceViewLoader from './TraceViewLoader';
export type DrawerTraceViewProps = {
traceId: string;
waterfall: UseTraceWaterfallDataResult;
totalSpansCount: number | undefined;
totalErrorSpansCount: number | undefined;
/** The drawer's span; the waterfall may not be loaded to supply it. */
selectedSpan: SpanV3 | undefined;
};
const NO_FILTERED_SPANS: string[] = [];
const VIEW_LOADER = <TraceViewLoader />;
export function DrawerWaterfall({
traceId,
waterfall,
}: DrawerTraceViewProps): 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={VIEW_LOADER}
/>
);
}
export function DrawerFlamegraph({
traceId,
totalSpansCount,
selectedSpan,
}: DrawerTraceViewProps): JSX.Element {
return (
<TraceFlamegraph
traceId={traceId}
filteredSpanIds={NO_FILTERED_SPANS}
isFilterActive={false}
selectedSpan={selectedSpan}
totalSpansCount={totalSpansCount ?? 0}
loadingFallback={VIEW_LOADER}
/>
);
}

View File

@@ -5,6 +5,7 @@ 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 { TRACE_QUERY_STALE_TIME_MS } from 'hooks/trace/constants';
import type { UseRowNavigationResult } from 'components/TanStackTableView/useRowNavigation';
import {
logOpenTraceClicked,
@@ -12,39 +13,106 @@ import {
} from 'container/TracesExplorer/events';
import { getTraceLink } from 'container/TracesExplorer/ListView/utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { useTraceWaterfallData } from 'pages/TraceDetailsV3/hooks/useTraceWaterfallData';
import { SpanDetailVariant } from 'pages/TraceDetailsV3/SpanDetailsPanel/constants';
import SpanDetailsPanel from 'pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel';
import { FLAMEGRAPH_SPAN_LIMIT } from 'pages/TraceDetailsV3/TraceFlamegraph/constants';
import { openInNewTab } from 'utils/navigation';
import SpanDrawerTracePane from './SpanDrawerTracePane';
import SpanDrawerTraceSection from './SpanDrawerTraceSection';
import { useArrowKeyNavigation } from './useArrowKeyNavigation';
import { toSpanV3 } from './utils';
import { useDrawerTraceLayout } from './useDrawerTraceLayout';
import { useDrawerSpan } from './useDrawerSpan';
export type SpanDrawerProps = {
row: TracesTableRow | null;
traceId: string | null;
spanId: string | null;
onClose: () => void;
navigation: UseRowNavigationResult;
/** Null when the open span is not a row of the list. */
navigation: UseRowNavigationResult | null;
/** The list row of the open span; shown until the waterfall's copy loads. */
seedRow: TracesTableRow | null;
/** The list's first load; until it settles a missing `seedRow` is not final. */
isListLoading?: boolean;
};
const noop = (): void => {};
function SpanDrawer({
row,
traceId,
spanId,
onClose,
navigation,
seedRow,
isListLoading = false,
}: SpanDrawerProps): JSX.Element {
const { goToPrev, goToNext, isPrevDisabled, isNextDisabled } = navigation;
const isOpen = row !== null;
const isOpen = !!traceId && !!spanId;
useArrowKeyNavigation({ enabled: isOpen, onPrev: goToPrev, onNext: goToNext });
useArrowKeyNavigation({
enabled: isOpen && !!navigation,
onPrev: navigation?.goToPrev ?? noop,
onNext: navigation?.goToNext ?? noop,
});
const panelState = useMemo(
() => ({ isOpen, open: (): void => {}, close: onClose }),
[isOpen, onClose],
);
const { data: traceSummary, isLoading: isTraceBoundsLoading } =
useGetTraceSummary(
{ traceID: traceId ?? '' },
{
query: {
enabled: !!traceId,
retry: false,
staleTime: TRACE_QUERY_STALE_TIME_MS,
},
},
);
// No trace view mounts before the span count says whether the flame graph fits.
const layout = useDrawerTraceLayout({
traceId,
hasFlamegraph: isTraceBoundsLoading
? undefined
: (traceSummary?.data?.totalSpansCount ?? 0) <= FLAMEGRAPH_SPAN_LIMIT,
});
const { isSplitLayout, toggleLayout } = layout;
// A list row already carries the full span, so the waterfall is fetched only
// to show it, or for a span the list doesn't have once the list has loaded.
const isWaterfallNeeded =
layout.isWaterfallShown || (!seedRow && !isListLoading);
const waterfall = useTraceWaterfallData(traceId ?? '', {
enabled: isWaterfallNeeded,
});
const { span, isStale } = useDrawerSpan({
traceId,
spanId,
waterfallSpans: waterfall.allSpans,
seedRow,
});
const headerActions = useMemo((): HeaderAction[] => {
if (!row) {
if (!traceId || !spanId) {
return [];
}
return [
const actions: HeaderAction[] = [
{
key: 'layout',
component: (
<Button
variant="ghost"
color="secondary"
size="md"
onClick={toggleLayout}
testId="span-drawer-layout-toggle"
>
{isSplitLayout ? 'Split' : 'Stacked'}
</Button>
),
},
{
key: 'view-full-trace',
component: (
@@ -55,7 +123,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,7 +131,9 @@ function SpanDrawer({
</Button>
),
},
{
];
if (navigation) {
actions.push({
key: 'nav',
component: (
<ButtonGroup
@@ -76,43 +146,56 @@ function SpanDrawer({
value: 'prev',
icon: <ChevronUp />,
ariaLabel: 'Previous span',
onClick: goToPrev,
disabled: isPrevDisabled,
onClick: navigation.goToPrev,
disabled: navigation.isPrevDisabled,
disabledTooltip: 'No previous span on this page',
},
{
value: 'next',
icon: <ChevronDown />,
ariaLabel: 'Next span',
onClick: goToNext,
disabled: isNextDisabled,
onClick: navigation.goToNext,
disabled: navigation.isNextDisabled,
disabledTooltip: 'No next span on this page',
},
]}
/>
),
},
];
}, [row, goToPrev, goToNext, isPrevDisabled, isNextDisabled]);
});
}
return actions;
}, [traceId, spanId, navigation, isSplitLayout, toggleLayout]);
const span = useMemo(() => (row ? toSpanV3(row) : undefined), [row]);
const traceId = span?.trace_id ?? '';
const { data: traceSummary, isLoading: isTraceBoundsLoading } =
useGetTraceSummary(
{ traceID: traceId },
{ query: { enabled: !!traceId, retry: false } },
);
const traceViewProps = traceId
? {
traceId,
waterfall,
totalSpansCount: traceSummary?.data?.totalSpansCount,
totalErrorSpansCount: traceSummary?.data?.totalErrorSpansCount,
selectedSpan: isStale ? undefined : span,
}
: null;
return (
<SpanDetailsPanel
panelState={panelState}
selectedSpan={span}
isStale={isStale}
variant={SpanDetailVariant.DRAWER}
headerActions={headerActions}
traceStartTime={traceSummary?.data?.startTimestampMillis}
traceEndTime={traceSummary?.data?.endTimestampMillis}
isTraceBoundsLoading={isTraceBoundsLoading}
tracePane={
traceViewProps && isSplitLayout ? (
<SpanDrawerTracePane viewProps={traceViewProps} layout={layout} />
) : null
}
traceSection={
traceViewProps && !isSplitLayout ? (
<SpanDrawerTraceSection viewProps={traceViewProps} layout={layout} />
) : null
}
/>
);
}

View File

@@ -0,0 +1,87 @@
import { ToggleGroup } from '@signozhq/ui/toggle-group';
import { ChartNoAxesGantt, Flame } from '@signozhq/icons';
import TraceStoreSync from 'pages/TraceDetailsV3/stores/TraceStoreSync';
import { ResizableBox } from 'periscope/components/ResizableBox';
import {
DrawerFlamegraph,
DrawerTraceViewProps,
DrawerWaterfall,
} from './DrawerTraceViews';
import { FLAMEGRAPH_UNAVAILABLE_TOOLTIP } from './constants';
import TraceCounts from './TraceCounts';
import TraceViewLoader from './TraceViewLoader';
import type { DrawerTraceLayout, TraceView } from './useDrawerTraceLayout';
import styles from './SpanDrawerTraceSection.module.scss';
type SpanDrawerTracePaneProps = {
viewProps: DrawerTraceViewProps;
layout: DrawerTraceLayout;
};
/** Split layout: one trace view above the span details, each scrolling on its own. */
function SpanDrawerTracePane({
viewProps,
layout,
}: SpanDrawerTracePaneProps): JSX.Element {
const { splitView, isPending, areTabsShown, hasFlamegraph } = layout;
let view = <TraceViewLoader />;
if (!isPending) {
view =
splitView === 'waterfall' ? (
<DrawerWaterfall {...viewProps} />
) : (
<DrawerFlamegraph {...viewProps} />
);
}
return (
<TraceStoreSync>
<div className={styles.pane}>
<div className={styles.paneToolbar}>
{areTabsShown && (
<ToggleGroup
variant="outlined"
color="secondary"
type="single"
size="sm"
value={splitView}
onChange={(next: string): void => {
if (next) {
layout.setSplitView(next as TraceView);
}
}}
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.paneSpacer} />
<TraceCounts
totalSpansCount={viewProps.totalSpansCount}
totalErrorSpansCount={viewProps.totalErrorSpansCount}
/>
</div>
<ResizableBox defaultHeight={320} minHeight={120} maxHeight={640}>
{view}
</ResizableBox>
</div>
</TraceStoreSync>
);
}
export default SpanDrawerTracePane;

View File

@@ -0,0 +1,109 @@
// Matches the span AI messages accordion (MessagesAccordion).
.root {
display: flex;
flex-direction: column;
gap: var(--spacing-4);
flex-shrink: 0;
min-width: 0;
}
.panel {
// The trace views paint their own surfaces in --l1-background; the drawer is --l2.
--l1-background: var(--l2-background);
border: 1px solid var(--l2-border);
border-radius: var(--radius-2);
background: var(--l2-background);
overflow: hidden;
}
.panelHeader {
display: flex;
align-items: center;
gap: var(--spacing-4);
width: 100%;
height: 40px;
padding: 0 var(--spacing-4);
border: none;
background: transparent;
cursor: pointer;
text-align: left;
&:focus:not(:focus-visible) {
outline: none;
}
&.disabled {
cursor: not-allowed;
opacity: 0.6;
}
}
.panelTitle {
display: flex;
flex: 1;
align-items: center;
gap: var(--spacing-2);
font-size: var(--periscope-font-size-base);
color: var(--l1-foreground);
}
.panelMeta {
font-size: var(--periscope-font-size-small);
color: var(--l2-foreground);
}
.counts {
display: flex;
align-items: center;
gap: var(--spacing-6);
font-size: var(--periscope-font-size-small);
color: var(--l2-foreground);
}
.countItem {
display: inline-flex;
align-items: center;
gap: var(--spacing-2);
}
.hasErrors {
color: var(--destructive);
}
.chevron {
display: flex;
color: var(--l2-foreground);
}
.panelBody {
border-top: 1px solid var(--l2-border);
}
// Split layout: fixed above the scrolling span details.
.pane {
--l1-background: var(--l2-background);
flex-shrink: 0;
border-bottom: 1px solid var(--l2-border);
background: var(--l2-background);
}
.paneToolbar {
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);
}
.paneSpacer {
flex: 1;
}
.viewLoader {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
color: var(--l2-foreground);
}

View File

@@ -0,0 +1,71 @@
import { ChartNoAxesGantt, Flame } from '@signozhq/icons';
import TraceStoreSync from 'pages/TraceDetailsV3/stores/TraceStoreSync';
import { ResizableBox } from 'periscope/components/ResizableBox';
import {
DrawerFlamegraph,
DrawerTraceViewProps,
DrawerWaterfall,
} from './DrawerTraceViews';
import { FLAMEGRAPH_UNAVAILABLE_TOOLTIP } from './constants';
import TraceCounts from './TraceCounts';
import TraceSectionPanel from './TraceSectionPanel';
import TraceViewLoader from './TraceViewLoader';
import type { DrawerTraceLayout } from './useDrawerTraceLayout';
import styles from './SpanDrawerTraceSection.module.scss';
type SpanDrawerTraceSectionProps = {
viewProps: DrawerTraceViewProps;
layout: DrawerTraceLayout;
};
function SpanDrawerTraceSection({
viewProps,
layout,
}: SpanDrawerTraceSectionProps): JSX.Element {
const { isPending } = layout;
const counts = (
<TraceCounts
totalSpansCount={viewProps.totalSpansCount}
totalErrorSpansCount={viewProps.totalErrorSpansCount}
/>
);
return (
<TraceStoreSync>
<div className={styles.root}>
<TraceSectionPanel
icon={<Flame size={14} />}
disabledTooltip={
layout.hasFlamegraph ? undefined : FLAMEGRAPH_UNAVAILABLE_TOOLTIP
}
title="Flame Graph"
meta={counts}
isOpen={layout.isFlamegraphOpen}
onToggle={layout.toggleFlamegraphOpen}
testId="span-drawer-flamegraph-toggle"
>
<ResizableBox defaultHeight={240} minHeight={100} maxHeight={400}>
{isPending ? <TraceViewLoader /> : <DrawerFlamegraph {...viewProps} />}
</ResizableBox>
</TraceSectionPanel>
<TraceSectionPanel
icon={<ChartNoAxesGantt size={14} />}
title="Waterfall"
meta={counts}
isOpen={layout.isWaterfallOpen}
onToggle={layout.toggleWaterfallOpen}
testId="span-drawer-waterfall-toggle"
>
<ResizableBox defaultHeight={300} minHeight={150} maxHeight={600}>
{isPending ? <TraceViewLoader /> : <DrawerWaterfall {...viewProps} />}
</ResizableBox>
</TraceSectionPanel>
</div>
</TraceStoreSync>
);
}
export default SpanDrawerTraceSection;

View File

@@ -0,0 +1,34 @@
import { ChartNoAxesGantt, TriangleAlert } from '@signozhq/icons';
import cx from 'classnames';
import styles from './SpanDrawerTraceSection.module.scss';
type TraceCountsProps = {
totalSpansCount: number | undefined;
totalErrorSpansCount: number | undefined;
};
function TraceCounts({
totalSpansCount,
totalErrorSpansCount,
}: TraceCountsProps): JSX.Element | null {
if (totalSpansCount === undefined) {
return null;
}
const errors = totalErrorSpansCount ?? 0;
return (
<span className={styles.counts} data-testid="span-drawer-trace-counts">
<span className={styles.countItem}>
<ChartNoAxesGantt size={13} />
Spans: {totalSpansCount}
</span>
<span className={cx(styles.countItem, { [styles.hasErrors]: errors > 0 })}>
<TriangleAlert size={13} />
Errors: {errors}
</span>
</span>
);
}
export default TraceCounts;

View File

@@ -0,0 +1,60 @@
import { ReactNode } from 'react';
import { Tooltip } from '@signozhq/ui/tooltip';
import { ChevronDown, ChevronUp } from '@signozhq/icons';
import cx from 'classnames';
import styles from './SpanDrawerTraceSection.module.scss';
type TraceSectionPanelProps = {
icon: ReactNode;
title: string;
meta?: ReactNode;
isOpen: boolean;
onToggle: () => void;
testId: string;
/** Set when the section can't be opened; shown on hover. */
disabledTooltip?: string;
/** Mounted only while open. */
children: ReactNode;
};
function TraceSectionPanel({
icon,
title,
meta,
isOpen,
onToggle,
testId,
disabledTooltip,
children,
}: TraceSectionPanelProps): JSX.Element {
const isDisabled = !!disabledTooltip;
const header = (
<button
type="button"
className={cx(styles.panelHeader, { [styles.disabled]: isDisabled })}
onClick={isDisabled ? undefined : onToggle}
aria-expanded={isOpen}
aria-disabled={isDisabled}
data-testid={testId}
>
<span className={styles.panelTitle}>
{icon}
{title}
</span>
{meta && <span className={styles.panelMeta}>{meta}</span>}
<span className={styles.chevron}>
{isOpen ? <ChevronUp size={14} /> : <ChevronDown size={14} />}
</span>
</button>
);
return (
<section className={styles.panel}>
{isDisabled ? <Tooltip title={disabledTooltip}>{header}</Tooltip> : header}
{isOpen && <div className={styles.panelBody}>{children}</div>}
</section>
);
}
export default TraceSectionPanel;

View File

@@ -0,0 +1,18 @@
import { Spinner } from '@signozhq/ui/spinner';
import styles from './SpanDrawerTraceSection.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>
);
}
export default TraceViewLoader;

View File

@@ -0,0 +1,92 @@
import { act, renderHook } from 'tests/test-utils';
import { useDrawerTraceLayout } from '../useDrawerTraceLayout';
type Args = Parameters<typeof useDrawerTraceLayout>[0];
function renderLayout(
initialProps: Args,
): ReturnType<
typeof renderHook<ReturnType<typeof useDrawerTraceLayout>, Args>
> {
return renderHook((args: Args) => useDrawerTraceLayout(args), {
initialProps,
});
}
describe('useDrawerTraceLayout', () => {
beforeEach(() => {
localStorage.clear();
});
it('shows the waterfall in the split pane when the trace has no flame graph', () => {
const { result, rerender } = renderLayout({
traceId: 'trace-a',
hasFlamegraph: true,
});
act(() => result.current.toggleLayout());
expect(result.current.splitView).toBe('flamegraph');
expect(result.current.isWaterfallShown).toBe(false);
rerender({ traceId: 'trace-a', hasFlamegraph: false });
expect(result.current.splitView).toBe('waterfall');
expect(result.current.isWaterfallShown).toBe(true);
rerender({ traceId: 'trace-a', hasFlamegraph: true });
expect(result.current.splitView).toBe('flamegraph');
});
it('closes an opened flame graph section on a trace without one', () => {
const { result, rerender } = renderLayout({
traceId: 'trace-a',
hasFlamegraph: true,
});
act(() => result.current.toggleFlamegraphOpen());
expect(result.current.isFlamegraphOpen).toBe(true);
rerender({ traceId: 'trace-a', hasFlamegraph: false });
expect(result.current.isFlamegraphOpen).toBe(false);
});
it('shows no view and no tabs until the first span count loads', () => {
const { result, rerender } = renderLayout({
traceId: 'trace-a',
hasFlamegraph: undefined,
});
expect(result.current.isPending).toBe(true);
expect(result.current.areTabsShown).toBe(false);
expect(result.current.isWaterfallShown).toBe(false);
rerender({ traceId: 'trace-a', hasFlamegraph: true });
expect(result.current.isPending).toBe(false);
expect(result.current.areTabsShown).toBe(true);
expect(result.current.isWaterfallShown).toBe(true);
});
it('keeps the last trace tabs while the next trace count loads', () => {
const { result, rerender } = renderLayout({
traceId: 'trace-a',
hasFlamegraph: false,
});
act(() => result.current.toggleLayout());
rerender({ traceId: 'trace-b', hasFlamegraph: undefined });
expect(result.current.isPending).toBe(true);
expect(result.current.areTabsShown).toBe(true);
expect(result.current.hasFlamegraph).toBe(false);
expect(result.current.splitView).toBe('waterfall');
rerender({ traceId: 'trace-b', hasFlamegraph: true });
expect(result.current.splitView).toBe('flamegraph');
});
it('hides the tabs again once the drawer closes', () => {
const { result, rerender } = renderLayout({
traceId: 'trace-a',
hasFlamegraph: true,
});
rerender({ traceId: null, hasFlamegraph: true });
rerender({ traceId: 'trace-b', hasFlamegraph: undefined });
expect(result.current.areTabsShown).toBe(false);
});
});

View File

@@ -1,4 +1,5 @@
import { act, renderHook } from 'tests/test-utils';
import { rest, server } from 'mocks-server/server';
import { act, AllTheProviders, renderHook, waitFor } from 'tests/test-utils';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { useSpanDrawer } from '../useSpanDrawer';
@@ -8,37 +9,112 @@ jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
useQueryBuilder: (): unknown => ({ stagedQuery: { id: mockQueryId } }),
}));
const rows: TracesTableRow[] = [{ id: 'span-a' }, { id: 'span-b' }];
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' },
];
describe('useSpanDrawer', () => {
beforeEach(() => {
mockQueryId = 'query-1';
});
it('does not reopen a span that a refetch dropped and a later one brings back', () => {
it('keeps a span open after its row leaves the list, without row navigation', () => {
const { result, rerender } = renderHook(
({ current }: { current: TracesTableRow[] }) => useSpanDrawer(current),
{ initialProps: { current: rows } },
{ initialProps: { current: rows }, wrapper: AllTheProviders },
);
act(() => result.current.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawerProps?.row).toBe(rows[1]);
expect(result.current.drawerProps.spanId).toBe('span-b');
expect(result.current.drawerProps.navigation).not.toBeNull();
rerender({ current: [rows[0]] });
expect(result.current.drawerProps?.row).toBeNull();
rerender({ current: rows });
expect(result.current.drawerProps?.row).toBeNull();
expect(result.current.drawerProps.traceId).toBe('trace-1');
expect(result.current.drawerProps.spanId).toBe('span-b');
expect(result.current.drawerProps.navigation).toBeNull();
});
it('closes on a new query while the old rows are still shown', () => {
const { result, rerender } = renderHook(() => useSpanDrawer(rows));
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 } = renderHook(() => useSpanDrawer(withDuplicate), {
wrapper: AllTheProviders,
});
act(() => result.current.tableProps.onRowClick?.(withDuplicate[0]));
act(() => result.current.drawerProps.navigation?.goToNext());
expect(result.current.tableProps.activeRowIndex).toBe(1);
act(() => result.current.drawerProps.navigation?.goToNext());
expect(result.current.drawerProps.spanId).toBe('span-b');
});
it('closes on a new query', () => {
const { result, rerender } = renderHook(() => useSpanDrawer(rows), {
wrapper: AllTheProviders,
});
act(() => result.current.tableProps.onRowClick?.(rows[1]));
expect(result.current.drawerProps?.row).toBe(rows[1]);
expect(result.current.drawerProps.spanId).toBe('span-b');
mockQueryId = 'query-2';
rerender();
expect(result.current.drawerProps?.row).toBeNull();
expect(result.current.drawerProps.spanId).toBeNull();
});
describe('summary prefetch', () => {
const threeTraces: TracesTableRow[] = [
{ id: 'row-1', trace_id: 'trace-1', span_id: 'span-1' },
{ id: 'row-2', trace_id: 'trace-2', span_id: 'span-2' },
{ id: 'row-3', trace_id: 'trace-3', span_id: 'span-3' },
];
let requestedTraceIds: string[];
beforeEach(() => {
requestedTraceIds = [];
server.use(
rest.get('*/api/v1/traces/:traceID/summary', (req, res, ctx) => {
requestedTraceIds.push(String(req.params.traceID));
return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
}),
);
});
afterEach(() => {
jest.useRealTimers();
});
it('fetches the summaries of the traces ↑/↓ lead to', async () => {
const { result } = renderHook(() => useSpanDrawer(threeTraces), {
wrapper: AllTheProviders,
});
act(() => result.current.tableProps.onRowClick?.(threeTraces[1]));
await waitFor(() =>
expect([...requestedTraceIds].sort()).toStrictEqual(['trace-1', 'trace-3']),
);
});
it('fetches the summary of the row the pointer rests on', async () => {
jest.useFakeTimers();
const { result } = renderHook(() => useSpanDrawer(threeTraces), {
wrapper: AllTheProviders,
});
act(() => {
result.current.tableProps.onRowHover?.(threeTraces[0]);
jest.advanceTimersByTime(50);
result.current.tableProps.onRowHover?.(threeTraces[2]);
jest.advanceTimersByTime(200);
});
jest.useRealTimers();
await waitFor(() => expect(requestedTraceIds).toStrictEqual(['trace-3']));
});
});
});

View File

@@ -0,0 +1,2 @@
export const FLAMEGRAPH_UNAVAILABLE_TOOLTIP =
'Flame graph is not available for traces over 100k spans';

View File

@@ -0,0 +1,61 @@
import { useMemo, useState } from 'react';
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { toSpanV3 } from './utils';
type UseDrawerSpanParams = {
traceId: string | null;
spanId: string | null;
waterfallSpans: SpanV3[];
/** The list row of the open span, if it is one. */
seedRow: TracesTableRow | null;
};
type UseDrawerSpanResult = {
span: SpanV3 | undefined;
/** `span` is the previously shown one; the requested span is still loading. */
isStale: boolean;
};
/**
* Picks the span to show: the waterfall's copy, else the list row's, else the
* last span shown until the requested one loads.
*/
export function useDrawerSpan({
traceId,
spanId,
waterfallSpans,
seedRow,
}: UseDrawerSpanParams): UseDrawerSpanResult {
const loadedSpan = useMemo(
() => waterfallSpans.find((s) => s.span_id === spanId),
[waterfallSpans, spanId],
);
const seedSpan = useMemo(
() =>
seedRow && seedRow.trace_id === traceId && seedRow.span_id === spanId
? toSpanV3(seedRow)
: undefined,
[seedRow, traceId, spanId],
);
const currentSpan = loadedSpan ?? seedSpan;
const isOpen = !!traceId && !!spanId;
const [lastShownSpan, setLastShownSpan] = useState<SpanV3>();
if (currentSpan && currentSpan !== lastShownSpan) {
setLastShownSpan(currentSpan);
} else if (!isOpen && lastShownSpan) {
setLastShownSpan(undefined);
}
if (currentSpan) {
return { span: currentSpan, isStale: false };
}
if (isOpen && lastShownSpan) {
return { span: lastShownSpan, isStale: true };
}
return { span: undefined, isStale: false };
}

View File

@@ -0,0 +1,86 @@
import { useCallback, useState } from 'react';
import getLocalStorageKey from 'api/browser/localstorage/get';
import setLocalStorageKey from 'api/browser/localstorage/set';
import { LOCALSTORAGE } from 'constants/localStorage';
export type TraceView = 'waterfall' | 'flamegraph';
export type DrawerTraceLayout = {
/** The open trace's span count hasn't loaded, so no view is mounted yet. */
isPending: boolean;
/** Split layout: false until a span count has loaded since the drawer opened. */
areTabsShown: boolean;
/** False above the flame graph limit; only the waterfall is offered. */
hasFlamegraph: boolean;
isSplitLayout: boolean;
toggleLayout: () => void;
/** Split layout: the one view shown in the pane. */
splitView: TraceView;
setSplitView: (view: TraceView) => void;
/** Stacked layout: which sections are expanded. */
isWaterfallOpen: boolean;
toggleWaterfallOpen: () => void;
isFlamegraphOpen: boolean;
toggleFlamegraphOpen: () => void;
/** The waterfall is on screen in the current layout. */
isWaterfallShown: boolean;
};
type UseDrawerTraceLayoutArgs = {
traceId: string | null;
/** Undefined until the open trace's span count has loaded. */
hasFlamegraph: boolean | undefined;
};
/** POC: the stacked sections vs the split pane, and what each shows. */
export function useDrawerTraceLayout({
traceId,
hasFlamegraph,
}: UseDrawerTraceLayoutArgs): DrawerTraceLayout {
const [isSplitLayout, setIsSplitLayout] = useState(
() => getLocalStorageKey(LOCALSTORAGE.SPAN_DRAWER_TRACE_LAYOUT) === 'split',
);
const [splitView, setSplitView] = useState<TraceView>('flamegraph');
const [isWaterfallOpen, setIsWaterfallOpen] = useState(true);
const [isFlamegraphOpen, setIsFlamegraphOpen] = useState(false);
// Moving to another trace keeps the last trace's tabs until its count loads.
const [lastHasFlamegraph, setLastHasFlamegraph] = useState(hasFlamegraph);
const nextLastHasFlamegraph = traceId
? (hasFlamegraph ?? lastHasFlamegraph)
: undefined;
if (nextLastHasFlamegraph !== lastHasFlamegraph) {
setLastHasFlamegraph(nextLastHasFlamegraph);
}
const toggleLayout = useCallback((): void => {
const next = !isSplitLayout;
setLocalStorageKey(
LOCALSTORAGE.SPAN_DRAWER_TRACE_LAYOUT,
next ? 'split' : 'stacked',
);
setIsSplitLayout(next);
}, [isSplitLayout]);
const isPending = !!traceId && hasFlamegraph === undefined;
const shownHasFlamegraph = nextLastHasFlamegraph ?? true;
const shownSplitView: TraceView = shownHasFlamegraph ? splitView : 'waterfall';
const isWaterfallShown =
!isPending &&
(isSplitLayout ? shownSplitView === 'waterfall' : isWaterfallOpen);
return {
isPending,
areTabsShown: nextLastHasFlamegraph !== undefined,
hasFlamegraph: shownHasFlamegraph,
isSplitLayout,
toggleLayout,
splitView: shownSplitView,
setSplitView,
isWaterfallOpen,
toggleWaterfallOpen: (): void => setIsWaterfallOpen((open) => !open),
isFlamegraphOpen: shownHasFlamegraph && isFlamegraphOpen,
toggleFlamegraphOpen: (): void => setIsFlamegraphOpen((open) => !open),
isWaterfallShown,
};
}

View File

@@ -0,0 +1,20 @@
import { useCallback } from 'react';
import { useQueryClient } from 'react-query';
import { getGetTraceSummaryQueryOptions } from 'api/generated/services/tracedetail';
import { TRACE_QUERY_STALE_TIME_MS } from 'hooks/trace/constants';
/** Loads a trace's summary into the cache the drawer reads, unless it's already fresh. */
export function usePrefetchTraceSummary(): (traceId: string) => void {
const queryClient = useQueryClient();
return useCallback(
(traceId: string): void => {
void queryClient.prefetchQuery(
getGetTraceSummaryQueryOptions(
{ traceID: traceId },
{ query: { retry: false, staleTime: TRACE_QUERY_STALE_TIME_MS } },
),
);
},
[queryClient],
);
}

View File

@@ -12,16 +12,17 @@ import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldCol
import type { TracesTableProps } from 'container/TracesExplorer/TracesTable/TracesTable';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useCloseOnOutsidePress } from 'hooks/useCloseOnOutsidePress';
import { parseAsString, useQueryStates } from 'nuqs';
import { SELECTED_SPAN_ID_PARAM } from 'pages/TraceDetailsV3/hooks/useSelectedSpanId';
import { OPEN_TRACE_COLUMN } from './openTraceColumn';
import type { SpanDrawerProps } from './SpanDrawer';
type ActiveSpan = { id: string; index: number };
import { usePrefetchTraceSummary } from './usePrefetchTraceSummary';
type UseSpanDrawerResult = {
tableProps: Pick<
TracesTableProps,
'onRowClick' | 'isRowActive' | 'activeRowIndex'
'onRowClick' | 'isRowActive' | 'activeRowIndex' | 'onRowHover'
>;
/** Leading column that opens the trace page. */
openTraceColumn: TableColumnDef<TracesTableRow>;
@@ -30,44 +31,66 @@ 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);
// Long enough that a pointer crossing the list doesn't fetch every row it passes.
const HOVER_PREFETCH_DELAY_MS = 150;
// `spanId` is shared with the trace views (useSelectedSpanId); same options.
const spanDrawerParams = {
traceId: parseAsString,
[SELECTED_SPAN_ID_PARAM]: parseAsString,
};
export function useSpanDrawer(
rows: TracesTableRow[],
isListLoading = false,
): UseSpanDrawerResult {
const [{ traceId, spanId }, setSpanDrawerParams] = useQueryStates(
spanDrawerParams,
{ shallow: false },
);
// The ids alone can't tell duplicate rows (a span stored twice) apart, so
// navigation steps from the row it last opened while that row still matches.
const [rowIndexHint, setRowIndexHint] = useState<number | null>(null);
const activeRowIndex = useMemo(() => {
if (!activeSpan) {
if (!traceId || !spanId) {
return -1;
}
return rows[activeSpan.index]?.id === activeSpan.id
? activeSpan.index
: rows.findIndex((row) => row.id === activeSpan.id);
}, [rows, activeSpan]);
const isOpenSpan = (row: TracesTableRow | undefined): boolean =>
row?.trace_id === traceId && row?.span_id === spanId;
if (rowIndexHint !== null && isOpenSpan(rows[rowIndexHint])) {
return rowIndexHint;
}
return rows.findIndex(isOpenSpan);
}, [rows, traceId, spanId, rowIndexHint]);
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 });
setRowIndexHint(index);
void setSpanDrawerParams({
traceId: String(row.trace_id),
spanId: String(row.span_id),
});
},
[],
[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 => {
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]);
const isOpen = !!traceId && !!spanId;
// A new query closes the drawer at once instead of waiting for its rows.
const { stagedQuery } = useQueryBuilder();
@@ -75,33 +98,61 @@ export function useSpanDrawer(rows: TracesTableRow[]): UseSpanDrawerResult {
const lastQueryIdRef = useRef(queryId);
useEffect(() => {
if (lastQueryIdRef.current && lastQueryIdRef.current !== queryId) {
setActiveSpan(null);
closeDrawer();
}
lastQueryIdRef.current = queryId;
}, [queryId]);
}, [queryId, closeDrawer]);
const onPressInside = useCloseOnOutsidePress(
activeRowIndex !== -1,
clearActiveSpan,
const onPressInside = useCloseOnOutsidePress(isOpen, closeDrawer);
// The span count decides the drawer's trace views, so it is fetched before a
// row opens: on hover, and for the rows ↑/↓ lead to.
const prefetchTraceSummary = usePrefetchTraceSummary();
const hoverTimerRef = useRef<number>();
const onRowHover = useCallback(
(row: TracesTableRow): void => {
window.clearTimeout(hoverTimerRef.current);
hoverTimerRef.current = window.setTimeout(
() => prefetchTraceSummary(String(row.trace_id)),
HOVER_PREFETCH_DELAY_MS,
);
},
[prefetchTraceSummary],
);
useEffect(() => (): void => window.clearTimeout(hoverTimerRef.current), []);
useEffect(() => {
if (activeRowIndex === -1) {
return;
}
[rows[activeRowIndex - 1], rows[activeRowIndex + 1]].forEach((row) => {
if (row && row.trace_id !== traceId) {
prefetchTraceSummary(String(row.trace_id));
}
});
}, [rows, activeRowIndex, traceId, prefetchTraceSummary]);
const navigation = useRowNavigation({
rows,
activeIndex: activeRowIndex,
onNavigate: handleNavigate,
onNavigate: openSpan,
});
return {
tableProps: {
onRowClick: selectRow,
onRowClick: openRow,
isRowActive,
activeRowIndex,
onRowHover,
},
openTraceColumn: OPEN_TRACE_COLUMN,
drawerProps: {
row: rows[activeRowIndex] ?? null,
onClose: clearActiveSpan,
navigation,
traceId: isOpen ? traceId : null,
spanId: isOpen ? spanId : null,
onClose: closeDrawer,
navigation: activeRowIndex === -1 ? null : navigation,
seedRow: rows[activeRowIndex] ?? null,
isListLoading,
},
onPressInside,
};

View File

@@ -38,6 +38,7 @@ export type TracesTableProps = {
/** Replaces the default row click, which opens the trace detail page. */
onRowClick?: (row: TracesTableRow) => void;
isRowActive?: (row: TracesTableRow) => boolean;
onRowHover?: (row: TracesTableRow) => void;
activeRowIndex?: number;
isLoading: boolean;
isFetching: boolean;
@@ -61,6 +62,7 @@ function TracesTable({
getRowHref,
onRowClick,
isRowActive,
onRowHover,
activeRowIndex,
isLoading,
isFetching,
@@ -149,6 +151,7 @@ function TracesTable({
onRowClick={handleRowClick}
onRowClickNewTab={handleRowClickNewTab}
isRowActive={isRowActive}
onRowHover={onRowHover}
activeRowIndex={activeRowIndex}
getRowKey={getRowKey}
getRowTestId={(row): string => `traces-table-row-${row.id}`}
@@ -175,6 +178,7 @@ TracesTable.defaultProps = {
respectColumnOrder: false,
onRowClick: undefined,
isRowActive: undefined,
onRowHover: undefined,
activeRowIndex: undefined,
onColumnOrderChange: undefined,
onColumnRemove: undefined,

View File

@@ -0,0 +1,2 @@
/** Trace data is immutable once ingested; reopening a trace serves it from cache. */
export const TRACE_QUERY_STALE_TIME_MS = 5 * 60 * 1000;

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 { TRACE_QUERY_STALE_TIME_MS } from './constants';
export interface GetTraceFlamegraphV3Props {
traceId: string;
selectedSpanId?: string;
@@ -37,6 +39,7 @@ const useGetTraceFlamegraphV3 = (
enabled: props.enabled,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: TRACE_QUERY_STALE_TIME_MS,
});
export default useGetTraceFlamegraphV3;

View File

@@ -2,12 +2,21 @@ import { useQuery, UseQueryResult } from 'react-query';
import getTraceV4 from 'api/trace/getTraceV4';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { TRACE_QUERY_STALE_TIME_MS } from './constants';
import {
GetTraceV4PayloadProps,
GetTraceV4SuccessResponse,
} from 'types/api/trace/getTraceV3';
const useGetTraceV4 = (props: GetTraceV4PayloadProps): UseTraceV4 =>
type UseGetTraceV4Options = {
/** Defaults to true; the query also needs a trace id. */
enabled?: boolean;
};
const useGetTraceV4 = (
props: GetTraceV4PayloadProps,
{ enabled = true }: UseGetTraceV4Options = {},
): UseTraceV4 =>
useQuery({
queryFn: () => getTraceV4(props),
queryKey: [
@@ -16,9 +25,10 @@ const useGetTraceV4 = (props: GetTraceV4PayloadProps): UseTraceV4 =>
props.selectedSpanId,
props.isSelectedSpanIDUnCollapsed,
],
enabled: !!props.traceId,
enabled: enabled && !!props.traceId,
keepPreviousData: true,
refetchOnWindowFocus: false,
staleTime: TRACE_QUERY_STALE_TIME_MS,
});
type UseTraceV4 = UseQueryResult<

View File

@@ -9,6 +9,58 @@
}
}
.contentFrame {
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;
}
@keyframes spanLoading {
0% {
opacity: 0.3;
transform: scaleX(0.3);
transform-origin: left;
}
50% {
opacity: 1;
transform: scaleX(1);
transform-origin: left;
}
100% {
opacity: 0.3;
transform: scaleX(0.3);
transform-origin: right;
}
}
.loadingBar {
height: 2px;
flex-shrink: 0;
background: var(--primary);
animation: spanLoading 1.5s ease-in-out infinite;
}
.skeletonPills {
--skeleton-input-min-width-small: 0;
display: flex;
flex-wrap: wrap;
gap: var(--spacing-2);
}
// Same height as the trace section headers.
.skeletonSection {
--skeleton-input-height: 40px;
}
.panelBody {
padding: 12px;
display: flex;
@@ -112,6 +164,12 @@
}
.drawerPanel {
// Wider than the widest drawer preset (extra-wide, 51.25rem) to fit the
// flamegraph and waterfall; the doubled class outranks the preset rule.
&.panel[data-width] {
max-width: min(75vw, 72rem);
}
.panelBody,
.logsFooter,
:global(.pretty-view__search-wrapper) {

View File

@@ -1,8 +1,7 @@
import { useCallback, useMemo, useState } from 'react';
import { ReactNode, useCallback, useMemo, useState } from 'react';
import { Badge } from '@signozhq/ui/badge';
import { Tabs, type TabsItemProps } from '@signozhq/ui/tabs';
import { Bookmark, ChartColumnBig, List, ScrollText } from '@signozhq/icons';
import { Skeleton } from 'antd';
import cx from 'classnames';
import { DetailsHeader, DetailsPanelDrawer } from 'components/DetailsPanel';
import { HeaderAction } from 'components/DetailsPanel/DetailsHeader/DetailsHeader';
@@ -50,6 +49,7 @@ import OpenInLogsExplorer from './SpanLogs/OpenInLogsExplorer';
import SpanLogs from './SpanLogs/SpanLogs';
import { useSpanContextLogs } from './SpanLogs/useSpanContextLogs';
import SpanAIMessages from './SpanAIMessages/SpanAIMessages';
import SpanDetailsSkeleton from './SpanDetailsSkeleton';
import SpanDrawerHeader from './SpanDrawerHeader';
import SpanSummary from './SpanSummary';
@@ -66,6 +66,12 @@ interface SpanDetailsPanelProps {
traceEndTime?: number;
/** The trace bounds are still being fetched; logs wait for them. */
isTraceBoundsLoading?: boolean;
/** Rendered under the span summary. */
traceSection?: ReactNode;
/** Rendered between the header and the scrolling details. */
tracePane?: ReactNode;
/** `selectedSpan` is the previous span, kept dimmed while the next one loads. */
isStale?: boolean;
}
// At/above this panel width the summary moves inside the Overview tab (bottom
@@ -80,11 +86,13 @@ function SpanDetailsContent({
traceStartTime,
traceEndTime,
isTraceBoundsLoading = false,
traceSection,
}: {
selectedSpan: SpanV3;
traceStartTime?: number;
traceEndTime?: number;
isTraceBoundsLoading?: boolean;
traceSection?: ReactNode;
}): JSX.Element {
const [bodyRef, { width: bodyWidth }] = useMeasure<HTMLDivElement>();
const spanAttributeActions = useSpanAttributeActions();
@@ -326,6 +334,7 @@ function SpanDetailsContent({
children: (
<>
{isWide && summary}
{isWide && <div className={styles.tabAiMessages}>{traceSection}</div>}
{isWide && <div className={styles.tabAiMessages}>{aiMessages}</div>}
<DataViewer
data={spanDisplayData}
@@ -398,6 +407,7 @@ function SpanDetailsContent({
<>
<div className={styles.panelBody} ref={bodyRef}>
{!isWide && <div className={styles.detailsSection}>{summary}</div>}
{!isWide && traceSection}
{!isWide && aiMessages}
<div className={styles.tabsSection}>
@@ -437,6 +447,9 @@ function SpanDetailsPanel({
traceStartTime,
traceEndTime,
isTraceBoundsLoading,
traceSection,
tracePane,
isStale = false,
}: SpanDetailsPanelProps): JSX.Element {
const headerActions = useMemo((): HeaderAction[] => {
const actions: HeaderAction[] = [
@@ -495,17 +508,22 @@ function SpanDetailsPanel({
}
/>
)}
{tracePane}
{selectedSpan ? (
<SpanDetailsContent
selectedSpan={selectedSpan}
traceStartTime={traceStartTime}
traceEndTime={traceEndTime}
isTraceBoundsLoading={isTraceBoundsLoading}
/>
) : (
<div className={styles.panelBody}>
<Skeleton active paragraph={{ rows: 6 }} title={{ width: '60%' }} />
<div className={styles.contentFrame} aria-busy={isStale}>
{isStale && <div className={styles.loadingBar} />}
<div className={cx(styles.contentFrame, { [styles.stale]: isStale })}>
<SpanDetailsContent
selectedSpan={selectedSpan}
traceStartTime={traceStartTime}
traceEndTime={traceEndTime}
isTraceBoundsLoading={isTraceBoundsLoading}
traceSection={traceSection}
/>
</div>
</div>
) : (
<SpanDetailsSkeleton />
)}
</>
);

View File

@@ -0,0 +1,32 @@
import { Skeleton } from '@signozhq/ui/skeleton';
import styles from './SpanDetailsPanel.module.scss';
const PILL_WIDTHS = [96, 120, 88, 132];
/** Placeholder shaped like the span summary, trace sections and tabs. */
function SpanDetailsSkeleton(): JSX.Element {
return (
<div className={styles.panelBody} data-testid="span-details-skeleton">
<Skeleton
active
title={{ width: '55%' }}
paragraph={{ rows: 1, width: '35%' }}
/>
<div className={styles.skeletonPills}>
{PILL_WIDTHS.map((width) => (
<Skeleton.Input key={width} active size="small" style={{ width }} />
))}
</div>
<Skeleton.Input active block className={styles.skeletonSection} />
<Skeleton.Input active block className={styles.skeletonSection} />
<Skeleton
active
title={{ width: '30%' }}
paragraph={{ rows: 4, width: ['100%', '90%', '95%', '70%'] }}
/>
</div>
);
}
export default SpanDetailsSkeleton;

View File

@@ -1,5 +1,6 @@
import { useGetTraceSummary } from 'api/generated/services/tracedetail';
import type { SpantypesGettableTraceSummaryDTO } from 'api/generated/services/sigNoz.schemas';
import { TRACE_QUERY_STALE_TIME_MS } from 'hooks/trace/constants';
interface UseTraceSummaryResult {
data: SpantypesGettableTraceSummaryDTO | undefined;
@@ -9,7 +10,13 @@ interface UseTraceSummaryResult {
export function useTraceSummary(traceId: string): UseTraceSummaryResult {
const { data, isLoading } = useGetTraceSummary(
{ traceID: traceId },
{ query: { enabled: !!traceId, keepPreviousData: true } },
{
query: {
enabled: !!traceId,
keepPreviousData: true,
staleTime: TRACE_QUERY_STALE_TIME_MS,
},
},
);
return { data: data?.data, isLoading };

View File

@@ -1,12 +1,5 @@
/* 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,
@@ -20,23 +13,18 @@ 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 { 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 { useTraceStore } from '../stores/traceStore';
import {
SPAN_DETAILS_PANEL_MIN_WIDTH,
SpanDetailVariant,
@@ -45,9 +33,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,20 +62,22 @@ 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 {
traceData,
isFetchingTraceData,
errorFetchingTraceData,
allSpans,
totalSpansCount,
isFullDataLoaded,
interestedSpanId,
setInterestedSpanId,
uncollapsedNodes,
localUncollapsedNodes,
setLocalUncollapsedNodes,
selectedSpan,
setSelectedSpan,
selectedSpanId,
} = useTraceWaterfallData(traceId || '');
const { safeNavigate } = useSafeNavigate();
const logTraceEvent = useTraceDetailLogEvent('v3', traceId || '');
@@ -115,83 +102,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 +142,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 => {

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

@@ -1,4 +1,4 @@
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';
@@ -33,6 +33,8 @@ interface ITraceWaterfallProps {
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,6 +102,9 @@ 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 }} />
@@ -144,6 +150,7 @@ function TraceWaterfall(props: ITraceWaterfallProps): JSX.Element {
interestedSpanId,
isFilterActive,
isFullDataLoaded,
loadingFallback,
localUncollapsedNodes,
setLocalUncollapsedNodes,
selectedSpan,

View File

@@ -33,6 +33,14 @@
min-height: 0;
display: flex;
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.
*,
*::before,
*::after {
box-sizing: border-box;
}
}
.splitPanel {
@@ -63,11 +71,6 @@
border-right: 1px solid var(--l2-border);
}
.resizeHandleHeader {
width: 4px;
flex-shrink: 0;
}
.statusHeader {
width: 50px;
flex-shrink: 0;

View File

@@ -24,8 +24,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,
@@ -677,19 +676,16 @@ function Success(props: ISuccessProps): JSX.Element {
setSelectedSpanToAddToFunnel(span);
}, []);
const { safeNavigate } = useSafeNavigate();
const [, setSelectedSpanId] = useSelectedSpanId();
const handleSpanClick = useCallback(
(span: SpanV3): void => {
setSelectedSpan(span);
const params = getUnstableCurrentSearchParams();
if (span?.span_id) {
params.set('spanId', span?.span_id);
setSelectedSpanId(span.span_id);
}
safeNavigate({ search: params.toString() }, { replace: true });
},
[setSelectedSpan, safeNavigate],
[setSelectedSpan, setSelectedSpanId],
);
// Left side columns using TanStack React Table (extensible for future columns)
@@ -848,7 +844,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 { useTraceDetailsTab } from 'pages/TraceDetailsV3/hooks/useTraceDetailsTab';
import { TraceDetailsTab } from 'pages/TraceDetailsV3/constants';
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,19 +26,8 @@ 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
@@ -228,13 +216,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 () => {
@@ -260,7 +241,7 @@ 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 spanOverview = screen.getByTestId(FIRST_SPAN_TEST_ID);
@@ -269,12 +250,7 @@ describe('Span Click User Flows', () => {
) as HTMLElement;
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 () => {
@@ -406,10 +382,6 @@ describe('Span Click User Flows', () => {
it('preserves existing URL parameters when selecting spans', async () => {
const user = userEvent.setup({ pointerEventsCheck: 0 });
// Pre-populate URL with existing parameters
mockUrlQuery.set('existingParam', 'existingValue');
mockUrlQuery.set('anotherParam', 'anotherValue');
renderWithTraceProvider(
<Success
spans={mockSpans}
@@ -426,7 +398,10 @@ describe('Span Click User Flows', () => {
isFilterActive={false}
/>,
undefined,
{ initialRoute: '/trace' },
{
initialRoute:
'/trace?existingParam=existingValue&anotherParam=anotherValue',
},
);
const spanOverview = screen.getByTestId(FIRST_SPAN_TEST_ID);
@@ -435,51 +410,60 @@ describe('Span Click User Flows', () => {
) as HTMLElement;
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({ pointerEventsCheck: 0 });
// 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"
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 spanOverview = screen.getByTestId(FIRST_SPAN_TEST_ID);
const spanElement = spanOverview.querySelector(
SPAN_OVERVIEW_CLASS,
) as HTMLElement;
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,62 @@
import { QueryClient } from 'react-query';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { toSpanV3 } from 'container/TracesExplorer/SpanDrawer/utils';
import { SuccessResponse } from 'types/api';
import { GetTraceV4SuccessResponse } from 'types/api/trace/getTraceV3';
import { getCachedFullWaterfallParams } from '../getCachedFullWaterfallParams';
function waterfallResponse(
traceId: string,
loaded: number,
total: number,
): SuccessResponse<GetTraceV4SuccessResponse> {
return {
statusCode: 200,
message: 'success',
error: null,
payload: {
spans: Array.from({ length: loaded }, (_, i) =>
toSpanV3({ id: `s${i}`, span_id: `s${i}`, trace_id: traceId }),
),
hasMissingSpans: false,
uncollapsedSpans: [],
startTimestampMillis: 0,
endTimestampMillis: 1,
totalSpansCount: total,
totalErrorSpansCount: 0,
rootServiceName: 'frontend',
rootServiceEntryPoint: 'GET /',
},
};
}
describe('getCachedFullWaterfallParams', () => {
it('returns the params of a cached response that holds every span', () => {
const queryClient = new QueryClient();
queryClient.setQueryData(
[REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL, 'trace-1', 'span-a', true],
waterfallResponse('trace-1', 3, 3),
);
expect(getCachedFullWaterfallParams(queryClient, 'trace-1')).toStrictEqual({
selectedSpanId: 'span-a',
isSelectedSpanIDUnCollapsed: true,
uncollapsedSpans: [],
});
});
it('ignores a windowed response and other traces', () => {
const queryClient = new QueryClient();
queryClient.setQueryData(
[REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL, 'trace-1', 'span-a', true],
waterfallResponse('trace-1', 2, 20_000),
);
queryClient.setQueryData(
[REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL, 'trace-2', 'span-b', true],
waterfallResponse('trace-2', 3, 3),
);
expect(getCachedFullWaterfallParams(queryClient, 'trace-1')).toBeUndefined();
});
});

View File

@@ -0,0 +1,42 @@
import { QueryClient } from 'react-query';
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
import { ErrorResponse, SuccessResponse } from 'types/api';
import { GetTraceV4SuccessResponse } from 'types/api/trace/getTraceV3';
export type WaterfallQueryParams = {
selectedSpanId: string;
isSelectedSpanIDUnCollapsed: boolean;
uncollapsedSpans: string[];
};
/** Params of a cached waterfall response that holds every span of `traceId`. */
export function getCachedFullWaterfallParams(
queryClient: QueryClient,
traceId: string,
): WaterfallQueryParams | undefined {
const entries = queryClient.getQueriesData<
SuccessResponse<GetTraceV4SuccessResponse> | ErrorResponse
>([REACT_QUERY_KEY.GET_TRACE_V4_WATERFALL, traceId]);
for (const [queryKey, data] of entries) {
const payload = data?.payload;
if (
payload &&
payload.totalSpansCount > 0 &&
payload.spans.length >= payload.totalSpansCount
) {
const [, , selectedSpanId, isSelectedSpanIDUnCollapsed] = queryKey as [
string,
string,
string,
boolean,
];
return {
selectedSpanId,
isSelectedSpanIDUnCollapsed,
uncollapsedSpans: [],
};
}
}
return undefined;
}

View File

@@ -0,0 +1,28 @@
import { useCallback } from 'react';
import { parseAsString, useQueryState } from 'nuqs';
export const SELECTED_SPAN_ID_PARAM = 'spanId';
/**
* The selected span, kept in the `spanId` URL param. Every reader of the
* selection goes through this hook so they all see a write in the same render.
* Not shallow: the thread tab still 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,278 @@
import {
Dispatch,
SetStateAction,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useQueryClient } from 'react-query';
import useGetTraceV4 from 'hooks/trace/useGetTraceV4';
import { SpanV3 } from 'types/api/trace/getTraceV3';
import { setTraceStoreAvailableColorByFields } from '../stores/traceStore';
import { useSelectedSpanId } from './useSelectedSpanId';
import { IInterestedSpan } from '../TraceWaterfall/types';
import { getAncestorSpanIds } from '../TraceWaterfall/utils';
import { getAvailableColorByFieldNames } from '../utils';
import {
getCachedFullWaterfallParams,
WaterfallQueryParams,
} from './getCachedFullWaterfallParams';
type TraceV4Result = ReturnType<typeof useGetTraceV4>;
export interface UseTraceWaterfallDataResult {
traceData: TraceV4Result['data'];
isFetchingTraceData: boolean;
errorFetchingTraceData: unknown;
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;
};
/** Waterfall data and collapse state for `traceId`; the selected span is the `spanId` URL param. */
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);
// 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<WaterfallQueryParams>({
selectedSpanId: interestedSpanId.spanId,
isSelectedSpanIDUnCollapsed: interestedSpanId.isUncollapsed,
uncollapsedSpans: uncollapsedNodes,
});
// A trace already cached in full is reused whichever span it is opened on.
const queryClient = useQueryClient();
const reuseCachedFullData = (id: string): void => {
const cachedParams = getCachedFullWaterfallParams(queryClient, id);
fullDataLoadedRef.current = !!cachedParams;
if (cachedParams) {
frozenParamsRef.current = cachedParams;
}
};
const isCacheCheckedRef = useRef(false);
if (!isCacheCheckedRef.current) {
isCacheCheckedRef.current = true;
reuseCachedFullData(traceId);
}
// A host that stays mounted across traces starts each trace from scratch.
const traceIdRef = useRef(traceId);
if (traceIdRef.current !== traceId) {
traceIdRef.current = traceId;
allSpansRef.current = [];
deepLinkResolvedRef.current = false;
reuseCachedFullData(traceId);
const spanId = urlSpanId || '';
setInterestedSpanId({ spanId, isUncollapsed: spanId !== '' });
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]);
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 show the last trace while the next loads.
const dataTraceIdRef = useRef<string>();
if (data && !isPreviousData) {
dataTraceIdRef.current = traceId;
}
const traceData = dataTraceIdRef.current === traceId ? data : undefined;
const allSpans = useMemo(
() => traceData?.payload?.spans || [],
[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(
() => (allSpans.length ? getAvailableColorByFieldNames(allSpans) : undefined),
[allSpans],
);
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,
errorFetchingTraceData,
allSpans,
totalSpansCount,
isFullDataLoaded,
interestedSpanId,
setInterestedSpanId,
uncollapsedNodes,
localUncollapsedNodes,
setLocalUncollapsedNodes,
selectedSpan,
setSelectedSpan,
selectedSpanId,
};
}