mirror of
https://github.com/SigNoz/signoz.git
synced 2026-11-04 15:31:08 +00:00
Compare commits
29 Commits
ci/e2e-nod
...
feat/trace
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7d2dad42e | ||
|
|
71e9e5aa31 | ||
|
|
5f91021c9a | ||
|
|
12eb474d57 | ||
|
|
589d99cdb6 | ||
|
|
d48659a838 | ||
|
|
bc2ac267b0 | ||
|
|
943c6434b4 | ||
|
|
6d8e79b0b6 | ||
|
|
c776817323 | ||
|
|
5b768834ef | ||
|
|
e83b7ee4bb | ||
|
|
3ae96d9e7a | ||
|
|
5985253c0f | ||
|
|
49253e032c | ||
|
|
6b8b20803c | ||
|
|
8c445c0bbd | ||
|
|
44c09ba22b | ||
|
|
c126b62f30 | ||
|
|
090ec639f8 | ||
|
|
a47997fe4d | ||
|
|
825991864d | ||
|
|
d19b9afff4 | ||
|
|
4cb022dd06 | ||
|
|
9d465d54f5 | ||
|
|
7d95fa7b25 | ||
|
|
cd1068e1c3 | ||
|
|
dca68d89bc | ||
|
|
1be806c58d |
8
.github/workflows/e2eci.yaml
vendored
8
.github/workflows/e2eci.yaml
vendored
@@ -47,7 +47,7 @@ jobs:
|
||||
- name: node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: lts/*
|
||||
- name: install-pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
@@ -67,7 +67,7 @@ jobs:
|
||||
matrix:
|
||||
project:
|
||||
- chromium
|
||||
shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
||||
shard: [1, 2, 3, 4]
|
||||
needs: changes
|
||||
if: needs.changes.outputs.e2e == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
@@ -105,7 +105,7 @@ jobs:
|
||||
- name: node
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: "22"
|
||||
node-version: lts/*
|
||||
- name: install-pnpm
|
||||
uses: pnpm/action-setup@v6
|
||||
with:
|
||||
@@ -162,7 +162,7 @@ jobs:
|
||||
- name: playwright-test
|
||||
run: |
|
||||
cd tests/e2e && \
|
||||
pnpm playwright test --project=${{ matrix.project }} --shard=${{ matrix.shard }}/10
|
||||
pnpm playwright test --project=${{ matrix.project }} --shard=${{ matrix.shard }}/4
|
||||
- name: teardown-stack
|
||||
if: always()
|
||||
run: |
|
||||
|
||||
@@ -143,7 +143,12 @@ const preview: Preview = {
|
||||
'Logs',
|
||||
['Explorer', 'Live Tail', 'Pipelines', 'Settings'],
|
||||
'Traces',
|
||||
['Explorer', 'Trace Details', 'Funnel Details'],
|
||||
[
|
||||
'Explorer',
|
||||
['Overview', 'Span Drawer'],
|
||||
'Trace Details',
|
||||
'Funnel Details',
|
||||
],
|
||||
'Metrics',
|
||||
['Explorer'],
|
||||
'Infrastructure',
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
.drawer {
|
||||
overflow: hidden;
|
||||
border-color: var(--l2-border);
|
||||
background: var(--l2-background);
|
||||
box-shadow: -4px 10px 16px 2px var(--l1-shadow);
|
||||
|
||||
&:focus,
|
||||
&:focus-visible {
|
||||
outline: none;
|
||||
}
|
||||
}
|
||||
|
||||
.body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
.details-panel-drawer {
|
||||
&__body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
import { DrawerWrapper } from '@signozhq/ui/drawer';
|
||||
import { Drawer, DrawerContent } from '@signozhq/ui/drawer';
|
||||
import cx from 'classnames';
|
||||
import { AnimatePresence } from 'motion/react';
|
||||
|
||||
import './DetailsPanelDrawer.styles.scss';
|
||||
import styles from './DetailsPanelDrawer.module.scss';
|
||||
|
||||
interface DetailsPanelDrawerProps {
|
||||
isOpen: boolean;
|
||||
onClose: () => void;
|
||||
children: React.ReactNode;
|
||||
className?: string;
|
||||
testId?: string;
|
||||
}
|
||||
|
||||
function DetailsPanelDrawer({
|
||||
@@ -14,22 +17,41 @@ function DetailsPanelDrawer({
|
||||
onClose,
|
||||
children,
|
||||
className,
|
||||
testId,
|
||||
}: DetailsPanelDrawerProps): JSX.Element {
|
||||
return (
|
||||
<DrawerWrapper
|
||||
<Drawer
|
||||
open={isOpen}
|
||||
onOpenChange={(open): void => {
|
||||
if (!open) {
|
||||
onClose();
|
||||
}
|
||||
}}
|
||||
direction="right"
|
||||
showOverlay={false}
|
||||
className={`details-panel-drawer ${className || ''}`}
|
||||
modal={false}
|
||||
>
|
||||
<div className="details-panel-drawer__body">{children}</div>
|
||||
</DrawerWrapper>
|
||||
<AnimatePresence>
|
||||
{isOpen && (
|
||||
<DrawerContent
|
||||
forceMount
|
||||
direction="right"
|
||||
width="extra-wide"
|
||||
showOverlay={false}
|
||||
// Outside presses are left to the page, which knows what counts as inside.
|
||||
onInteractOutside={(e): void => e.preventDefault()}
|
||||
className={cx(styles.drawer, className)}
|
||||
testId={testId}
|
||||
>
|
||||
<div className={styles.body}>{children}</div>
|
||||
</DrawerContent>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
</Drawer>
|
||||
);
|
||||
}
|
||||
|
||||
DetailsPanelDrawer.defaultProps = {
|
||||
className: undefined,
|
||||
testId: undefined,
|
||||
};
|
||||
|
||||
export default DetailsPanelDrawer;
|
||||
|
||||
@@ -18,6 +18,7 @@ function InputWithLabel({
|
||||
className,
|
||||
closeIcon,
|
||||
disabled,
|
||||
sanitize,
|
||||
}: {
|
||||
label: string;
|
||||
initialValue?: string | number | null;
|
||||
@@ -29,14 +30,17 @@ function InputWithLabel({
|
||||
className?: string;
|
||||
closeIcon?: React.ReactNode;
|
||||
disabled?: boolean;
|
||||
/** Rewrites the typed value before it is shown and reported. */
|
||||
sanitize?: (value: string) => string;
|
||||
}): JSX.Element {
|
||||
const [inputValue, setInputValue] = useState<string>(
|
||||
initialValue ? initialValue.toString() : '',
|
||||
);
|
||||
|
||||
const handleChange = (e: React.ChangeEvent<HTMLInputElement>): void => {
|
||||
setInputValue(e.target.value);
|
||||
onChange?.(e.target.value);
|
||||
const value = sanitize ? sanitize(e.target.value) : e.target.value;
|
||||
setInputValue(value);
|
||||
onChange?.(value);
|
||||
};
|
||||
|
||||
return (
|
||||
@@ -78,6 +82,7 @@ InputWithLabel.defaultProps = {
|
||||
initialValue: undefined,
|
||||
className: undefined,
|
||||
closeIcon: undefined,
|
||||
sanitize: undefined,
|
||||
};
|
||||
|
||||
export default InputWithLabel;
|
||||
|
||||
@@ -18,71 +18,51 @@
|
||||
right: -2px;
|
||||
width: 240px;
|
||||
|
||||
[data-format-menu='back'],
|
||||
[data-format-menu='font-option'],
|
||||
[data-format-menu='font-size'],
|
||||
[data-format-menu='edit-columns'] {
|
||||
--button-justify-content: flex-start;
|
||||
}
|
||||
|
||||
[data-format-menu='font-option'],
|
||||
[data-format-menu='font-size'],
|
||||
[data-format-menu='edit-columns'] {
|
||||
--button-label-min-width: 100%;
|
||||
--button-font-size: 13px;
|
||||
--button-variant-link-font-weight: 400;
|
||||
--button-size-line-height: 20px;
|
||||
}
|
||||
|
||||
[data-format-menu='back'] {
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
[data-format-menu='font-option'],
|
||||
[data-format-menu='font-size'] {
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.menu-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.font-size-dropdown {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 8px 12px;
|
||||
|
||||
.back-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 12px;
|
||||
border: none !important;
|
||||
box-shadow: none !important;
|
||||
|
||||
.icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.text {
|
||||
color: var(--l1-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 11px;
|
||||
font-style: normal;
|
||||
font-weight: 500;
|
||||
line-height: 20px; /* 142.857% */
|
||||
letter-spacing: 0.14px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
}
|
||||
|
||||
.back-btn:hover {
|
||||
background-color: unset !important;
|
||||
.horizontal-line {
|
||||
margin-inline: -12px;
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
.option-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
padding: 12px;
|
||||
border: none !important;
|
||||
box-shadow: none !important;
|
||||
justify-content: space-between;
|
||||
|
||||
.icon {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.text {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 13px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: normal; /* 142.857% */
|
||||
letter-spacing: 0.14px;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
|
||||
.text:hover {
|
||||
color: var(--l2-foreground);
|
||||
}
|
||||
}
|
||||
|
||||
.option-btn:hover {
|
||||
background-color: unset !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -102,31 +82,6 @@
|
||||
letter-spacing: 0.88px;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.value {
|
||||
display: flex;
|
||||
height: 20px;
|
||||
padding: 4px 0px;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border: none !important;
|
||||
.font-value {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 13px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: normal;
|
||||
letter-spacing: 0.14px;
|
||||
text-transform: capitalize;
|
||||
}
|
||||
.icon {
|
||||
}
|
||||
}
|
||||
|
||||
.value:hover {
|
||||
background-color: unset !important;
|
||||
}
|
||||
}
|
||||
|
||||
.menu-container {
|
||||
@@ -198,90 +153,10 @@
|
||||
cursor: pointer;
|
||||
}
|
||||
}
|
||||
|
||||
.max-lines-per-row-input {
|
||||
display: flex;
|
||||
|
||||
.ant-input-number-handler-wrap {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.ant-input-number {
|
||||
min-width: 36px;
|
||||
width: auto;
|
||||
border-right: none;
|
||||
border-left: none;
|
||||
border-top: 1px solid var(--l1-border);
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
text-align: center;
|
||||
height: 26px;
|
||||
border-radius: 0;
|
||||
|
||||
&:active,
|
||||
&:focus {
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
}
|
||||
}
|
||||
|
||||
.ant-input-number-focused {
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.ant-input-number-input-wrap {
|
||||
input {
|
||||
text-align: center;
|
||||
font-size: 13px;
|
||||
|
||||
&:active,
|
||||
&:focus {
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
&:active,
|
||||
&:focus {
|
||||
border: none;
|
||||
}
|
||||
}
|
||||
|
||||
.periscope-btn {
|
||||
box-shadow: none;
|
||||
padding: 6px 12px;
|
||||
height: 26px;
|
||||
|
||||
border-radius: 0px 1px 1px 0px;
|
||||
background: var(--l3-background);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.edit-columns-container {
|
||||
padding: 12px;
|
||||
|
||||
.edit-columns-btn {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
height: 20px;
|
||||
padding: 4px 0px;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
border: none !important;
|
||||
|
||||
.edit-columns-text {
|
||||
color: var(--l2-foreground);
|
||||
font-family: Inter;
|
||||
font-size: 13px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: normal;
|
||||
letter-spacing: 0.14px;
|
||||
}
|
||||
}
|
||||
|
||||
.edit-columns-btn:hover {
|
||||
background-color: unset !important;
|
||||
}
|
||||
}
|
||||
|
||||
.add-new-column-container {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Button, InputNumber, Popover, Tooltip } from 'antd';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import { Popover, Tooltip } from 'antd';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { InputNumber } from '@signozhq/ui/input-number';
|
||||
import cx from 'classnames';
|
||||
import {
|
||||
LogViewMode,
|
||||
@@ -11,13 +12,15 @@ import {
|
||||
Check,
|
||||
ChevronLeft,
|
||||
ChevronRight,
|
||||
Minus,
|
||||
Plus,
|
||||
SlidersVertical,
|
||||
} from '@signozhq/icons';
|
||||
|
||||
import './LogsFormatOptionsMenu.styles.scss';
|
||||
|
||||
const MIN_LINES_PER_ROW = 1;
|
||||
const MAX_LINES_PER_ROW = 10;
|
||||
const FONT_SIZES = [FontSize.SMALL, FontSize.MEDIUM, FontSize.LARGE];
|
||||
|
||||
interface LogsFormatOptionsMenuProps {
|
||||
items: any;
|
||||
selectedOptionFormat: any;
|
||||
@@ -62,25 +65,11 @@ function OptionsMenu({
|
||||
onChange(key);
|
||||
};
|
||||
|
||||
const incrementMaxLinesPerRow = (): void => {
|
||||
if (maxLinesPerRow < 10) {
|
||||
setMaxLinesPerRow(maxLinesPerRow + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const decrementMaxLinesPerRow = (): void => {
|
||||
if (maxLinesPerRow > 1) {
|
||||
setMaxLinesPerRow(maxLinesPerRow - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleLinesPerRowChange = (maxLinesPerRow: number | null): void => {
|
||||
if (
|
||||
maxLinesPerRow &&
|
||||
Number.isInteger(maxLinesNumber) &&
|
||||
maxLinesPerRow > 1
|
||||
) {
|
||||
setMaxLinesPerRow(maxLinesPerRow);
|
||||
const handleLinesPerRowChange = (value: number | null): void => {
|
||||
if (value !== null) {
|
||||
setMaxLinesPerRow(
|
||||
Math.min(Math.max(value, MIN_LINES_PER_ROW), MAX_LINES_PER_ROW),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -111,51 +100,36 @@ function OptionsMenu({
|
||||
{isFontSizeOptionsOpen ? (
|
||||
<div className="font-size-dropdown">
|
||||
<Button
|
||||
variant="link"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
width="100%"
|
||||
data-format-menu="back"
|
||||
testId="font-size-back"
|
||||
prefix={<ChevronLeft size={14} />}
|
||||
onClick={(): void => setIsFontSizeOptionsOpen(false)}
|
||||
className="back-btn"
|
||||
type="text"
|
||||
>
|
||||
<ChevronLeft size={14} className="icon" />
|
||||
<Typography.Text className="text">Select font size</Typography.Text>
|
||||
Select font size
|
||||
</Button>
|
||||
<div className="horizontal-line" />
|
||||
<div className="content">
|
||||
<Button
|
||||
onClick={(): void => {
|
||||
setFontSizeValue(FontSize.SMALL);
|
||||
}}
|
||||
className="option-btn"
|
||||
type="text"
|
||||
>
|
||||
<Typography.Text className="text">{FontSize.SMALL}</Typography.Text>
|
||||
{fontSizeValue === FontSize.SMALL && (
|
||||
<Check size={14} className="icon" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(): void => {
|
||||
setFontSizeValue(FontSize.MEDIUM);
|
||||
}}
|
||||
className="option-btn"
|
||||
type="text"
|
||||
>
|
||||
<Typography.Text className="text">{FontSize.MEDIUM}</Typography.Text>
|
||||
{fontSizeValue === FontSize.MEDIUM && (
|
||||
<Check size={14} className="icon" />
|
||||
)}
|
||||
</Button>
|
||||
<Button
|
||||
onClick={(): void => {
|
||||
setFontSizeValue(FontSize.LARGE);
|
||||
}}
|
||||
className="option-btn"
|
||||
type="text"
|
||||
>
|
||||
<Typography.Text className="text">{FontSize.LARGE}</Typography.Text>
|
||||
{fontSizeValue === FontSize.LARGE && (
|
||||
<Check size={14} className="icon" />
|
||||
)}
|
||||
</Button>
|
||||
{FONT_SIZES.map((size) => (
|
||||
<Button
|
||||
key={size}
|
||||
variant="link"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
width="100%"
|
||||
data-format-menu="font-option"
|
||||
testId={`font-size-option-${size}`}
|
||||
onClick={(): void => setFontSizeValue(size)}
|
||||
>
|
||||
<span className="menu-row">
|
||||
{size}
|
||||
{fontSizeValue === size && <Check size={14} />}
|
||||
</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
@@ -163,14 +137,20 @@ function OptionsMenu({
|
||||
<div className="font-size-container">
|
||||
<div className="title">Font Size</div>
|
||||
<Button
|
||||
className="value"
|
||||
type="text"
|
||||
variant="link"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
width="100%"
|
||||
data-format-menu="font-size"
|
||||
testId="font-size-select"
|
||||
onClick={(): void => {
|
||||
setIsFontSizeOptionsOpen(true);
|
||||
}}
|
||||
>
|
||||
<Typography.Text className="font-value">{fontSizeValue}</Typography.Text>
|
||||
<ChevronRight size={14} className="icon" />
|
||||
<span className="menu-row">
|
||||
{fontSizeValue}
|
||||
<ChevronRight size={14} />
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
<div className="horizontal-line" />
|
||||
@@ -200,30 +180,20 @@ function OptionsMenu({
|
||||
<div className="horizontal-line" />
|
||||
<div className="max-lines-per-row">
|
||||
<div className="title"> max lines per row </div>
|
||||
<div className="raw-format max-lines-per-row-input">
|
||||
<button
|
||||
type="button"
|
||||
className="periscope-btn"
|
||||
onClick={decrementMaxLinesPerRow}
|
||||
>
|
||||
{' '}
|
||||
<Minus size={12} />{' '}
|
||||
</button>
|
||||
<InputNumber
|
||||
min={1}
|
||||
max={10}
|
||||
value={maxLinesPerRow}
|
||||
onChange={handleLinesPerRowChange}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="periscope-btn"
|
||||
onClick={incrementMaxLinesPerRow}
|
||||
>
|
||||
{' '}
|
||||
<Plus size={12} />{' '}
|
||||
</button>
|
||||
</div>
|
||||
<InputNumber
|
||||
controls
|
||||
mode="spinner"
|
||||
size="small"
|
||||
min={MIN_LINES_PER_ROW}
|
||||
max={MAX_LINES_PER_ROW}
|
||||
precision={0}
|
||||
value={maxLinesPerRow}
|
||||
onChange={handleLinesPerRowChange}
|
||||
aria-label="Max lines per row"
|
||||
decrementAriaLabel="Fewer lines per row"
|
||||
incrementAriaLabel="More lines per row"
|
||||
testId="max-lines-per-row"
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
@@ -233,15 +203,18 @@ function OptionsMenu({
|
||||
<div className="horizontal-line" />
|
||||
<div className="edit-columns-container">
|
||||
<Button
|
||||
className="edit-columns-btn"
|
||||
type="text"
|
||||
variant="link"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
width="100%"
|
||||
data-format-menu="edit-columns"
|
||||
onClick={handleEditColumns}
|
||||
data-testid="periscope-btn-edit-columns"
|
||||
testId="periscope-btn-edit-columns"
|
||||
>
|
||||
<Typography.Text className="edit-columns-text">
|
||||
<span className="menu-row">
|
||||
Edit columns
|
||||
</Typography.Text>
|
||||
<ChevronRight size={14} className="icon" />
|
||||
<ChevronRight size={14} />
|
||||
</span>
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
@@ -280,10 +253,15 @@ function LogsFormatOptionsMenu({
|
||||
>
|
||||
<Tooltip title="Options">
|
||||
<Button
|
||||
className="periscope-btn ghost"
|
||||
icon={<SlidersVertical size="md" />}
|
||||
data-testid="periscope-btn-format-options"
|
||||
/>
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label="Options"
|
||||
testId="periscope-btn-format-options"
|
||||
>
|
||||
<SlidersVertical size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</Popover>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import { FontSize } from 'container/OptionsMenu/types';
|
||||
import { fireEvent, render, waitFor } from 'tests/test-utils';
|
||||
import {
|
||||
fireEvent,
|
||||
render,
|
||||
screen,
|
||||
userEvent,
|
||||
waitFor,
|
||||
} from 'tests/test-utils';
|
||||
|
||||
import LogsFormatOptionsMenu from '../LogsFormatOptionsMenu';
|
||||
|
||||
@@ -107,18 +113,12 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
|
||||
it('increments max-lines and calls onChange', async () => {
|
||||
const { maxLinesOnChange } = setup();
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
|
||||
// Increment max lines
|
||||
const input = document.querySelector(
|
||||
'.max-lines-per-row-input input',
|
||||
) as HTMLInputElement;
|
||||
const input = getByTestId('max-lines-per-row') as HTMLInputElement;
|
||||
const initial = Number(input.value);
|
||||
const buttons = document.querySelectorAll(
|
||||
'.max-lines-per-row-input .periscope-btn',
|
||||
);
|
||||
const incrementBtn = buttons[1] as HTMLElement;
|
||||
fireEvent.click(incrementBtn);
|
||||
fireEvent.click(screen.getByRole('button', { name: 'More lines per row' }));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(Number(input.value)).toBe(initial + 1);
|
||||
@@ -128,28 +128,46 @@ describe('LogsFormatOptionsMenu (unit)', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('clamps a typed max-lines value to 10', async () => {
|
||||
const { maxLinesOnChange, getByTestId } = setup();
|
||||
const input = getByTestId('max-lines-per-row') as HTMLInputElement;
|
||||
const user = userEvent.setup();
|
||||
|
||||
await user.clear(input);
|
||||
await user.type(input, '15');
|
||||
await user.tab();
|
||||
|
||||
await waitFor(() => expect(input.value).toBe('10'));
|
||||
expect(maxLinesOnChange).toHaveBeenLastCalledWith(10);
|
||||
});
|
||||
|
||||
it('stops max-lines at 10', async () => {
|
||||
const { getByTestId } = setup();
|
||||
const input = getByTestId('max-lines-per-row') as HTMLInputElement;
|
||||
const increment = screen.getByRole('button', { name: 'More lines per row' });
|
||||
|
||||
for (let i = 0; i < 12; i++) {
|
||||
fireEvent.click(increment);
|
||||
}
|
||||
|
||||
await waitFor(() => expect(input.value).toBe('10'));
|
||||
});
|
||||
|
||||
it('changes font size to MEDIUM and calls onChange', async () => {
|
||||
const { fontSizeOnChange } = setup();
|
||||
const { fontSizeOnChange, getByTestId } = setup();
|
||||
// Open font dropdown
|
||||
const fontButton = document.querySelector(
|
||||
'.font-size-container .value',
|
||||
) as HTMLElement;
|
||||
fireEvent.click(fontButton);
|
||||
fireEvent.click(getByTestId('font-size-select'));
|
||||
|
||||
// Choose MEDIUM
|
||||
const optionButtons = Array.from(
|
||||
document.querySelectorAll('.font-size-dropdown .option-btn'),
|
||||
);
|
||||
const mediumBtn = optionButtons[1] as HTMLElement;
|
||||
fireEvent.click(mediumBtn);
|
||||
fireEvent.click(getByTestId(`font-size-option-${FontSize.MEDIUM}`));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
document.querySelectorAll('.font-size-dropdown .option-btn .icon'),
|
||||
).toHaveLength(1);
|
||||
expect(
|
||||
(optionButtons[1] as Element).querySelector('.icon'),
|
||||
getByTestId(`font-size-option-${FontSize.MEDIUM}`).querySelector('svg'),
|
||||
).toBeInTheDocument();
|
||||
expect(
|
||||
getByTestId(`font-size-option-${FontSize.SMALL}`).querySelector('svg'),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(fontSizeOnChange).toHaveBeenCalledWith(FontSize.MEDIUM);
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
RAW_QUERY_FIELDS,
|
||||
resolveQueryBuilderFields,
|
||||
} from '../../queryBuilderFields.utils';
|
||||
import { parseLimit, sanitizeLimit } from '../../utils';
|
||||
|
||||
import BucketOptions from './BucketOptions/BucketOptions';
|
||||
import HavingFilter from './HavingFilter/HavingFilter';
|
||||
@@ -278,7 +279,7 @@ function QueryAddOns({
|
||||
|
||||
const handleChangeLimit = useCallback(
|
||||
(value: string) => {
|
||||
handleChangeQueryData('limit', Number(value) || null);
|
||||
handleChangeQueryData('limit', parseLimit(value));
|
||||
},
|
||||
[handleChangeQueryData],
|
||||
);
|
||||
@@ -374,6 +375,7 @@ function QueryAddOns({
|
||||
label="Limit"
|
||||
type="number"
|
||||
onChange={handleChangeLimit}
|
||||
sanitize={sanitizeLimit}
|
||||
initialValue={query?.limit ?? undefined}
|
||||
placeholder={placeholderOf(QueryBuilderField.Limit)}
|
||||
onClose={(): void => handleRemoveView(QueryBuilderField.Limit)}
|
||||
|
||||
@@ -169,8 +169,15 @@ describe('QueryAddOns', () => {
|
||||
expect(screen.getByTestId('limit-content')).toBeInTheDocument();
|
||||
expect(input.value).toBe('5');
|
||||
|
||||
fireEvent.change(input, { target: { value: '10' } });
|
||||
expect(mockHandleChangeQueryData).toHaveBeenCalledWith('limit', 10);
|
||||
const user = userEvent.setup();
|
||||
await user.clear(input);
|
||||
await user.type(input, '10');
|
||||
expect(mockHandleChangeQueryData).toHaveBeenLastCalledWith('limit', 10);
|
||||
|
||||
await user.clear(input);
|
||||
await user.type(input, '-5');
|
||||
expect(input.value).toBe('5');
|
||||
expect(mockHandleChangeQueryData).toHaveBeenLastCalledWith('limit', 5);
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -12,10 +12,62 @@ import {
|
||||
convertExpressionToFilters,
|
||||
convertFiltersToExpression,
|
||||
convertFiltersToExpressionWithExistingQuery,
|
||||
convertHavingToExpression,
|
||||
formatValueForExpression,
|
||||
parseLimit,
|
||||
removeKeysFromExpression,
|
||||
sanitizeLimit,
|
||||
} from '../utils';
|
||||
|
||||
describe('convertHavingToExpression', () => {
|
||||
it.each([
|
||||
['COUNT()', 'count() > 5'],
|
||||
['COUNT_DISTINCT(service.name)', 'count_distinct(service.name) > 5'],
|
||||
['P99(duration_nano)', 'p99(duration_nano) > 5'],
|
||||
['SUM(http.Request.Size)', 'sum(http.Request.Size) > 5'],
|
||||
['count()', 'count() > 5'],
|
||||
])('references %s by its lower-case function', (columnName, expected) => {
|
||||
expect(
|
||||
convertHavingToExpression([{ columnName, op: '>', value: 5 }]),
|
||||
).toStrictEqual({ expression: expected });
|
||||
});
|
||||
|
||||
it('joins several conditions and formats list values', () => {
|
||||
expect(
|
||||
convertHavingToExpression([
|
||||
{ columnName: 'COUNT()', op: '>', value: 5 },
|
||||
{ columnName: 'COUNT()', op: 'NOT IN', value: [1, 2] },
|
||||
]),
|
||||
).toStrictEqual({ expression: 'count() > 5 AND count() NOT IN [1, 2]' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('sanitizeLimit', () => {
|
||||
it.each([
|
||||
['10', '10'],
|
||||
['-10', '10'],
|
||||
['2.5', '25'],
|
||||
['1e3', '13'],
|
||||
['', ''],
|
||||
])('sanitizes %j to %j', (value, expected) => {
|
||||
expect(sanitizeLimit(value)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseLimit', () => {
|
||||
it.each([
|
||||
['10', 10],
|
||||
['1', 1],
|
||||
['', null],
|
||||
['0', null],
|
||||
['-5', null],
|
||||
['2.5', null],
|
||||
['abc', null],
|
||||
])('parses %j as %j', (value, expected) => {
|
||||
expect(parseLimit(value)).toBe(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('convertFiltersToExpression', () => {
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
|
||||
@@ -840,6 +840,16 @@ export const appendAndClause = (
|
||||
return hasTopLevelOr ? `(${base}) AND ${clause}` : `${base} AND ${clause}`;
|
||||
};
|
||||
|
||||
/** Strips everything but digits, so a limit input can't hold a sign or decimal. */
|
||||
export const sanitizeLimit = (value: string): string =>
|
||||
value.replace(/\D/g, '');
|
||||
|
||||
/** A query or formula limit: a positive integer, otherwise none. */
|
||||
export const parseLimit = (value: string): number | null => {
|
||||
const limit = Number(value);
|
||||
return Number.isInteger(limit) && limit > 0 ? limit : null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert old having format to new having format
|
||||
* @param having - Array of old having objects with columnName, op, and value
|
||||
@@ -871,7 +881,14 @@ export const convertHavingToExpression = (
|
||||
formattedValue = String(value);
|
||||
}
|
||||
|
||||
return `${columnName} ${op} ${formattedValue}`;
|
||||
// The old having filter upper-cased the function (`COUNT()`); v5 only
|
||||
// resolves the aggregation's own lower-case expression.
|
||||
const reference = columnName.replace(
|
||||
/^\s*([A-Za-z_]\w*)\(/,
|
||||
(_, fn: string) => `${fn.toLowerCase()}(`,
|
||||
);
|
||||
|
||||
return `${reference} ${op} ${formattedValue}`;
|
||||
})
|
||||
.filter((expression) => expression !== ''); // Remove empty expressions
|
||||
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useCallback } from 'react';
|
||||
|
||||
export type UseRowNavigationParams<TData> = {
|
||||
rows: TData[];
|
||||
activeIndex: number;
|
||||
onNavigate: (row: TData, index: number) => void;
|
||||
};
|
||||
|
||||
export type UseRowNavigationResult = {
|
||||
goToPrev: () => void;
|
||||
goToNext: () => void;
|
||||
isPrevDisabled: boolean;
|
||||
isNextDisabled: boolean;
|
||||
};
|
||||
|
||||
/** Steps the active row through the loaded rows; stops at either end. */
|
||||
export function useRowNavigation<TData>({
|
||||
rows,
|
||||
activeIndex,
|
||||
onNavigate,
|
||||
}: UseRowNavigationParams<TData>): UseRowNavigationResult {
|
||||
const isPrevDisabled = activeIndex <= 0;
|
||||
const isNextDisabled = activeIndex < 0 || activeIndex >= rows.length - 1;
|
||||
|
||||
const goToPrev = useCallback((): void => {
|
||||
if (!isPrevDisabled) {
|
||||
onNavigate(rows[activeIndex - 1], activeIndex - 1);
|
||||
}
|
||||
}, [isPrevDisabled, onNavigate, rows, activeIndex]);
|
||||
|
||||
const goToNext = useCallback((): void => {
|
||||
if (!isNextDisabled) {
|
||||
onNavigate(rows[activeIndex + 1], activeIndex + 1);
|
||||
}
|
||||
}, [isNextDisabled, onNavigate, rows, activeIndex]);
|
||||
|
||||
return { goToPrev, goToNext, isPrevDisabled, isNextDisabled };
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
} from 'api/ai-assistant/chat';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { buildExplorerNavigationUrl } from 'utils/buildExplorerNavigationUrl';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
import {
|
||||
ArchiveRestore,
|
||||
@@ -47,6 +48,10 @@ import { AIAssistantEvents, SuggestedPromptCategory } from '../../events';
|
||||
import { useAIAssistantAnalyticsContext } from '../../hooks/useAIAssistantAnalyticsContext';
|
||||
import { useAIAssistantStore } from '../../store/useAIAssistantStore';
|
||||
|
||||
import {
|
||||
getPanelTypeForRequestType,
|
||||
requestTypeFromActionQuery,
|
||||
} from './utils/getPanelTypeForRequestType';
|
||||
import { openSavedViewByKey } from './utils/openSavedView';
|
||||
import {
|
||||
isSavedViewOpenAction,
|
||||
@@ -333,6 +338,11 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Read before toUrlCompositeQuery, which drops the requestType envelope.
|
||||
const panelType = getPanelTypeForRequestType(
|
||||
requestTypeFromActionQuery(action.query),
|
||||
action.signal,
|
||||
);
|
||||
const normalized = withDerivedFilterExpressions(urlQuery as unknown as Query);
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('[apply_filter] normalized', normalized);
|
||||
@@ -342,7 +352,9 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
|
||||
normalized.builder.queryData.forEach((q, i) => {
|
||||
deps.handleSetQueryData(i, q);
|
||||
});
|
||||
deps.redirectWithQueryBuilderData(normalized);
|
||||
deps.redirectWithQueryBuilderData(normalized, {
|
||||
[QueryParams.panelTypes]: panelType,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const base = explorerRouteForSignal(action.signal);
|
||||
@@ -353,8 +365,10 @@ function applyFilter(action: MessageActionDTO, deps: ApplyFilterDeps): void {
|
||||
}
|
||||
// eslint-disable-next-line no-console
|
||||
console.log('[apply_filter] off-page → navigate', base);
|
||||
const encoded = encodeURIComponent(JSON.stringify(normalized));
|
||||
navigate(`${base}?${QueryParams.compositeQuery}=${encoded}`);
|
||||
const url = buildExplorerNavigationUrl(base, normalized, {
|
||||
[QueryParams.panelTypes]: panelType,
|
||||
});
|
||||
navigate(url);
|
||||
}
|
||||
|
||||
/** Picks the right rollback API call for a given action kind. */
|
||||
@@ -613,6 +627,7 @@ export default function ActionsSection({
|
||||
disabled={isSuccess}
|
||||
loading={isLoading}
|
||||
aria-label={action.label}
|
||||
testId={`ai-action-chip-${action.kind}`}
|
||||
prefix={icon}
|
||||
>
|
||||
<span className={styles.chipLabel}>{action.label}</span>
|
||||
|
||||
@@ -1,7 +1,16 @@
|
||||
import { undoExecution } from 'api/ai-assistant/chat';
|
||||
import type { MessageActionDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { MessageActionKindDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
MessageActionKindDTO,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { getCurrentLocation } from 'lib/router/navigation';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
import { QueryBuilderContextType } from 'types/common/queryBuilder';
|
||||
|
||||
import ActionsSection from '../ActionsSection';
|
||||
|
||||
@@ -28,6 +37,37 @@ function renderUndoChip(): HTMLElement {
|
||||
return screen.getByRole('button', { name: 'Undo change' });
|
||||
}
|
||||
|
||||
// Labels differ per test: auto-applied filters are deduped module-wide by label.
|
||||
function countByServiceAction(label: string): MessageActionDTO {
|
||||
return {
|
||||
kind: MessageActionKindDTO.apply_filter,
|
||||
label,
|
||||
signal: ApplyFilterSignalDTO.logs,
|
||||
query: {
|
||||
requestType: Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
name: 'A',
|
||||
signal: 'logs',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
groupBy: [{ name: 'service.name' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function currentPanelTypesParam(): string | null {
|
||||
return new URLSearchParams(getCurrentLocation().search).get(
|
||||
QueryParams.panelTypes,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ActionsSection rollback chip', () => {
|
||||
beforeEach(() => {
|
||||
mockUndo.mockReset();
|
||||
@@ -81,3 +121,52 @@ describe('ActionsSection rollback chip', () => {
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ActionsSection apply_filter', () => {
|
||||
it('opens the explorer in the Table view when the chip is clicked from another page', async () => {
|
||||
const user = userEvent.setup({ pointerEventsCheck: 0 });
|
||||
render(
|
||||
<ActionsSection
|
||||
actions={[countByServiceAction('Open in Logs Explorer')]}
|
||||
messageId="message-1"
|
||||
/>,
|
||||
undefined,
|
||||
{ initialRoute: ROUTES.HOME },
|
||||
);
|
||||
|
||||
await user.click(screen.getByTestId('ai-action-chip-apply_filter'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getCurrentLocation().pathname).toBe(ROUTES.LOGS_EXPLORER),
|
||||
);
|
||||
expect(currentPanelTypesParam()).toBe(JSON.stringify(PANEL_TYPES.TABLE));
|
||||
});
|
||||
|
||||
it('switches the open explorer to the Table view when applied on it', async () => {
|
||||
const redirectWithQueryBuilderData = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['redirectWithQueryBuilderData']
|
||||
>;
|
||||
const handleSetQueryData = jest.fn() as jest.MockedFunction<
|
||||
QueryBuilderContextType['handleSetQueryData']
|
||||
>;
|
||||
render(
|
||||
<ActionsSection
|
||||
actions={[countByServiceAction('Apply on Logs Explorer')]}
|
||||
messageId="message-2"
|
||||
/>,
|
||||
undefined,
|
||||
{
|
||||
initialRoute: ROUTES.LOGS_EXPLORER,
|
||||
queryBuilderOverrides: { redirectWithQueryBuilderData, handleSetQueryData },
|
||||
},
|
||||
);
|
||||
|
||||
await waitFor(() =>
|
||||
expect(redirectWithQueryBuilderData).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
expect(redirectWithQueryBuilderData).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ builder: expect.anything() }),
|
||||
{ [QueryParams.panelTypes]: PANEL_TYPES.TABLE },
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { ApplyFilterSignalDTO } from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
import {
|
||||
getPanelTypeForRequestType,
|
||||
requestTypeFromActionQuery,
|
||||
} from '../getPanelTypeForRequestType';
|
||||
|
||||
describe('getPanelTypeForRequestType', () => {
|
||||
it.each([
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.scalar,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.TABLE,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.time_series,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.TIME_SERIES,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.raw,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.LIST,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.trace,
|
||||
ApplyFilterSignalDTO.traces,
|
||||
PANEL_TYPES.TRACE,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.trace,
|
||||
ApplyFilterSignalDTO.logs,
|
||||
PANEL_TYPES.LIST,
|
||||
],
|
||||
[
|
||||
Querybuildertypesv5RequestTypeDTO.trace,
|
||||
ApplyFilterSignalDTO.metrics,
|
||||
PANEL_TYPES.LIST,
|
||||
],
|
||||
])('maps %s on the %s signal to the %s view', (requestType, signal, view) => {
|
||||
expect(getPanelTypeForRequestType(requestType, signal)).toBe(view);
|
||||
});
|
||||
|
||||
it.each([
|
||||
undefined,
|
||||
null,
|
||||
'',
|
||||
Querybuildertypesv5RequestTypeDTO.raw_stream,
|
||||
Querybuildertypesv5RequestTypeDTO.heatmap,
|
||||
'distribution',
|
||||
'nonsense',
|
||||
'toString',
|
||||
'constructor',
|
||||
42,
|
||||
{},
|
||||
])(
|
||||
'falls back to the List view for unmapped or invalid requestType (%p)',
|
||||
(value) => {
|
||||
expect(getPanelTypeForRequestType(value, ApplyFilterSignalDTO.traces)).toBe(
|
||||
PANEL_TYPES.LIST,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('requestTypeFromActionQuery', () => {
|
||||
it('reads the requestType envelope field and returns undefined when absent', () => {
|
||||
expect(
|
||||
requestTypeFromActionQuery({
|
||||
requestType: 'scalar',
|
||||
schemaVersion: 'v5',
|
||||
compositeQuery: { queries: [] },
|
||||
}),
|
||||
).toBe('scalar');
|
||||
expect(requestTypeFromActionQuery({})).toBeUndefined();
|
||||
expect(requestTypeFromActionQuery(null)).toBeUndefined();
|
||||
expect(requestTypeFromActionQuery(undefined)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('maps a grouped count() payload to the Table view', () => {
|
||||
const query = {
|
||||
requestType: 'scalar',
|
||||
schemaVersion: 'v5',
|
||||
compositeQuery: {
|
||||
queries: [
|
||||
{
|
||||
type: 'builder_query',
|
||||
spec: {
|
||||
signal: 'logs',
|
||||
aggregations: [{ expression: 'count()' }],
|
||||
groupBy: [{ name: 'service.name' }],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(
|
||||
getPanelTypeForRequestType(
|
||||
requestTypeFromActionQuery(query),
|
||||
ApplyFilterSignalDTO.logs,
|
||||
),
|
||||
).toBe(PANEL_TYPES.TABLE);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import {
|
||||
ApplyFilterSignalDTO,
|
||||
type MessageActionDTOQuery,
|
||||
} from 'api/ai-assistant/sigNozAIAssistantAPI.schemas';
|
||||
import { Querybuildertypesv5RequestTypeDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
export function getPanelTypeForRequestType(
|
||||
requestType: unknown,
|
||||
signal: ApplyFilterSignalDTO,
|
||||
): PANEL_TYPES {
|
||||
switch (requestType) {
|
||||
case Querybuildertypesv5RequestTypeDTO.scalar:
|
||||
return PANEL_TYPES.TABLE;
|
||||
case Querybuildertypesv5RequestTypeDTO.time_series:
|
||||
return PANEL_TYPES.TIME_SERIES;
|
||||
case Querybuildertypesv5RequestTypeDTO.trace:
|
||||
return signal === ApplyFilterSignalDTO.traces
|
||||
? PANEL_TYPES.TRACE
|
||||
: PANEL_TYPES.LIST;
|
||||
default:
|
||||
return PANEL_TYPES.LIST;
|
||||
}
|
||||
}
|
||||
|
||||
export function requestTypeFromActionQuery(
|
||||
query: MessageActionDTOQuery | undefined,
|
||||
): unknown {
|
||||
return query?.requestType;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
.logsTable {
|
||||
--tanstack-table-row-height: 30px;
|
||||
}
|
||||
@@ -2,7 +2,6 @@
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 14px;
|
||||
font-weight: 400;
|
||||
line-height: 18px;
|
||||
@@ -19,7 +18,6 @@
|
||||
thead {
|
||||
tr {
|
||||
th {
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 12px;
|
||||
color: white !important;
|
||||
|
||||
@@ -37,7 +35,6 @@
|
||||
}
|
||||
|
||||
td {
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@@ -57,7 +54,6 @@
|
||||
tbody {
|
||||
tr {
|
||||
td {
|
||||
font-family: 'Space Mono', monospace;
|
||||
font-size: 12px;
|
||||
padding: 4px !important;
|
||||
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
isTraceToLogsQuery,
|
||||
} from './utils';
|
||||
|
||||
import styles from './LogsExplorerList.module.scss';
|
||||
import './LogsExplorerList.style.scss';
|
||||
|
||||
function Footer(): JSX.Element {
|
||||
@@ -202,6 +203,7 @@ function LogsExplorerList({
|
||||
return (
|
||||
<TanStackTable<ILog>
|
||||
ref={ref as React.Ref<TanStackTableHandle>}
|
||||
className={styles.logsTable}
|
||||
columns={logsColumns}
|
||||
columnStorageKey={LOCALSTORAGE.LOGS_LIST_COLUMNS}
|
||||
respectColumnOrder={false}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
.logs-explorer-views-container {
|
||||
margin-bottom: 24px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ChangeEvent, useCallback, useMemo, useState } from 'react';
|
||||
import { Col, Input, Row, Select } from 'antd';
|
||||
import InputWithLabel from 'components/InputWithLabel/InputWithLabel';
|
||||
import BucketOptions from 'components/QueryBuilderV2/QueryV2/QueryAddOns/BucketOptions/BucketOptions';
|
||||
import { parseLimit, sanitizeLimit } from 'components/QueryBuilderV2/utils';
|
||||
import { LEGEND } from 'constants/global';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
// ** Hooks
|
||||
@@ -171,7 +172,8 @@ export function Formula({
|
||||
<InputWithLabel
|
||||
label="Limit"
|
||||
type="number"
|
||||
onChange={(value): void => handleChangeLimit(Number(value))}
|
||||
onChange={(value): void => handleChangeLimit(parseLimit(value))}
|
||||
sanitize={sanitizeLimit}
|
||||
initialValue={formula?.limit ?? undefined}
|
||||
placeholder="Enter limit"
|
||||
/>
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
.container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 0.3rem;
|
||||
margin: 8px 0;
|
||||
}
|
||||
|
||||
.optionsTrigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
@@ -1,82 +1,57 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Settings } from '@signozhq/icons';
|
||||
import { SlidersVertical } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import FieldsSelector from 'components/FieldsSelector';
|
||||
import Controls, { ControlsProps } from 'container/Controls';
|
||||
import { OptionsMenuConfig } from 'container/OptionsMenu/types';
|
||||
import useQueryPagination from 'hooks/queryPagination/useQueryPagination';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
|
||||
import styles from './Controls.module.scss';
|
||||
|
||||
function TraceExplorerControls({
|
||||
isLoading,
|
||||
totalCount,
|
||||
perPageOptions,
|
||||
config,
|
||||
showSizeChanger = true,
|
||||
}: TraceExplorerControlsProps): JSX.Element | null {
|
||||
const { t } = useTranslation(['trace']);
|
||||
const [isFieldsSelectorOpen, setIsFieldsSelectorOpen] = useState(false);
|
||||
|
||||
const {
|
||||
pagination,
|
||||
handleCountItemsPerPageChange,
|
||||
handleNavigateNext,
|
||||
handleNavigatePrevious,
|
||||
} = useQueryPagination(totalCount, perPageOptions);
|
||||
if (!config?.fieldsSelector) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const label = t('options_menu.options');
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
{config?.fieldsSelector && (
|
||||
<>
|
||||
<div
|
||||
className={styles.optionsTrigger}
|
||||
onClick={(): void => setIsFieldsSelectorOpen(true)}
|
||||
>
|
||||
{t('options_menu.options')}
|
||||
<Settings size="md" />
|
||||
</div>
|
||||
<FieldsSelector
|
||||
isOpen={isFieldsSelectorOpen}
|
||||
title="Edit columns"
|
||||
fields={config.fieldsSelector.value}
|
||||
onFieldsChange={config.fieldsSelector.onFieldsChange}
|
||||
onClose={(): void => setIsFieldsSelectorOpen(false)}
|
||||
signal={DataSource.TRACES}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<Controls
|
||||
isLoading={isLoading}
|
||||
totalCount={totalCount}
|
||||
offset={pagination.offset}
|
||||
countPerPage={pagination.limit}
|
||||
perPageOptions={perPageOptions}
|
||||
handleCountItemsPerPageChange={handleCountItemsPerPageChange}
|
||||
handleNavigateNext={handleNavigateNext}
|
||||
handleNavigatePrevious={handleNavigatePrevious}
|
||||
showSizeChanger={showSizeChanger}
|
||||
<>
|
||||
<Tooltip title={label}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
aria-label={label}
|
||||
testId="periscope-btn-options-traces"
|
||||
onClick={(): void => setIsFieldsSelectorOpen(true)}
|
||||
>
|
||||
<SlidersVertical size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
<FieldsSelector
|
||||
isOpen={isFieldsSelectorOpen}
|
||||
title="Edit columns"
|
||||
fields={config.fieldsSelector.value}
|
||||
onFieldsChange={config.fieldsSelector.onFieldsChange}
|
||||
onClose={(): void => setIsFieldsSelectorOpen(false)}
|
||||
signal={DataSource.TRACES}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type TraceExplorerControlsProps = {
|
||||
config?: OptionsMenuConfig | null;
|
||||
};
|
||||
|
||||
TraceExplorerControls.defaultProps = {
|
||||
config: null,
|
||||
};
|
||||
|
||||
type TraceExplorerControlsProps = Pick<
|
||||
ControlsProps,
|
||||
'isLoading' | 'totalCount' | 'perPageOptions'
|
||||
> & {
|
||||
config?: OptionsMenuConfig | null;
|
||||
showSizeChanger?: boolean;
|
||||
};
|
||||
|
||||
TraceExplorerControls.defaultProps = {
|
||||
showSizeChanger: true,
|
||||
};
|
||||
|
||||
export default memo(TraceExplorerControls);
|
||||
|
||||
@@ -6,3 +6,33 @@
|
||||
height: calc(100vh - 240px);
|
||||
min-height: 400px;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-height: 40px;
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
}
|
||||
|
||||
.orderBy {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.orderByLabel {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
color: var(--l2-foreground);
|
||||
font-size: 12px;
|
||||
font-weight: 400;
|
||||
line-height: 16px;
|
||||
}
|
||||
|
||||
.drawerScope {
|
||||
display: contents;
|
||||
}
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
.trace-explorer-controls {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
.order-by-container {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
|
||||
.order-by-label {
|
||||
color: var(--muted-foreground);
|
||||
font-size: 12px;
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
line-height: 16px; /* 133.333% */
|
||||
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.order-by-select {
|
||||
width: 100px;
|
||||
|
||||
.ant-select-selector {
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
background-color: transparent;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { initialQueriesMap } from 'constants/queryBuilder';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { screen } from 'tests/test-utils';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
|
||||
import {
|
||||
listResponse,
|
||||
listRows,
|
||||
QUERY_RANGE_URL,
|
||||
renderListView,
|
||||
} from './testUtils';
|
||||
|
||||
// globalTime starts with loading:true, which gates the list query. Force just that
|
||||
// slice's loading to false so the query fires; every other selector is untouched.
|
||||
jest.mock('react-redux', () => {
|
||||
const actual = jest.requireActual('react-redux');
|
||||
return {
|
||||
...actual,
|
||||
useSelector: (selector: (state: unknown) => unknown): unknown => {
|
||||
const result = actual.useSelector(selector);
|
||||
if (result && typeof result === 'object' && 'loading' in result) {
|
||||
return { ...result, loading: false };
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// List columns come from the options menu (server-synced preferences). Pin them
|
||||
// so the expected columns render, independent of that API.
|
||||
jest.mock('container/OptionsMenu/useOptionsMenu', () => ({
|
||||
__esModule: true,
|
||||
default: (): unknown => ({
|
||||
options: {
|
||||
selectColumns: [
|
||||
{ name: 'service.name', fieldContext: 'resource' },
|
||||
{ name: 'name', fieldContext: 'span' },
|
||||
{ name: 'duration_nano', fieldContext: 'span' },
|
||||
{ name: 'http_method', fieldContext: 'span' },
|
||||
{ name: 'response_status_code', fieldContext: 'span' },
|
||||
{ name: 'http.route', fieldContext: 'attribute' },
|
||||
{ name: 'cache.hit', fieldContext: 'attribute' },
|
||||
],
|
||||
},
|
||||
config: { addColumn: { onRemove: jest.fn() } },
|
||||
}),
|
||||
}));
|
||||
|
||||
type ListRequest = {
|
||||
offset: number;
|
||||
limit: number;
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
|
||||
// Answers each offset with `rowsPerOffset[offset]` rows and records every request.
|
||||
const mockListPages = (
|
||||
rowsPerOffset: Record<number, number>,
|
||||
firstPageDelayMs = 0,
|
||||
): ListRequest[] => {
|
||||
const requests: ListRequest[] = [];
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const body = await req.json<QueryRangeRequestV5>();
|
||||
const spec = body.compositeQuery.queries[0].spec as {
|
||||
offset?: number;
|
||||
limit: number;
|
||||
};
|
||||
const offset = spec.offset ?? 0;
|
||||
requests.push({
|
||||
offset,
|
||||
limit: spec.limit,
|
||||
start: body.start,
|
||||
end: body.end,
|
||||
});
|
||||
const length = Math.min(rowsPerOffset[offset] ?? 0, spec.limit);
|
||||
const rows = Array.from({ length }, (_, i) => ({
|
||||
...listRows[0],
|
||||
data: {
|
||||
...listRows[0].data,
|
||||
name: `span-${offset + i}`,
|
||||
span_id: `span-${offset + i}`,
|
||||
},
|
||||
}));
|
||||
return res(
|
||||
ctx.delay(offset === 0 ? firstPageDelayMs : 0),
|
||||
ctx.status(200),
|
||||
ctx.json(listResponse(rows)),
|
||||
);
|
||||
}),
|
||||
);
|
||||
return requests;
|
||||
};
|
||||
|
||||
// Tall enough that the mocked virtuoso renders every row and reaches the end.
|
||||
const FULL_HEIGHT = 200 * 54;
|
||||
|
||||
describe('Traces ListView - infinite scroll', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('loads the next page at the end of the list over the same window', async () => {
|
||||
// Past the one-second resolution of the window, so a recomputed "now" would show.
|
||||
const requests = mockListPages({ 0: 100, 100: 5 }, 1100);
|
||||
renderListView(initialQueriesMap.traces, FULL_HEIGHT);
|
||||
|
||||
await expect(
|
||||
screen.findByText('span-104', undefined, { timeout: 3000 }),
|
||||
).resolves.toBeInTheDocument();
|
||||
expect(screen.getByText('span-0')).toBeInTheDocument();
|
||||
expect(requests.map(({ offset }) => offset)).toStrictEqual([0, 100]);
|
||||
expect(requests[1].start).toBe(requests[0].start);
|
||||
expect(requests[1].end).toBe(requests[0].end);
|
||||
});
|
||||
|
||||
it('stops after a short page', async () => {
|
||||
const requests = mockListPages({ 0: 5 });
|
||||
renderListView(initialQueriesMap.traces, FULL_HEIGHT);
|
||||
|
||||
await expect(screen.findByText('span-4')).resolves.toBeInTheDocument();
|
||||
expect(requests.map(({ offset }) => offset)).toStrictEqual([0]);
|
||||
});
|
||||
|
||||
it('stops at the query limit', async () => {
|
||||
const requests = mockListPages({ 0: 100, 100: 100 });
|
||||
const { builder } = initialQueriesMap.traces;
|
||||
renderListView(
|
||||
{
|
||||
...initialQueriesMap.traces,
|
||||
builder: {
|
||||
...builder,
|
||||
queryData: [{ ...builder.queryData[0], limit: 150 }],
|
||||
},
|
||||
} as Query,
|
||||
FULL_HEIGHT,
|
||||
);
|
||||
|
||||
await expect(screen.findByText('span-149')).resolves.toBeInTheDocument();
|
||||
expect(
|
||||
requests.map(({ offset, limit }) => ({ offset, limit })),
|
||||
).toStrictEqual([
|
||||
{ offset: 0, limit: 100 },
|
||||
{ offset: 100, limit: 50 },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,208 @@
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import {
|
||||
OpenTraceSource,
|
||||
TracesExplorerEvents,
|
||||
} from 'container/TracesExplorer/events';
|
||||
import { getCurrentLocation } from 'lib/router/navigation';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import {
|
||||
listRows,
|
||||
mockSuccess,
|
||||
mockTraceSummary,
|
||||
renderListView,
|
||||
} from './testUtils';
|
||||
|
||||
jest.mock('api/common/logEvent');
|
||||
|
||||
// globalTime starts with loading:true, which gates the list query. Force just that
|
||||
// slice's loading to false so the query fires; every other selector is untouched.
|
||||
jest.mock('react-redux', () => {
|
||||
const actual = jest.requireActual('react-redux');
|
||||
return {
|
||||
...actual,
|
||||
useSelector: (selector: (state: unknown) => unknown): unknown => {
|
||||
const result = actual.useSelector(selector);
|
||||
if (result && typeof result === 'object' && 'loading' in result) {
|
||||
return { ...result, loading: false };
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// List columns come from the options menu (server-synced preferences). Pin them
|
||||
// so the expected columns render, independent of that API.
|
||||
jest.mock('container/OptionsMenu/useOptionsMenu', () => ({
|
||||
__esModule: true,
|
||||
default: (): unknown => ({
|
||||
options: {
|
||||
selectColumns: [
|
||||
{ name: 'service.name', fieldContext: 'resource' },
|
||||
{ name: 'name', fieldContext: 'span' },
|
||||
{ name: 'duration_nano', fieldContext: 'span' },
|
||||
{ name: 'http_method', fieldContext: 'span' },
|
||||
{ name: 'response_status_code', fieldContext: 'span' },
|
||||
{ name: 'http.route', fieldContext: 'attribute' },
|
||||
{ name: 'cache.hit', fieldContext: 'attribute' },
|
||||
],
|
||||
},
|
||||
config: { addColumn: { onRemove: jest.fn() } },
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('Traces ListView - span drawer navigation', () => {
|
||||
beforeEach(() => {
|
||||
mockSuccess();
|
||||
mockTraceSummary({});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('opens the clicked span and steps through rows with the arrow keys', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
await user.click(await screen.findByText('HTTP GET'));
|
||||
|
||||
const drawer = await screen.findByTestId('span-details-drawer');
|
||||
expect(within(drawer).getByText('HTTP GET')).toBeInTheDocument();
|
||||
expect(within(drawer).getByTestId('span-details-trace-id')).toHaveTextContent(
|
||||
'0000000000000000344ded1387b08a7e',
|
||||
);
|
||||
|
||||
await user.keyboard('{ArrowDown}');
|
||||
await expect(
|
||||
within(drawer).findByText('authenticate_check_db'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
await user.keyboard('{ArrowUp}');
|
||||
await expect(
|
||||
within(drawer).findByText('HTTP GET'),
|
||||
).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('closes the drawer', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
await user.click(await screen.findByText('HTTP GET'));
|
||||
await screen.findByTestId('span-details-drawer');
|
||||
|
||||
await user.click(screen.getByTestId('span-drawer-close'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('span-details-drawer')).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it('stays open on a press in the drawer or the list, and closes on one outside', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
await user.click(await screen.findByText('HTTP GET'));
|
||||
const drawer = await screen.findByTestId('span-details-drawer');
|
||||
|
||||
await user.click(drawer);
|
||||
// Hovering re-renders the row, so the press needs a fresh query.
|
||||
await user.hover(screen.getByText('authenticate_check_db'));
|
||||
await user.click(screen.getByText('authenticate_check_db'));
|
||||
await expect(
|
||||
within(drawer).findByText('authenticate_check_db'),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
await user.click(document.body);
|
||||
await waitFor(() =>
|
||||
expect(screen.queryByTestId('span-details-drawer')).not.toBeInTheDocument(),
|
||||
);
|
||||
});
|
||||
|
||||
it('opens the trace page in a new tab from the row icon without opening the drawer', async () => {
|
||||
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
|
||||
// user-event leaves the row on its way to the button, which clears the hover.
|
||||
const user = userEvent.setup({ skipHover: true });
|
||||
renderListView();
|
||||
|
||||
const row = (await screen.findByText('HTTP GET')).closest(
|
||||
'tr',
|
||||
) as HTMLElement;
|
||||
expect(screen.queryByTestId('span-row-open-trace')).not.toBeInTheDocument();
|
||||
await user.hover(row);
|
||||
await user.click(await screen.findByTestId('span-row-open-trace'));
|
||||
|
||||
expect(open).toHaveBeenCalledWith(
|
||||
expect.stringMatching(
|
||||
/\/trace\/0000000000000000344ded1387b08a7e\?.*772c4d29dd9076ac/,
|
||||
),
|
||||
'_blank',
|
||||
);
|
||||
expect(getCurrentLocation().pathname).toBe('/traces-explorer');
|
||||
expect(screen.queryByTestId('span-details-drawer')).not.toBeInTheDocument();
|
||||
expect(logEvent).toHaveBeenCalledWith(TracesExplorerEvents.OpenTraceClicked, {
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
source: OpenTraceSource.RowIcon,
|
||||
});
|
||||
});
|
||||
|
||||
it('opens the trace page in a new tab from the drawer', async () => {
|
||||
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
await user.click(await screen.findByText('HTTP GET'));
|
||||
expect(logEvent).not.toHaveBeenCalledWith(
|
||||
TracesExplorerEvents.OpenTraceClicked,
|
||||
{ panelType: PANEL_TYPES.LIST, source: OpenTraceSource.Row },
|
||||
);
|
||||
await user.click(await screen.findByTestId('span-drawer-view-full-trace'));
|
||||
|
||||
expect(open).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/trace\/0000000000000000344ded1387b08a7e\?/),
|
||||
'_blank',
|
||||
);
|
||||
expect(logEvent).toHaveBeenCalledWith(TracesExplorerEvents.OpenTraceClicked, {
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
source: OpenTraceSource.SpanDrawer,
|
||||
});
|
||||
});
|
||||
|
||||
it('opens the trace page in a new tab on a Cmd-click without opening the drawer', async () => {
|
||||
const open = jest.spyOn(window, 'open').mockImplementation(() => null);
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
const row = await screen.findByText('HTTP GET');
|
||||
await user.keyboard('{Meta>}');
|
||||
await user.click(row);
|
||||
await user.keyboard('{/Meta}');
|
||||
|
||||
expect(open).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/\/trace\/0000000000000000344ded1387b08a7e\?/),
|
||||
'_blank',
|
||||
'noopener',
|
||||
);
|
||||
expect(screen.queryByTestId('span-details-drawer')).not.toBeInTheDocument();
|
||||
expect(logEvent).toHaveBeenCalledWith(TracesExplorerEvents.OpenTraceClicked, {
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
source: OpenTraceSource.Row,
|
||||
});
|
||||
});
|
||||
|
||||
it('shows the row icon only on the hovered copy of a duplicate span', async () => {
|
||||
mockSuccess([listRows[0], listRows[0]]);
|
||||
// user-event leaves the row on its way to the button, which clears the hover.
|
||||
const user = userEvent.setup({ skipHover: true });
|
||||
renderListView();
|
||||
|
||||
const [first] = await screen.findAllByText('HTTP GET');
|
||||
await user.hover(first.closest('tr') as HTMLElement);
|
||||
|
||||
await expect(
|
||||
screen.findAllByTestId('span-row-open-trace'),
|
||||
).resolves.toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
import {
|
||||
FIVE_MINUTES_IN_MS,
|
||||
listResponse,
|
||||
listRows,
|
||||
mockSuccess,
|
||||
mockTraceSummary,
|
||||
QUERY_RANGE_URL,
|
||||
renderListView,
|
||||
TraceBounds,
|
||||
} from './testUtils';
|
||||
|
||||
// globalTime starts with loading:true, which gates the list query. Force just that
|
||||
// slice's loading to false so the query fires; every other selector is untouched.
|
||||
jest.mock('react-redux', () => {
|
||||
const actual = jest.requireActual('react-redux');
|
||||
return {
|
||||
...actual,
|
||||
useSelector: (selector: (state: unknown) => unknown): unknown => {
|
||||
const result = actual.useSelector(selector);
|
||||
if (result && typeof result === 'object' && 'loading' in result) {
|
||||
return { ...result, loading: false };
|
||||
}
|
||||
return result;
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
// List columns come from the options menu (server-synced preferences). Pin them
|
||||
// so the expected columns render, independent of that API.
|
||||
jest.mock('container/OptionsMenu/useOptionsMenu', () => ({
|
||||
__esModule: true,
|
||||
default: (): unknown => ({
|
||||
options: {
|
||||
selectColumns: [
|
||||
{ name: 'service.name', fieldContext: 'resource' },
|
||||
{ name: 'name', fieldContext: 'span' },
|
||||
{ name: 'duration_nano', fieldContext: 'span' },
|
||||
{ name: 'http_method', fieldContext: 'span' },
|
||||
{ name: 'response_status_code', fieldContext: 'span' },
|
||||
{ name: 'http.route', fieldContext: 'attribute' },
|
||||
{ name: 'cache.hit', fieldContext: 'attribute' },
|
||||
],
|
||||
},
|
||||
config: { addColumn: { onRemove: jest.fn() } },
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('Traces ListView - span drawer trace bounds', () => {
|
||||
beforeEach(() => {
|
||||
mockSuccess();
|
||||
mockTraceSummary({});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('requests span logs over whole milliseconds', async () => {
|
||||
const logsRequests: QueryRangeRequestV5[] = [];
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const body = await req.json<QueryRangeRequestV5>();
|
||||
const spec = body.compositeQuery.queries[0]?.spec;
|
||||
if (spec && 'signal' in spec && spec.signal === 'logs') {
|
||||
logsRequests.push(body);
|
||||
// No logs, so no context queries follow to outlive the test.
|
||||
return res(ctx.status(200), ctx.json(listResponse([])));
|
||||
}
|
||||
return res(ctx.status(200), ctx.json(listResponse(listRows)));
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
// Its 790.94939 ms duration makes the span window end mid-millisecond.
|
||||
await user.click(await screen.findByText('authenticate_check_db'));
|
||||
|
||||
await waitFor(() => expect(logsRequests.length).toBeGreaterThan(0));
|
||||
logsRequests.forEach(({ start, end }) => {
|
||||
expect(Number.isInteger(start)).toBe(true);
|
||||
expect(Number.isInteger(end)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
it('reads the trace bounds from the trace summary', async () => {
|
||||
const bounds: TraceBounds = {
|
||||
'0000000000000000344ded1387b08a7e': {
|
||||
start: Date.parse('2024-07-19T08:39:58.700Z'),
|
||||
end: Date.parse('2024-07-19T08:39:58.900Z'),
|
||||
},
|
||||
a364a8e15af3e9a8c866e0528db8b637: {
|
||||
start: Date.parse('2024-07-19T08:39:59.900Z'),
|
||||
end: Date.parse('2024-07-19T08:40:01.000Z'),
|
||||
},
|
||||
};
|
||||
mockTraceSummary(bounds);
|
||||
const logsRequests: {
|
||||
traceId: string;
|
||||
isTraceWide: boolean;
|
||||
start: number;
|
||||
end: number;
|
||||
}[] = [];
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const body = await req.json<QueryRangeRequestV5>();
|
||||
const spec = body.compositeQuery.queries[0]?.spec;
|
||||
if (spec && 'signal' in spec && spec.signal === 'logs') {
|
||||
const traceId =
|
||||
Object.keys(bounds).find((id) => spec.filter?.expression?.includes(id)) ??
|
||||
'';
|
||||
// The payload carries the window in µs.
|
||||
logsRequests.push({
|
||||
traceId,
|
||||
isTraceWide: !spec.filter?.expression?.includes('span_id'),
|
||||
start: body.start / 1e3,
|
||||
end: body.end / 1e3,
|
||||
});
|
||||
return res(ctx.status(200), ctx.json(listResponse([])));
|
||||
}
|
||||
return res(ctx.status(200), ctx.json(listResponse(listRows)));
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
await user.click(await screen.findByText('HTTP GET'));
|
||||
const drawer = await screen.findByTestId('span-details-drawer');
|
||||
await expect(
|
||||
within(drawer).findByText(/of total exec time/),
|
||||
).resolves.toBeInTheDocument();
|
||||
|
||||
// The next span is in another trace, so it needs that trace's bounds.
|
||||
// Both its span logs and its trace-wide check must land before the test ends.
|
||||
await user.keyboard('{ArrowDown}');
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
logsRequests
|
||||
.filter(({ traceId }) => traceId === 'a364a8e15af3e9a8c866e0528db8b637')
|
||||
.map(({ isTraceWide }) => isTraceWide),
|
||||
).toStrictEqual(expect.arrayContaining([false, true])),
|
||||
);
|
||||
|
||||
// Logs wait for the bounds: no request ever goes out with another window.
|
||||
logsRequests.forEach(({ traceId, start, end }) => {
|
||||
expect(start).toBe(bounds[traceId].start - FIVE_MINUTES_IN_MS);
|
||||
expect(end).toBe(bounds[traceId].end + FIVE_MINUTES_IN_MS);
|
||||
});
|
||||
});
|
||||
|
||||
it('speaks only for the span when the trace has no summary', async () => {
|
||||
const logsFilters: string[] = [];
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const body = await req.json<QueryRangeRequestV5>();
|
||||
const spec = body.compositeQuery.queries[0]?.spec;
|
||||
if (spec && 'signal' in spec && spec.signal === 'logs') {
|
||||
logsFilters.push(spec.filter?.expression ?? '');
|
||||
return res(ctx.status(200), ctx.json(listResponse([])));
|
||||
}
|
||||
return res(ctx.status(200), ctx.json(listResponse(listRows)));
|
||||
}),
|
||||
);
|
||||
const user = userEvent.setup();
|
||||
renderListView();
|
||||
|
||||
await user.click(await screen.findByText('HTTP GET'));
|
||||
const drawer = await screen.findByTestId('span-details-drawer');
|
||||
|
||||
await user.click(within(drawer).getByRole('tab', { name: /logs/i }));
|
||||
await expect(
|
||||
within(drawer).findByText('No logs found for this span.'),
|
||||
).resolves.toBeInTheDocument();
|
||||
// Checked once the 404 has settled; before it, exec time is absent anyway.
|
||||
expect(
|
||||
within(drawer).queryByText(/of total exec time/),
|
||||
).not.toBeInTheDocument();
|
||||
// No trace-wide check: every logs request is scoped to the span.
|
||||
expect(logsFilters.length).toBeGreaterThan(0);
|
||||
logsFilters.forEach((expression) => {
|
||||
expect(expression).toContain('span_id');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render } from 'tests/test-utils';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import ListView from '../index';
|
||||
|
||||
const BASE_URL = ENVIRONMENT.baseURL;
|
||||
export const QUERY_RANGE_URL = `${BASE_URL}/api/v5/query_range`;
|
||||
|
||||
export const listRows = [
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:58.735245Z',
|
||||
data: {
|
||||
name: 'HTTP GET',
|
||||
duration_nano: 55306000,
|
||||
http_method: 'GET',
|
||||
response_status_code: '200',
|
||||
span_id: '772c4d29dd9076ac',
|
||||
trace_id: '0000000000000000344ded1387b08a7e',
|
||||
attributes: { 'http.route': '/api/cart', 'cache.hit': false },
|
||||
resource: { 'service.name': 'frontend' },
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:59.949129915Z',
|
||||
data: {
|
||||
name: 'authenticate_check_db',
|
||||
duration_nano: 790949390,
|
||||
// empty status fields to assert the "-" cell
|
||||
http_method: '',
|
||||
response_status_code: '',
|
||||
span_id: '5704353737b6778e',
|
||||
trace_id: 'a364a8e15af3e9a8c866e0528db8b637',
|
||||
attributes: {},
|
||||
resource: { 'service.name': 'demo-app' },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const listResponse = (rows: unknown[]): Record<string, unknown> => ({
|
||||
data: { type: 'raw', data: { results: [{ queryName: 'A', rows }] } },
|
||||
});
|
||||
|
||||
export const TRACE_SUMMARY_URL = `${BASE_URL}/api/v1/traces/:traceId/summary`;
|
||||
export const FIVE_MINUTES_IN_MS = 5 * 60 * 1000;
|
||||
|
||||
export type TraceBounds = Record<string, { start: number; end: number }>;
|
||||
|
||||
// Traces missing from `bounds` get a 404, like a trace with no summary row.
|
||||
export const mockTraceSummary = (bounds: TraceBounds): void => {
|
||||
server.use(
|
||||
rest.get(TRACE_SUMMARY_URL, (req, res, ctx) => {
|
||||
const traceBounds = bounds[req.params.traceId as string];
|
||||
if (!traceBounds) {
|
||||
return res(ctx.status(404), ctx.json({ status: 'error' }));
|
||||
}
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json({
|
||||
status: 'success',
|
||||
data: {
|
||||
startTimestampMillis: traceBounds.start,
|
||||
endTimestampMillis: traceBounds.end,
|
||||
hasMissingSpans: false,
|
||||
rootServiceEntryPoint: '',
|
||||
rootServiceName: '',
|
||||
rootSpanStatusCode: '',
|
||||
totalErrorSpansCount: 0,
|
||||
totalSpansCount: 1,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
export const mockSuccess = (rows: unknown[] = listRows): void => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listResponse(rows))),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const renderListView = (
|
||||
stagedQuery: Query = initialQueriesMap.traces,
|
||||
viewportHeight = 500,
|
||||
): ReturnType<typeof render> =>
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight, itemHeight: 54 }}>
|
||||
<ListView
|
||||
isFilterApplied={false}
|
||||
setWarning={jest.fn()}
|
||||
setIsLoadingQueries={jest.fn()}
|
||||
/>
|
||||
</VirtuosoMockContext.Provider>,
|
||||
{},
|
||||
{
|
||||
initialRoute: '/traces-explorer',
|
||||
queryBuilderOverrides: {
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
stagedQuery,
|
||||
currentQuery: stagedQuery,
|
||||
redirectWithQueryBuilderData: jest.fn(),
|
||||
} as any,
|
||||
},
|
||||
);
|
||||
@@ -1,17 +1,20 @@
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import {
|
||||
initialQueriesMap,
|
||||
initialQueryBuilderFormTraceOperatorValues,
|
||||
PANEL_TYPES,
|
||||
} from 'constants/queryBuilder';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import { screen } from 'tests/test-utils';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
|
||||
import ListView from './index';
|
||||
import {
|
||||
listResponse,
|
||||
listRows,
|
||||
mockSuccess,
|
||||
QUERY_RANGE_URL,
|
||||
renderListView,
|
||||
} from './__tests__/testUtils';
|
||||
|
||||
// globalTime starts with loading:true, which gates the list query. Force just that
|
||||
// slice's loading to false so the query fires; every other selector is untouched.
|
||||
@@ -49,74 +52,6 @@ jest.mock('container/OptionsMenu/useOptionsMenu', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
const BASE_URL = ENVIRONMENT.baseURL;
|
||||
const QUERY_RANGE_URL = `${BASE_URL}/api/v5/query_range`;
|
||||
|
||||
const listRows = [
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:58.735245Z',
|
||||
data: {
|
||||
name: 'HTTP GET',
|
||||
duration_nano: 55306000,
|
||||
http_method: 'GET',
|
||||
response_status_code: '200',
|
||||
span_id: '772c4d29dd9076ac',
|
||||
trace_id: '0000000000000000344ded1387b08a7e',
|
||||
attributes: { 'http.route': '/api/cart', 'cache.hit': false },
|
||||
resource: { 'service.name': 'frontend' },
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:59.949129915Z',
|
||||
data: {
|
||||
name: 'authenticate_check_db',
|
||||
duration_nano: 790949390,
|
||||
// empty status fields to assert the "-" cell
|
||||
http_method: '',
|
||||
response_status_code: '',
|
||||
span_id: '5704353737b6778e',
|
||||
trace_id: 'a364a8e15af3e9a8c866e0528db8b637',
|
||||
attributes: {},
|
||||
resource: { 'service.name': 'demo-app' },
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const listResponse = (rows: unknown[]): Record<string, unknown> => ({
|
||||
data: { type: 'raw', data: { results: [{ queryName: 'A', rows }] } },
|
||||
});
|
||||
|
||||
const mockSuccess = (rows: unknown[] = listRows): void => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(listResponse(rows))),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const renderListView = (
|
||||
stagedQuery: Query = initialQueriesMap.traces,
|
||||
): ReturnType<typeof render> =>
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight: 500, itemHeight: 54 }}>
|
||||
<ListView
|
||||
isFilterApplied={false}
|
||||
setWarning={jest.fn()}
|
||||
setIsLoadingQueries={jest.fn()}
|
||||
/>
|
||||
</VirtuosoMockContext.Provider>,
|
||||
{},
|
||||
{
|
||||
initialRoute: '/traces-explorer',
|
||||
queryBuilderOverrides: {
|
||||
panelType: PANEL_TYPES.LIST,
|
||||
stagedQuery,
|
||||
currentQuery: stagedQuery,
|
||||
redirectWithQueryBuilderData: jest.fn(),
|
||||
} as any,
|
||||
},
|
||||
);
|
||||
|
||||
describe('Traces ListView - Data Loaded', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
@@ -143,8 +78,8 @@ describe('Traces ListView - Data Loaded', () => {
|
||||
'200',
|
||||
);
|
||||
|
||||
// empty status fields render "-"
|
||||
expect(screen.getAllByText('-').length).toBeGreaterThanOrEqual(1);
|
||||
// empty status fields render the dash icon
|
||||
expect(screen.getAllByTestId('empty-value').length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('requests every span field instead of the selected columns', async () => {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
import { render, screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import ListView from './index';
|
||||
|
||||
@@ -59,16 +59,8 @@ const verifyControlsVisibility = (): void => {
|
||||
// Order by controls
|
||||
expect(screen.getByText(/Order by/i)).toBeInTheDocument();
|
||||
|
||||
// Pagination controls
|
||||
expect(screen.getByRole('button', { name: /previous/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /next/i })).toBeInTheDocument();
|
||||
|
||||
// Items per page selector (there are multiple comboboxes, so we check for at least 2)
|
||||
const comboboxes = screen.getAllByRole('combobox');
|
||||
expect(comboboxes.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
// Options menu (settings button) - check for translation key or actual text
|
||||
expect(screen.getByText(/options_menu.options|options/i)).toBeInTheDocument();
|
||||
expect(screen.getByTestId('periscope-btn-options-traces')).toBeInTheDocument();
|
||||
};
|
||||
|
||||
describe('Traces ListView - Error and Empty States', () => {
|
||||
@@ -153,18 +145,11 @@ describe('Traces ListView - Error and Empty States', () => {
|
||||
});
|
||||
|
||||
// Order by controls should be interactive
|
||||
const comboboxes = screen.getAllByRole('combobox');
|
||||
expect(comboboxes.length).toBeGreaterThanOrEqual(2);
|
||||
|
||||
// Pagination controls should be present
|
||||
const previousButton = screen.getByRole('button', { name: /previous/i });
|
||||
const nextButton = screen.getByRole('button', { name: /next/i });
|
||||
expect(previousButton).toBeInTheDocument();
|
||||
expect(nextButton).toBeInTheDocument();
|
||||
expect(screen.getAllByRole('combobox').length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Options menu should be clickable
|
||||
const optionsButton = screen.getByText(/options_menu.options|options/i);
|
||||
expect(optionsButton).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByTestId('periscope-btn-options-traces'));
|
||||
await expect(screen.findByText('Edit columns')).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('allows interaction with controls in empty state', async () => {
|
||||
@@ -176,12 +161,11 @@ describe('Traces ListView - Error and Empty States', () => {
|
||||
});
|
||||
|
||||
// All controls should be interactive
|
||||
const comboboxes = screen.getAllByRole('combobox');
|
||||
expect(comboboxes.length).toBeGreaterThanOrEqual(2);
|
||||
expect(screen.getAllByRole('combobox').length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Options menu should be clickable
|
||||
const optionsButton = screen.getByText(/options_menu.options|options/i);
|
||||
expect(optionsButton).toBeInTheDocument();
|
||||
await userEvent.click(screen.getByTestId('periscope-btn-options-traces'));
|
||||
await expect(screen.findByText('Edit columns')).resolves.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -20,20 +20,15 @@ import {
|
||||
getFieldColumn,
|
||||
TracesTableRow,
|
||||
} from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { useOptionsMenu } from 'container/OptionsMenu';
|
||||
import { CustomTimeType } from 'container/TopNav/DateTimeSelectionV2/types';
|
||||
import TraceExplorerControls from 'container/TracesExplorer/Controls';
|
||||
import { getListViewQuery } from 'container/TracesExplorer/explorerUtils';
|
||||
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
|
||||
import SpanDrawer from 'container/TracesExplorer/SpanDrawer/SpanDrawer';
|
||||
import { useSpanDrawer } from 'container/TracesExplorer/SpanDrawer/useSpanDrawer';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { Pagination } from 'hooks/queryPagination';
|
||||
import { getDefaultPaginationConfig } from 'hooks/queryPagination/utils';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { getListOrderBy, setListOrderBy } from 'utils/explorerUtils';
|
||||
import { ArrowUp10, Minus } from '@signozhq/icons';
|
||||
import { AppState } from 'store/reducers';
|
||||
@@ -41,14 +36,9 @@ import { Warning } from 'types/api';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
|
||||
import {
|
||||
defaultSelectedColumns,
|
||||
PER_PAGE_OPTIONS,
|
||||
TIMESTAMP_FIELD,
|
||||
} from './configs';
|
||||
import { getTraceLink, transformSpanRows } from './utils';
|
||||
|
||||
import './ListView.styles.scss';
|
||||
import { defaultSelectedColumns, TIMESTAMP_FIELD } from './configs';
|
||||
import { useListViewInfiniteQuery } from './useListViewInfiniteQuery';
|
||||
import { getTraceLink } from './utils';
|
||||
|
||||
import styles from './ListView.module.scss';
|
||||
|
||||
@@ -94,12 +84,6 @@ function ListView({
|
||||
},
|
||||
});
|
||||
|
||||
const { queryData: paginationQueryData } = useUrlQueryData<Pagination>(
|
||||
QueryParams.pagination,
|
||||
);
|
||||
const paginationConfig =
|
||||
paginationQueryData ?? getDefaultPaginationConfig(PER_PAGE_OPTIONS);
|
||||
|
||||
// Empty selectFields makes the API return every span field.
|
||||
const requestQuery = useMemo(() => {
|
||||
const query = getListViewQuery(
|
||||
@@ -123,51 +107,26 @@ function ListView({
|
||||
minTime,
|
||||
stagedQuery,
|
||||
panelType,
|
||||
paginationConfig,
|
||||
],
|
||||
[
|
||||
stagedQuery,
|
||||
panelType,
|
||||
globalSelectedTime,
|
||||
paginationConfig,
|
||||
maxTime,
|
||||
minTime,
|
||||
],
|
||||
[stagedQuery, panelType, globalSelectedTime, maxTime, minTime],
|
||||
);
|
||||
|
||||
if (queryKeyRef) {
|
||||
queryKeyRef.current = queryKey;
|
||||
}
|
||||
|
||||
const { data, isFetching, isLoading, isError, error } = useGetQueryRange(
|
||||
{
|
||||
const { rows, warning, isFetching, isLoading, isError, error, loadMore } =
|
||||
useListViewInfiniteQuery({
|
||||
query: requestQuery,
|
||||
graphType: panelType,
|
||||
selectedTime: 'GLOBAL_TIME' as const,
|
||||
globalSelectedInterval: globalSelectedTime as CustomTimeType,
|
||||
params: {
|
||||
dataSource: 'traces',
|
||||
},
|
||||
tableParams: {
|
||||
pagination: paginationConfig,
|
||||
},
|
||||
},
|
||||
// ENTITY_VERSION_V4,
|
||||
ENTITY_VERSION_V5,
|
||||
{
|
||||
queryKey,
|
||||
enabled:
|
||||
// don't make api call while the time range state in redux is loading
|
||||
!timeRangeUpdateLoading && !!stagedQuery && panelType === PANEL_TYPES.LIST,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.payload) {
|
||||
setWarning(data?.warning);
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data?.payload, data?.warning]);
|
||||
setWarning(warning);
|
||||
}, [warning, setWarning]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isLoading || isFetching) {
|
||||
@@ -177,15 +136,8 @@ function ListView({
|
||||
}
|
||||
}, [isLoading, isFetching, setIsLoadingQueries]);
|
||||
|
||||
const dataLength =
|
||||
data?.payload?.data?.newResult?.data?.result[0]?.list?.length;
|
||||
const totalCount = useMemo(() => dataLength || 0, [dataLength]);
|
||||
|
||||
const queryTableDataResult = data?.payload?.data?.newResult?.data?.result;
|
||||
const queryTableData = useMemo(
|
||||
() => queryTableDataResult || [],
|
||||
[queryTableDataResult],
|
||||
);
|
||||
const { tableProps, openTraceColumn, drawerProps, onPressInside } =
|
||||
useSpanDrawer(rows);
|
||||
|
||||
const columns = useMemo<TableColumnDef<TracesTableRow>[]>(() => {
|
||||
const fields = [
|
||||
@@ -194,13 +146,11 @@ function ListView({
|
||||
(field) => field.name !== TIMESTAMP_FIELD.name,
|
||||
),
|
||||
];
|
||||
return fields.map((field) => getFieldColumn(field));
|
||||
}, [options?.selectColumns]);
|
||||
|
||||
const rows = useMemo(
|
||||
() => transformSpanRows(queryTableData),
|
||||
[queryTableData],
|
||||
);
|
||||
const fieldColumns = fields.map((field) =>
|
||||
getFieldColumn(field, PANEL_TYPES.LIST),
|
||||
);
|
||||
return [openTraceColumn, ...fieldColumns];
|
||||
}, [options?.selectColumns, openTraceColumn]);
|
||||
|
||||
const handleColumnOrderChange = useCallback(
|
||||
(cols: TableColumnDef<TracesTableRow>[]): void => {
|
||||
@@ -226,10 +176,10 @@ function ListView({
|
||||
|
||||
return (
|
||||
<div className={styles.container}>
|
||||
<div className="trace-explorer-controls">
|
||||
<div className={styles.controls}>
|
||||
{headerActions}
|
||||
<div className="order-by-container">
|
||||
<div className="order-by-label">
|
||||
<div className={styles.orderBy}>
|
||||
<div className={styles.orderByLabel}>
|
||||
Order by <Minus size={14} /> <ArrowUp10 size={14} />
|
||||
</div>
|
||||
|
||||
@@ -245,28 +195,30 @@ function ListView({
|
||||
selectedColumns={options?.selectColumns}
|
||||
/>
|
||||
|
||||
<TraceExplorerControls
|
||||
isLoading={isFetching}
|
||||
totalCount={totalCount}
|
||||
config={config}
|
||||
perPageOptions={PER_PAGE_OPTIONS}
|
||||
/>
|
||||
<TraceExplorerControls config={config} />
|
||||
</div>
|
||||
|
||||
<TracesTable
|
||||
data={rows}
|
||||
columns={columns}
|
||||
columnStorageKey={LOCALSTORAGE.TRACES_LIST_COLUMNS}
|
||||
panelType="LIST"
|
||||
getRowHref={getTraceLink}
|
||||
isLoading={isLoading}
|
||||
isFetching={isFetching}
|
||||
isError={isError}
|
||||
error={error}
|
||||
isFilterApplied={isFilterApplied}
|
||||
onColumnOrderChange={handleColumnOrderChange}
|
||||
onColumnRemove={config?.addColumn?.onRemove}
|
||||
/>
|
||||
{/* A press in the table or the drawer (a portal) keeps the drawer open. */}
|
||||
<div className={styles.drawerScope} onPointerDownCapture={onPressInside}>
|
||||
<TracesTable
|
||||
data={rows}
|
||||
columns={columns}
|
||||
columnStorageKey={LOCALSTORAGE.TRACES_LIST_COLUMNS}
|
||||
panelType="LIST"
|
||||
getRowHref={getTraceLink}
|
||||
{...tableProps}
|
||||
isLoading={isLoading}
|
||||
isFetching={isFetching}
|
||||
isError={isError}
|
||||
error={error}
|
||||
isFilterApplied={isFilterApplied}
|
||||
onColumnOrderChange={handleColumnOrderChange}
|
||||
onColumnRemove={config?.addColumn?.onRemove}
|
||||
onEndReached={loadMore}
|
||||
/>
|
||||
|
||||
<SpanDrawer {...drawerProps} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { useCallback, useMemo } from 'react';
|
||||
import { QueryKey, useInfiniteQuery } from 'react-query';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { DEFAULT_PER_PAGE_VALUE } from 'container/Controls/config';
|
||||
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
import { useKeepRowsForSameQuery } from 'container/TracesExplorer/TracesTable/useKeepRowsForSameQuery';
|
||||
import { GetMetricQueryRange } from 'lib/dashboard/getQueryResults';
|
||||
import { Warning } from 'types/api';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
|
||||
import { getListLimit, getNextPageOffset, transformSpanRows } from './utils';
|
||||
|
||||
type UseListViewInfiniteQueryParams = {
|
||||
query: Query;
|
||||
queryKey: QueryKey;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
type UseListViewInfiniteQueryResult = {
|
||||
rows: TracesTableRow[];
|
||||
warning: Warning | undefined;
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
error: Error | null;
|
||||
loadMore: () => void;
|
||||
};
|
||||
|
||||
export function useListViewInfiniteQuery({
|
||||
query,
|
||||
queryKey,
|
||||
enabled,
|
||||
}: UseListViewInfiniteQueryParams): UseListViewInfiniteQueryResult {
|
||||
const limit = getListLimit(query);
|
||||
|
||||
const {
|
||||
data,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isFetchingNextPage,
|
||||
isError,
|
||||
error,
|
||||
hasNextPage,
|
||||
fetchNextPage,
|
||||
isPreviousData,
|
||||
} = useInfiniteQuery({
|
||||
queryKey,
|
||||
queryFn: ({ pageParam = 0, signal }) =>
|
||||
GetMetricQueryRange(
|
||||
{
|
||||
query,
|
||||
graphType: PANEL_TYPES.LIST,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
// Every page reads the window in redux, so later pages cannot drift.
|
||||
globalSelectedInterval: 'custom',
|
||||
params: { dataSource: 'traces' },
|
||||
tableParams: {
|
||||
pagination: {
|
||||
offset: pageParam as number,
|
||||
limit: limit
|
||||
? Math.min(DEFAULT_PER_PAGE_VALUE, limit - (pageParam as number))
|
||||
: DEFAULT_PER_PAGE_VALUE,
|
||||
},
|
||||
},
|
||||
},
|
||||
ENTITY_VERSION_V5,
|
||||
undefined,
|
||||
signal,
|
||||
),
|
||||
getNextPageParam: (_lastPage, allPages) =>
|
||||
getNextPageOffset(
|
||||
allPages.map(
|
||||
(page) => page.payload.data.newResult.data.result?.[0]?.list?.length ?? 0,
|
||||
),
|
||||
DEFAULT_PER_PAGE_VALUE,
|
||||
limit,
|
||||
),
|
||||
keepPreviousData: true,
|
||||
enabled,
|
||||
});
|
||||
|
||||
const keepRows = useKeepRowsForSameQuery(isPreviousData);
|
||||
|
||||
const rows = useMemo(
|
||||
() =>
|
||||
keepRows
|
||||
? (data?.pages ?? []).flatMap((page) =>
|
||||
transformSpanRows(page.payload.data.newResult.data.result ?? []),
|
||||
)
|
||||
: [],
|
||||
[data?.pages, keepRows],
|
||||
);
|
||||
|
||||
const loadMore = useCallback((): void => {
|
||||
if (hasNextPage && !isFetchingNextPage) {
|
||||
void fetchNextPage();
|
||||
}
|
||||
}, [hasNextPage, isFetchingNextPage, fetchNextPage]);
|
||||
|
||||
return {
|
||||
rows,
|
||||
warning: data?.pages[data.pages.length - 1]?.warning,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
error: error as Error | null,
|
||||
loadMore,
|
||||
};
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import { TimestampInput } from 'hooks/useTimezoneFormatter/useTimezoneFormatter'
|
||||
import { RowData } from 'lib/query/createTableColumnsFromQuery';
|
||||
import LineClampedText from 'periscope/components/LineClampedText/LineClampedText';
|
||||
import { ILog } from 'types/api/logs/log';
|
||||
import { Query } from 'types/api/queryBuilder/queryBuilderData';
|
||||
import { QueryDataV3 } from 'types/api/widgets/getQuery';
|
||||
|
||||
export function BlockLink({
|
||||
@@ -178,3 +179,23 @@ export const transformSpanRows = (data: QueryDataV3[]): TracesTableRow[] => {
|
||||
};
|
||||
}) as TracesTableRow[];
|
||||
};
|
||||
|
||||
export const getListLimit = (query: Query): number | null =>
|
||||
query.builder.queryTraceOperator?.[0]?.limit ??
|
||||
query.builder.queryData[0]?.limit ??
|
||||
null;
|
||||
|
||||
/** Offset of the next page, or undefined once a short page or the limit ends the list. */
|
||||
export const getNextPageOffset = (
|
||||
pageLengths: number[],
|
||||
pageSize: number,
|
||||
limit: number | null,
|
||||
): number | undefined => {
|
||||
const loaded = pageLengths.reduce((sum, length) => sum + length, 0);
|
||||
const lastLength = pageLengths[pageLengths.length - 1] ?? 0;
|
||||
|
||||
if (lastLength < pageSize || (limit && loaded >= limit)) {
|
||||
return undefined;
|
||||
}
|
||||
return loaded;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
// One text line tall, so the taller button overflows into the cell padding
|
||||
// instead of growing the row on hover.
|
||||
.slot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
height: var(--tanstack-plain-cell-line-height, 20px);
|
||||
overflow: visible;
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import { MouseEvent } from 'react';
|
||||
import { CornerUpRight } from '@signozhq/icons';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { useIsRowHovered } from 'components/TanStackTableView/TanStackTableStateContext';
|
||||
import {
|
||||
logOpenTraceClicked,
|
||||
OpenTraceSource,
|
||||
} from 'container/TracesExplorer/events';
|
||||
import { getTraceLink } from 'container/TracesExplorer/ListView/utils';
|
||||
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
|
||||
import styles from './OpenTraceButton.module.scss';
|
||||
|
||||
type OpenTraceButtonProps = {
|
||||
row: TracesTableRow;
|
||||
rowId: string;
|
||||
};
|
||||
|
||||
function OpenTraceButton({
|
||||
row,
|
||||
rowId,
|
||||
}: OpenTraceButtonProps): JSX.Element | null {
|
||||
const isHovered = useIsRowHovered(rowId);
|
||||
|
||||
const handleClick = (event: MouseEvent): void => {
|
||||
// The row click would open the drawer instead.
|
||||
event.stopPropagation();
|
||||
logOpenTraceClicked(PANEL_TYPES.LIST, OpenTraceSource.RowIcon);
|
||||
openInNewTab(getTraceLink(row));
|
||||
};
|
||||
|
||||
if (!isHovered) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<span className={styles.slot}>
|
||||
<Tooltip title="Open trace details">
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="sm"
|
||||
icon
|
||||
onClick={handleClick}
|
||||
aria-label="Open trace details"
|
||||
testId="span-row-open-trace"
|
||||
>
|
||||
<CornerUpRight size={14} />
|
||||
</Button>
|
||||
</Tooltip>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
export default OpenTraceButton;
|
||||
120
frontend/src/container/TracesExplorer/SpanDrawer/SpanDrawer.tsx
Normal file
120
frontend/src/container/TracesExplorer/SpanDrawer/SpanDrawer.tsx
Normal file
@@ -0,0 +1,120 @@
|
||||
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';
|
||||
import {
|
||||
logOpenTraceClicked,
|
||||
OpenTraceSource,
|
||||
} from 'container/TracesExplorer/events';
|
||||
import { getTraceLink } from 'container/TracesExplorer/ListView/utils';
|
||||
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
import { SpanDetailVariant } from 'pages/TraceDetailsV3/SpanDetailsPanel/constants';
|
||||
import SpanDetailsPanel from 'pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel';
|
||||
import { openInNewTab } from 'utils/navigation';
|
||||
|
||||
import { useArrowKeyNavigation } from './useArrowKeyNavigation';
|
||||
import { toSpanV3 } from './utils';
|
||||
|
||||
export type SpanDrawerProps = {
|
||||
row: TracesTableRow | null;
|
||||
onClose: () => void;
|
||||
navigation: UseRowNavigationResult;
|
||||
};
|
||||
|
||||
function SpanDrawer({
|
||||
row,
|
||||
onClose,
|
||||
navigation,
|
||||
}: SpanDrawerProps): JSX.Element {
|
||||
const { goToPrev, goToNext, isPrevDisabled, isNextDisabled } = navigation;
|
||||
const isOpen = row !== null;
|
||||
|
||||
useArrowKeyNavigation({ enabled: isOpen, onPrev: goToPrev, onNext: goToNext });
|
||||
|
||||
const panelState = useMemo(
|
||||
() => ({ isOpen, open: (): void => {}, close: onClose }),
|
||||
[isOpen, onClose],
|
||||
);
|
||||
|
||||
const headerActions = useMemo((): HeaderAction[] => {
|
||||
if (!row) {
|
||||
return [];
|
||||
}
|
||||
return [
|
||||
{
|
||||
key: 'view-full-trace',
|
||||
component: (
|
||||
<Button
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="md"
|
||||
prefix={<CornerUpRight />}
|
||||
onClick={(): void => {
|
||||
logOpenTraceClicked(PANEL_TYPES.LIST, OpenTraceSource.SpanDrawer);
|
||||
openInNewTab(getTraceLink(row));
|
||||
}}
|
||||
testId="span-drawer-view-full-trace"
|
||||
>
|
||||
View full trace
|
||||
</Button>
|
||||
),
|
||||
},
|
||||
{
|
||||
key: 'nav',
|
||||
component: (
|
||||
<ButtonGroup
|
||||
variant="outlined"
|
||||
color="secondary"
|
||||
size="md"
|
||||
testId="span-drawer-nav"
|
||||
items={[
|
||||
{
|
||||
value: 'prev',
|
||||
icon: <ChevronUp />,
|
||||
ariaLabel: 'Previous span',
|
||||
onClick: goToPrev,
|
||||
disabled: isPrevDisabled,
|
||||
disabledTooltip: 'No previous span on this page',
|
||||
},
|
||||
{
|
||||
value: 'next',
|
||||
icon: <ChevronDown />,
|
||||
ariaLabel: 'Next span',
|
||||
onClick: goToNext,
|
||||
disabled: isNextDisabled,
|
||||
disabledTooltip: 'No next span on this page',
|
||||
},
|
||||
]}
|
||||
/>
|
||||
),
|
||||
},
|
||||
];
|
||||
}, [row, goToPrev, goToNext, isPrevDisabled, isNextDisabled]);
|
||||
|
||||
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 } },
|
||||
);
|
||||
|
||||
return (
|
||||
<SpanDetailsPanel
|
||||
panelState={panelState}
|
||||
selectedSpan={span}
|
||||
variant={SpanDetailVariant.DRAWER}
|
||||
headerActions={headerActions}
|
||||
traceStartTime={traceSummary?.data?.startTimestampMillis}
|
||||
traceEndTime={traceSummary?.data?.endTimestampMillis}
|
||||
isTraceBoundsLoading={isTraceBoundsLoading}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export default SpanDrawer;
|
||||
@@ -0,0 +1,39 @@
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useArrowKeyNavigation } from '../useArrowKeyNavigation';
|
||||
|
||||
const pressArrowDown = ({ handled }: { handled: boolean }): void => {
|
||||
const event = new KeyboardEvent('keydown', {
|
||||
key: 'ArrowDown',
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
if (handled) {
|
||||
event.preventDefault();
|
||||
}
|
||||
document.body.dispatchEvent(event);
|
||||
};
|
||||
|
||||
describe('useArrowKeyNavigation', () => {
|
||||
it('steps to the next span on ArrowDown', () => {
|
||||
const onNext = jest.fn() as jest.MockedFunction<() => void>;
|
||||
renderHook(() =>
|
||||
useArrowKeyNavigation({ enabled: true, onPrev: jest.fn(), onNext }),
|
||||
);
|
||||
|
||||
pressArrowDown({ handled: false });
|
||||
|
||||
expect(onNext).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('ignores a key that a focused menu already handled', () => {
|
||||
const onNext = jest.fn() as jest.MockedFunction<() => void>;
|
||||
renderHook(() =>
|
||||
useArrowKeyNavigation({ enabled: true, onPrev: jest.fn(), onNext }),
|
||||
);
|
||||
|
||||
pressArrowDown({ handled: true });
|
||||
|
||||
expect(onNext).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
import { toSpanV3 } from '../utils';
|
||||
|
||||
describe('toSpanV3', () => {
|
||||
const row = {
|
||||
id: '772c4d29dd9076ac',
|
||||
span_id: '772c4d29dd9076ac',
|
||||
timestamp: '2024-07-19T08:39:58.735Z',
|
||||
resource: { 'service.name': 'frontend' },
|
||||
events: [
|
||||
{
|
||||
name: 'exception',
|
||||
timeUnixNano: 1721378398735000000,
|
||||
attributes: { 'exception.type': 'Error' },
|
||||
},
|
||||
],
|
||||
links: [{ traceId: 'a364a8e15af3e9a8', spanId: '5704353737b6778e' }],
|
||||
};
|
||||
|
||||
it('reshapes a list row into the span the details panel reads', () => {
|
||||
const span = toSpanV3(row);
|
||||
|
||||
expect(span.timestamp).toBe(Date.UTC(2024, 6, 19, 8, 39, 58, 735));
|
||||
expect(span['service.name']).toBe('frontend');
|
||||
expect(span.events).toStrictEqual([
|
||||
{
|
||||
name: 'exception',
|
||||
timeUnixNano: 1721378398735000000,
|
||||
attributeMap: { 'exception.type': 'Error' },
|
||||
isError: false,
|
||||
},
|
||||
]);
|
||||
expect((span as unknown as { references: unknown }).references).toStrictEqual(
|
||||
row.links,
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the parent from the linked spans', () => {
|
||||
const link = { traceId: 'a364a8e15af3e9a8', spanId: '5704353737b6778e' };
|
||||
const parent = { traceId: '1f2e3d4c5b6a7980', spanId: '0aa1bb2cc3dd4ee5' };
|
||||
const span = toSpanV3({
|
||||
...row,
|
||||
trace_id: parent.traceId,
|
||||
parent_span_id: parent.spanId,
|
||||
links: [parent, link, { ...parent, traceId: link.traceId }],
|
||||
});
|
||||
|
||||
expect((span as unknown as { references: unknown }).references).toStrictEqual(
|
||||
[link, { ...parent, traceId: link.traceId }],
|
||||
);
|
||||
});
|
||||
|
||||
it('drops the empty parent ref of a root span', () => {
|
||||
const span = toSpanV3({
|
||||
...row,
|
||||
trace_id: 'a364a8e15af3e9a8',
|
||||
parent_span_id: '',
|
||||
links: [{ traceId: 'a364a8e15af3e9a8' }],
|
||||
});
|
||||
|
||||
expect((span as unknown as { references: unknown }).references).toStrictEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
it('defaults missing events, links and service name', () => {
|
||||
const span = toSpanV3({ id: 'x', timestamp: row.timestamp });
|
||||
|
||||
expect(span.events).toStrictEqual([]);
|
||||
expect(span['service.name']).toBe('');
|
||||
expect((span as unknown as { references: unknown }).references).toStrictEqual(
|
||||
[],
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { TableColumnDef } from 'components/TanStackTableView/types';
|
||||
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
|
||||
import OpenTraceButton from './OpenTraceButton';
|
||||
|
||||
export const OPEN_TRACE_COLUMN: TableColumnDef<TracesTableRow> = {
|
||||
id: 'open-trace',
|
||||
header: '',
|
||||
pin: 'left',
|
||||
enableMove: false,
|
||||
enableResize: false,
|
||||
enableRemove: false,
|
||||
canBeHidden: false,
|
||||
width: { fixed: 32 },
|
||||
cell: ({ row, rowId }): JSX.Element => (
|
||||
<OpenTraceButton row={row} rowId={rowId} />
|
||||
),
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
import { useEffect } from 'react';
|
||||
|
||||
const EDITABLE_TARGET = 'input, textarea, [contenteditable="true"], .cm-editor';
|
||||
|
||||
type UseArrowKeyNavigationParams = {
|
||||
enabled: boolean;
|
||||
onPrev: () => void;
|
||||
onNext: () => void;
|
||||
};
|
||||
|
||||
export function useArrowKeyNavigation({
|
||||
enabled,
|
||||
onPrev,
|
||||
onNext,
|
||||
}: UseArrowKeyNavigationParams): void {
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const handleKeyDown = (e: KeyboardEvent): void => {
|
||||
// A focused menu or listbox already used the key.
|
||||
if (e.defaultPrevented) {
|
||||
return;
|
||||
}
|
||||
if (e.altKey || e.ctrlKey || e.metaKey || e.shiftKey) {
|
||||
return;
|
||||
}
|
||||
if (e.target instanceof Element && e.target.closest(EDITABLE_TARGET)) {
|
||||
return;
|
||||
}
|
||||
if (e.key === 'ArrowUp') {
|
||||
e.preventDefault();
|
||||
onPrev();
|
||||
} else if (e.key === 'ArrowDown') {
|
||||
e.preventDefault();
|
||||
onNext();
|
||||
}
|
||||
};
|
||||
|
||||
document.addEventListener('keydown', handleKeyDown);
|
||||
return (): void => {
|
||||
document.removeEventListener('keydown', handleKeyDown);
|
||||
};
|
||||
}, [enabled, onPrev, onNext]);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import {
|
||||
PointerEvent,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useMemo,
|
||||
useRef,
|
||||
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';
|
||||
|
||||
type ActiveSpan = { id: string; index: number };
|
||||
|
||||
type UseSpanDrawerResult = {
|
||||
tableProps: Pick<
|
||||
TracesTableProps,
|
||||
'onRowClick' | 'isRowActive' | 'activeRowIndex'
|
||||
>;
|
||||
/** Leading column that opens the trace page. */
|
||||
openTraceColumn: TableColumnDef<TracesTableRow>;
|
||||
drawerProps: SpanDrawerProps;
|
||||
/** `onPointerDownCapture` for the area a press keeps the drawer open in. */
|
||||
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 activeRowIndex = useMemo(() => {
|
||||
if (!activeSpan) {
|
||||
return -1;
|
||||
}
|
||||
return rows[activeSpan.index]?.id === activeSpan.id
|
||||
? activeSpan.index
|
||||
: rows.findIndex((row) => row.id === activeSpan.id);
|
||||
}, [rows, activeSpan]);
|
||||
|
||||
const isRowActive = useCallback(
|
||||
(row: TracesTableRow): boolean => row === rows[activeRowIndex],
|
||||
[rows, activeRowIndex],
|
||||
);
|
||||
|
||||
const handleNavigate = useCallback(
|
||||
(row: TracesTableRow, index: number): void => {
|
||||
setActiveSpan({ id: row.id, index });
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const selectRow = useCallback(
|
||||
(row: TracesTableRow): void => handleNavigate(row, rows.indexOf(row)),
|
||||
[handleNavigate, rows],
|
||||
);
|
||||
|
||||
const clearActiveSpan = useCallback((): void => setActiveSpan(null), []);
|
||||
|
||||
// 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 navigation = useRowNavigation({
|
||||
rows,
|
||||
activeIndex: activeRowIndex,
|
||||
onNavigate: handleNavigate,
|
||||
});
|
||||
|
||||
return {
|
||||
tableProps: {
|
||||
onRowClick: selectRow,
|
||||
isRowActive,
|
||||
activeRowIndex,
|
||||
},
|
||||
openTraceColumn: OPEN_TRACE_COLUMN,
|
||||
drawerProps: {
|
||||
row: rows[activeRowIndex] ?? null,
|
||||
onClose: clearActiveSpan,
|
||||
navigation,
|
||||
},
|
||||
onPressInside,
|
||||
};
|
||||
}
|
||||
40
frontend/src/container/TracesExplorer/SpanDrawer/utils.ts
Normal file
40
frontend/src/container/TracesExplorer/SpanDrawer/utils.ts
Normal file
@@ -0,0 +1,40 @@
|
||||
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
type ListSpanEvent = {
|
||||
name: string;
|
||||
timeUnixNano: number;
|
||||
attributes?: Record<string, string>;
|
||||
isError?: boolean;
|
||||
};
|
||||
|
||||
type ListSpanLink = { traceId: string; spanId: string };
|
||||
|
||||
/**
|
||||
* The list API returns a span in a different shape from the trace API the
|
||||
* details panel was built on: an ISO timestamp, `attributes` on events, and
|
||||
* `links` in place of `references`.
|
||||
*/
|
||||
export const toSpanV3 = (row: TracesTableRow): SpanV3 => {
|
||||
const resource = (row.resource ?? {}) as Record<string, string>;
|
||||
const events = (row.events ?? []) as ListSpanEvent[];
|
||||
const links = (row.links ?? []) as ListSpanLink[];
|
||||
|
||||
return {
|
||||
...row,
|
||||
timestamp: new Date(row.timestamp as string).getTime(),
|
||||
'service.name': resource['service.name'] ?? '',
|
||||
events: events.map(({ attributes, isError, ...event }) => ({
|
||||
...event,
|
||||
attributeMap: attributes ?? {},
|
||||
isError: isError ?? false,
|
||||
})),
|
||||
// The list API drops `refType`, so the parent ref is matched by id. A root
|
||||
// span's parent ref has no span id.
|
||||
references: links.filter(
|
||||
(link) =>
|
||||
!!link.spanId &&
|
||||
(link.spanId !== row.parent_span_id || link.traceId !== row.trace_id),
|
||||
),
|
||||
} as unknown as SpanV3;
|
||||
};
|
||||
@@ -0,0 +1,4 @@
|
||||
.emptyValue {
|
||||
display: block;
|
||||
color: var(--l2-border);
|
||||
}
|
||||
@@ -1,9 +1,15 @@
|
||||
import { AppLink } from 'lib/router/AppLink';
|
||||
import { buildRoutePath } from 'lib/router/buildRoutePath';
|
||||
import { Minus } from '@signozhq/icons';
|
||||
import { Badge } from '@signozhq/ui/badge';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { DATE_TIME_FORMATS } from 'constants/dateTimeFormats';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import ROUTES from 'constants/routes';
|
||||
import {
|
||||
logOpenTraceClicked,
|
||||
OpenTraceSource,
|
||||
} from 'container/TracesExplorer/events';
|
||||
import { getMs } from 'utils/timeUtils';
|
||||
import { useTimezone } from 'providers/Timezone';
|
||||
|
||||
@@ -15,12 +21,15 @@ import {
|
||||
} from './constants';
|
||||
import { stringifyCellValue } from './utils';
|
||||
|
||||
import styles from './FieldCell.module.scss';
|
||||
|
||||
type FieldCellProps = {
|
||||
name: string;
|
||||
value: unknown;
|
||||
panelType: PANEL_TYPES;
|
||||
};
|
||||
|
||||
function FieldCell({ name, value }: FieldCellProps): JSX.Element {
|
||||
function FieldCell({ name, value, panelType }: FieldCellProps): JSX.Element {
|
||||
const { formatTimezoneAdjustedTimestamp } = useTimezone();
|
||||
|
||||
if (TIMESTAMP_FIELD_NAMES.has(name)) {
|
||||
@@ -37,7 +46,11 @@ function FieldCell({ name, value }: FieldCellProps): JSX.Element {
|
||||
}
|
||||
|
||||
if (value === '' || value == null) {
|
||||
return <TanStackTable.Text data-testid={name}>-</TanStackTable.Text>;
|
||||
return (
|
||||
<TanStackTable.Text data-testid={name}>
|
||||
<Minus size={14} className={styles.emptyValue} data-testid="empty-value" />
|
||||
</TanStackTable.Text>
|
||||
);
|
||||
}
|
||||
|
||||
const text = stringifyCellValue(value);
|
||||
@@ -47,7 +60,15 @@ function FieldCell({ name, value }: FieldCellProps): JSX.Element {
|
||||
<AppLink
|
||||
to={buildRoutePath(ROUTES.TRACE_DETAIL, { id: text })}
|
||||
data-testid="trace-id"
|
||||
onClick={(e): void => e.stopPropagation()}
|
||||
onClick={(e): void => {
|
||||
e.stopPropagation();
|
||||
logOpenTraceClicked(panelType, OpenTraceSource.TraceId);
|
||||
}}
|
||||
onAuxClick={(e): void => {
|
||||
if (e.button === 1) {
|
||||
logOpenTraceClicked(panelType, OpenTraceSource.TraceId);
|
||||
}
|
||||
}}
|
||||
>
|
||||
{text}
|
||||
</AppLink>
|
||||
|
||||
@@ -6,21 +6,7 @@
|
||||
}
|
||||
|
||||
.tracesTable {
|
||||
--tanstack-table-row-height: 54px;
|
||||
--tanstack-table-header-height: 54px;
|
||||
|
||||
--tanstack-cell-padding-top-override: 5px;
|
||||
--tanstack-cell-padding-bottom-override: 5px;
|
||||
--tanstack-cell-padding-right-override: 15px;
|
||||
|
||||
--tanstack-cell-padding-left-override: 15px;
|
||||
--tanstack-cell-header-padding-left-override: 5px;
|
||||
|
||||
--tanstack-cell-header-padding-left-first-column: 15px;
|
||||
|
||||
--tanstack-plain-body-line-clamp: 1;
|
||||
|
||||
--tanstack-table-cell-bg: var(--l2-background);
|
||||
--tanstack-table-header-cell-bg: var(--l1-background-hover);
|
||||
--tanstack-table-row-hover-bg: var(--l1-background-hover);
|
||||
--tanstack-table-row-height: 30px;
|
||||
--tanstack-table-row-hover-bg: var(--l2-background-hover);
|
||||
--tanstack-table-row-active-bg: var(--l3-background-60);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,30 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useCallback, useRef } from 'react';
|
||||
import { useAppNavigate } from 'lib/router/useAppNavigate';
|
||||
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
|
||||
import TanStackTable from 'components/TanStackTableView';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import type {
|
||||
CellTypographySize,
|
||||
TableColumnDef,
|
||||
} from 'components/TanStackTableView/types';
|
||||
import { useRecoverFromEmptyPage } from 'components/TanStackTableView/useRecoverFromEmptyPage';
|
||||
import EmptyLogsSearch from 'container/EmptyLogsSearch/EmptyLogsSearch';
|
||||
import NoLogs from 'container/NoLogs/NoLogs';
|
||||
import { TracesLoading } from 'container/TracesExplorer/TraceLoading/TraceLoading';
|
||||
import {
|
||||
logOpenTraceClicked,
|
||||
OpenTraceSource,
|
||||
} from 'container/TracesExplorer/events';
|
||||
import APIError from 'types/api/error';
|
||||
import { DataSource, PanelTypeKeys } from 'types/common/queryBuilder';
|
||||
import { noop } from 'lodash-es';
|
||||
import { getAbsoluteUrl } from 'utils/basePath';
|
||||
|
||||
import { TRACES_TABLE_QUERY_PARAMS } from './constants';
|
||||
import type { TracesTableRow } from './getFieldColumn';
|
||||
import type { TracesTablePagination } from './useTracesTablePagination';
|
||||
import { getRollingTotal, getRowKey } from './utils';
|
||||
|
||||
import styles from './TracesTable.module.scss';
|
||||
|
||||
export type TracesTableProps = {
|
||||
@@ -24,6 +35,10 @@ export type TracesTableProps = {
|
||||
panelType: PanelTypeKeys;
|
||||
/** Builds the trace-detail href for a row; drives row click + cmd/ctrl-click. */
|
||||
getRowHref: (row: TracesTableRow) => string;
|
||||
/** Replaces the default row click, which opens the trace detail page. */
|
||||
onRowClick?: (row: TracesTableRow) => void;
|
||||
isRowActive?: (row: TracesTableRow) => boolean;
|
||||
activeRowIndex?: number;
|
||||
isLoading: boolean;
|
||||
isFetching: boolean;
|
||||
isError: boolean;
|
||||
@@ -32,6 +47,9 @@ export type TracesTableProps = {
|
||||
onColumnOrderChange?: (cols: TableColumnDef<TracesTableRow>[]) => void;
|
||||
onColumnRemove?: (columnId: string) => void;
|
||||
cellTypographySize?: CellTypographySize;
|
||||
pagination?: TracesTablePagination;
|
||||
/** Loads the next page when the scroll reaches the last row; hides the pager. */
|
||||
onEndReached?: () => void;
|
||||
};
|
||||
|
||||
function TracesTable({
|
||||
@@ -41,6 +59,9 @@ function TracesTable({
|
||||
respectColumnOrder = false,
|
||||
panelType,
|
||||
getRowHref,
|
||||
onRowClick,
|
||||
isRowActive,
|
||||
activeRowIndex,
|
||||
isLoading,
|
||||
isFetching,
|
||||
isError,
|
||||
@@ -49,24 +70,54 @@ function TracesTable({
|
||||
onColumnOrderChange,
|
||||
onColumnRemove,
|
||||
cellTypographySize = 'medium',
|
||||
pagination,
|
||||
onEndReached,
|
||||
}: TracesTableProps): JSX.Element {
|
||||
const navigate = useAppNavigate();
|
||||
|
||||
// While the next page loads, `data` is still the previous page, so its rows
|
||||
// cannot size the total for the new offset.
|
||||
const settledTotalRef = useRef(0);
|
||||
if (pagination && !isFetching) {
|
||||
settledTotalRef.current = getRollingTotal(
|
||||
pagination.request.offset,
|
||||
data.length,
|
||||
pagination.limit,
|
||||
);
|
||||
}
|
||||
const total = settledTotalRef.current;
|
||||
|
||||
useRecoverFromEmptyPage({
|
||||
page: pagination?.page ?? 1,
|
||||
pageSize: pagination?.limit ?? 0,
|
||||
rowCount: data.length,
|
||||
total,
|
||||
isFetching: isLoading || isFetching,
|
||||
isDisabled: !pagination || isError,
|
||||
setPage: pagination?.setPage ?? noop,
|
||||
});
|
||||
|
||||
const isDataAbsent =
|
||||
!isLoading && !isFetching && !isError && data.length === 0;
|
||||
|
||||
const handleRowClick = useCallback(
|
||||
(row: TracesTableRow): void => {
|
||||
if (onRowClick) {
|
||||
onRowClick(row);
|
||||
return;
|
||||
}
|
||||
logOpenTraceClicked(PANEL_TYPES[panelType], OpenTraceSource.Row);
|
||||
navigate(getRowHref(row));
|
||||
},
|
||||
[navigate, getRowHref],
|
||||
[onRowClick, navigate, getRowHref, panelType],
|
||||
);
|
||||
|
||||
const handleRowClickNewTab = useCallback(
|
||||
(row: TracesTableRow): void => {
|
||||
logOpenTraceClicked(PANEL_TYPES[panelType], OpenTraceSource.Row);
|
||||
window.open(getAbsoluteUrl(getRowHref(row)), '_blank', 'noopener');
|
||||
},
|
||||
[getRowHref],
|
||||
[getRowHref, panelType],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -97,8 +148,21 @@ function TracesTable({
|
||||
onColumnRemove={onColumnRemove}
|
||||
onRowClick={handleRowClick}
|
||||
onRowClickNewTab={handleRowClickNewTab}
|
||||
isRowActive={isRowActive}
|
||||
activeRowIndex={activeRowIndex}
|
||||
getRowKey={getRowKey}
|
||||
getRowTestId={(row): string => `traces-table-row-${row.id}`}
|
||||
testId={`traces-table-${panelType.toLowerCase()}`}
|
||||
onEndReached={onEndReached}
|
||||
enableQueryParams={pagination ? TRACES_TABLE_QUERY_PARAMS : undefined}
|
||||
pagination={
|
||||
pagination && {
|
||||
total,
|
||||
defaultLimit: pagination.limit,
|
||||
showTotalCount: false,
|
||||
onLimitChange: pagination.setLimit,
|
||||
}
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
@@ -109,9 +173,14 @@ function TracesTable({
|
||||
TracesTable.defaultProps = {
|
||||
columnStorageKey: undefined,
|
||||
respectColumnOrder: false,
|
||||
onRowClick: undefined,
|
||||
isRowActive: undefined,
|
||||
activeRowIndex: undefined,
|
||||
onColumnOrderChange: undefined,
|
||||
onColumnRemove: undefined,
|
||||
cellTypographySize: 'medium',
|
||||
pagination: undefined,
|
||||
onEndReached: undefined,
|
||||
};
|
||||
|
||||
export default TracesTable;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { renderHook } from 'tests/test-utils';
|
||||
|
||||
import { useKeepRowsForSameQuery } from '../useKeepRowsForSameQuery';
|
||||
|
||||
let mockQueryId = 'query-1';
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: (): unknown => ({ stagedQuery: { id: mockQueryId } }),
|
||||
}));
|
||||
|
||||
describe('useKeepRowsForSameQuery', () => {
|
||||
beforeEach(() => {
|
||||
mockQueryId = 'query-1';
|
||||
});
|
||||
|
||||
it('keeps the old rows while the same query refetches', () => {
|
||||
const { result, rerender } = renderHook(
|
||||
({ isPreviousData }: { isPreviousData: boolean }) =>
|
||||
useKeepRowsForSameQuery(isPreviousData),
|
||||
{ initialProps: { isPreviousData: false } },
|
||||
);
|
||||
|
||||
rerender({ isPreviousData: true });
|
||||
expect(result.current).toBe(true);
|
||||
});
|
||||
|
||||
it('drops the old rows once a new query runs, until its rows land', () => {
|
||||
const { result, rerender } = renderHook(
|
||||
({ isPreviousData }: { isPreviousData: boolean }) =>
|
||||
useKeepRowsForSameQuery(isPreviousData),
|
||||
{ initialProps: { isPreviousData: false } },
|
||||
);
|
||||
|
||||
mockQueryId = 'query-2';
|
||||
rerender({ isPreviousData: true });
|
||||
expect(result.current).toBe(false);
|
||||
|
||||
rerender({ isPreviousData: false });
|
||||
expect(result.current).toBe(true);
|
||||
|
||||
rerender({ isPreviousData: true });
|
||||
expect(result.current).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,72 @@
|
||||
import { ReactNode } from 'react';
|
||||
import { NuqsTestingAdapter, UrlUpdateEvent } from 'nuqs/adapters/testing';
|
||||
import { renderHook, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { useTracesTablePagination } from '../useTracesTablePagination';
|
||||
|
||||
let mockQueryId = 'query-1';
|
||||
jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
|
||||
useQueryBuilder: (): unknown => ({ stagedQuery: { id: mockQueryId } }),
|
||||
}));
|
||||
|
||||
const renderPagination = (
|
||||
searchParams: Record<string, string>,
|
||||
): {
|
||||
offsets: number[];
|
||||
urlUpdates: UrlUpdateEvent[];
|
||||
rerender: () => void;
|
||||
} => {
|
||||
const offsets: number[] = [];
|
||||
const urlUpdates: UrlUpdateEvent[] = [];
|
||||
const wrapper = ({ children }: { children: ReactNode }): JSX.Element => (
|
||||
<NuqsTestingAdapter
|
||||
searchParams={searchParams}
|
||||
onUrlUpdate={(event): void => {
|
||||
urlUpdates.push(event);
|
||||
}}
|
||||
hasMemory
|
||||
>
|
||||
{children}
|
||||
</NuqsTestingAdapter>
|
||||
);
|
||||
const { rerender } = renderHook(
|
||||
() => {
|
||||
const pagination = useTracesTablePagination();
|
||||
offsets.push(pagination.request.offset);
|
||||
return pagination;
|
||||
},
|
||||
{ wrapper },
|
||||
);
|
||||
return { offsets, urlUpdates, rerender };
|
||||
};
|
||||
|
||||
describe('useTracesTablePagination', () => {
|
||||
beforeEach(() => {
|
||||
mockQueryId = 'query-1';
|
||||
});
|
||||
|
||||
it('requests the page in the URL for the query it was picked on', () => {
|
||||
const { offsets, rerender } = renderPagination({ page: '3', limit: '10' });
|
||||
|
||||
rerender();
|
||||
|
||||
expect(new Set(offsets)).toStrictEqual(new Set([20]));
|
||||
});
|
||||
|
||||
it('requests the first page as soon as a new query runs, then resets the URL', async () => {
|
||||
const { offsets, urlUpdates, rerender } = renderPagination({
|
||||
page: '3',
|
||||
limit: '10',
|
||||
});
|
||||
const before = offsets.length;
|
||||
|
||||
mockQueryId = 'query-2';
|
||||
rerender();
|
||||
|
||||
expect(offsets.slice(before)).not.toContain(20);
|
||||
// Page 1 is the default, so the URL drops the param.
|
||||
await waitFor(() =>
|
||||
expect(urlUpdates.at(-1)?.searchParams.has('page')).toBe(false),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -16,3 +16,12 @@ export const STATUS_FIELD_NAMES = new Set([
|
||||
export const DURATION_FIELD_NAMES = new Set(['durationNano', 'duration_nano']);
|
||||
|
||||
export const TRACE_ID_FIELD_NAMES = new Set(['traceID', 'trace_id']);
|
||||
|
||||
export const TRACES_TABLE_QUERY_PARAMS = {
|
||||
page: 'page',
|
||||
limit: 'limit',
|
||||
} as const;
|
||||
|
||||
export const TRACES_TABLE_DEFAULT_LIMIT = 20;
|
||||
|
||||
export const TRACES_TABLE_PAGE_SIZE_KEY = 'traces-explorer';
|
||||
|
||||
@@ -2,6 +2,7 @@ import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView/types';
|
||||
import { buildCompositeKey } from 'container/OptionsMenu/utils';
|
||||
import { getSpanAttribute } from 'pages/TraceDetailsV3/utils';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
import { TIMESTAMP_FIELD_NAMES } from './constants';
|
||||
import FieldCell from './FieldCell';
|
||||
@@ -10,6 +11,7 @@ export type TracesTableRow = { id: string } & Record<string, unknown>;
|
||||
|
||||
export function getFieldColumn(
|
||||
field: TelemetryFieldKey,
|
||||
panelType: PANEL_TYPES,
|
||||
): TableColumnDef<TracesTableRow> {
|
||||
const { name, fieldContext, fieldDataType } = field;
|
||||
const isTimestamp = TIMESTAMP_FIELD_NAMES.has(name);
|
||||
@@ -25,6 +27,8 @@ export function getFieldColumn(
|
||||
enableRemove: !isTimestamp,
|
||||
canBeHidden: !isTimestamp,
|
||||
width: { min: 192 },
|
||||
cell: ({ value }): JSX.Element => <FieldCell name={name} value={value} />,
|
||||
cell: ({ value }): JSX.Element => (
|
||||
<FieldCell name={name} value={value} panelType={panelType} />
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
|
||||
/**
|
||||
* Whether rows kept from the previous request may stay on screen: yes while the
|
||||
* same query refetches (refresh, next page), no once a new query runs, so the
|
||||
* table shows its loader instead of the old query's rows.
|
||||
*/
|
||||
export function useKeepRowsForSameQuery(isPreviousData: boolean): boolean {
|
||||
const { stagedQuery } = useQueryBuilder();
|
||||
const queryId = stagedQuery?.id;
|
||||
const [loadedQueryId, setLoadedQueryId] = useState(queryId);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isPreviousData) {
|
||||
setLoadedQueryId(queryId);
|
||||
}
|
||||
}, [isPreviousData, queryId]);
|
||||
|
||||
return !isPreviousData || loadedQueryId === queryId;
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
SetPageOptions,
|
||||
useTableParams,
|
||||
} from 'components/TanStackTableView/useTableParams';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { Pagination } from 'hooks/queryPagination';
|
||||
|
||||
import {
|
||||
TRACES_TABLE_DEFAULT_LIMIT,
|
||||
TRACES_TABLE_PAGE_SIZE_KEY,
|
||||
TRACES_TABLE_QUERY_PARAMS,
|
||||
} from './constants';
|
||||
|
||||
export type TracesTablePagination = {
|
||||
page: number;
|
||||
limit: number;
|
||||
request: Pagination;
|
||||
setPage: (page: number, options?: SetPageOptions) => void;
|
||||
setLimit: (limit: number) => void;
|
||||
};
|
||||
|
||||
export function useTracesTablePagination(): TracesTablePagination {
|
||||
const { page, limit, setPage, setLimit } = useTableParams(
|
||||
TRACES_TABLE_QUERY_PARAMS,
|
||||
{
|
||||
page: 1,
|
||||
limit: TRACES_TABLE_DEFAULT_LIMIT,
|
||||
storageKey: TRACES_TABLE_PAGE_SIZE_KEY,
|
||||
},
|
||||
);
|
||||
|
||||
const { stagedQuery } = useQueryBuilder();
|
||||
const queryId = stagedQuery?.id;
|
||||
const [pageQueryId, setPageQueryId] = useState(queryId);
|
||||
// A page number only means something for the query it was picked on, so a
|
||||
// new query reads page 1 before the URL catches up.
|
||||
const isNewQuery = !!pageQueryId && pageQueryId !== queryId;
|
||||
const currentPage = isNewQuery ? 1 : page;
|
||||
|
||||
useEffect(() => {
|
||||
if (isNewQuery) {
|
||||
setPage(1, { history: 'replace' });
|
||||
}
|
||||
setPageQueryId(queryId);
|
||||
}, [isNewQuery, queryId, setPage]);
|
||||
|
||||
const request = useMemo(
|
||||
() => ({ offset: (currentPage - 1) * limit, limit }),
|
||||
[currentPage, limit],
|
||||
);
|
||||
|
||||
return { page: currentPage, limit, request, setPage, setLimit };
|
||||
}
|
||||
@@ -1,3 +1,5 @@
|
||||
import type { TracesTableRow } from './getFieldColumn';
|
||||
|
||||
export function stringifyCellValue(value: unknown): string {
|
||||
if (value == null) {
|
||||
return '';
|
||||
@@ -10,3 +12,20 @@ export function stringifyCellValue(value: unknown): string {
|
||||
}
|
||||
return JSON.stringify(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* The list API returns no total, so a full page counts one row past itself:
|
||||
* the pager offers the next page only while the last one came back full.
|
||||
*/
|
||||
export function getRollingTotal(
|
||||
offset: number,
|
||||
rowCount: number,
|
||||
limit: number,
|
||||
): number {
|
||||
return offset + rowCount + (rowCount >= limit ? 1 : 0);
|
||||
}
|
||||
|
||||
/** The API can return the same span twice; the table suffixes repeated keys so each row hovers on its own. */
|
||||
export function getRowKey(row: TracesTableRow): string {
|
||||
return row.id;
|
||||
}
|
||||
|
||||
@@ -10,6 +10,16 @@
|
||||
|
||||
.actionsContainer {
|
||||
display: flex;
|
||||
min-height: 40px;
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.controls {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import {
|
||||
OpenTraceSource,
|
||||
TracesExplorerEvents,
|
||||
} from 'container/TracesExplorer/events';
|
||||
import { getCurrentLocation } from 'lib/router/navigation';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { screen, userEvent, waitFor } from 'tests/test-utils';
|
||||
|
||||
import {
|
||||
groupedResponse,
|
||||
groupedRows,
|
||||
QUERY_RANGE_URL,
|
||||
renderTracesView,
|
||||
} from './testUtils';
|
||||
|
||||
jest.mock('api/common/logEvent');
|
||||
|
||||
describe('TracesView - open trace clicked', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, (_req, res, ctx) =>
|
||||
res(ctx.status(200), ctx.json(groupedResponse(groupedRows))),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('logs a row click that opens the trace page', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderTracesView();
|
||||
|
||||
await user.click(await screen.findByText('HTTP GET'));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(getCurrentLocation().pathname).toBe(
|
||||
'/trace/0000000000000000344ded1387b08a7e',
|
||||
),
|
||||
);
|
||||
expect(logEvent).toHaveBeenCalledWith(TracesExplorerEvents.OpenTraceClicked, {
|
||||
panelType: PANEL_TYPES.TRACE,
|
||||
source: OpenTraceSource.Row,
|
||||
});
|
||||
});
|
||||
|
||||
it('logs a trace_id link click', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderTracesView();
|
||||
|
||||
await user.click(await screen.findByText('0000000000000000344ded1387b08a7e'));
|
||||
|
||||
expect(logEvent).toHaveBeenCalledWith(TracesExplorerEvents.OpenTraceClicked, {
|
||||
panelType: PANEL_TYPES.TRACE,
|
||||
source: OpenTraceSource.TraceId,
|
||||
});
|
||||
expect(logEvent).not.toHaveBeenCalledWith(
|
||||
TracesExplorerEvents.OpenTraceClicked,
|
||||
{ panelType: PANEL_TYPES.TRACE, source: OpenTraceSource.Row },
|
||||
);
|
||||
});
|
||||
|
||||
it('logs a middle click on the trace_id link', async () => {
|
||||
const user = userEvent.setup();
|
||||
renderTracesView();
|
||||
|
||||
await user.pointer({
|
||||
keys: '[MouseMiddle]',
|
||||
target: await screen.findByText('0000000000000000344ded1387b08a7e'),
|
||||
});
|
||||
|
||||
expect(logEvent).toHaveBeenCalledWith(TracesExplorerEvents.OpenTraceClicked, {
|
||||
panelType: PANEL_TYPES.TRACE,
|
||||
source: OpenTraceSource.TraceId,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,84 @@
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { screen, userEvent, waitFor, within } from 'tests/test-utils';
|
||||
import { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
|
||||
import {
|
||||
groupedResponse,
|
||||
groupedRows,
|
||||
QUERY_RANGE_URL,
|
||||
renderTracesView,
|
||||
} from './testUtils';
|
||||
|
||||
// Answers each offset with `rowsPerOffset[offset]` rows and records the offsets asked for.
|
||||
// An offset in `held` answers once its promise resolves.
|
||||
const mockPages = (
|
||||
rowsPerOffset: Record<number, number>,
|
||||
held?: Record<number, Promise<void>>,
|
||||
): number[] => {
|
||||
const offsets: number[] = [];
|
||||
server.use(
|
||||
rest.post(QUERY_RANGE_URL, async (req, res, ctx) => {
|
||||
const body = (await req.json()) as QueryRangeRequestV5;
|
||||
const spec = body.compositeQuery.queries[0].spec as { offset?: number };
|
||||
const offset = spec.offset ?? 0;
|
||||
offsets.push(offset);
|
||||
await held?.[offset];
|
||||
const rows = Array.from({ length: rowsPerOffset[offset] ?? 0 }, (_, i) => ({
|
||||
...groupedRows[0],
|
||||
data: { ...groupedRows[0].data, trace_id: `trace-${offset + i}` },
|
||||
}));
|
||||
return res(ctx.status(200), ctx.json(groupedResponse(rows)));
|
||||
}),
|
||||
);
|
||||
return offsets;
|
||||
};
|
||||
|
||||
describe('TracesView pagination', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
});
|
||||
|
||||
it('offers the next page after a full page and requests its offset', async () => {
|
||||
const offsets = mockPages({ 0: 20, 20: 3 });
|
||||
const user = userEvent.setup();
|
||||
renderTracesView();
|
||||
|
||||
const next = await screen.findByRole('button', { name: 'Go to next page' });
|
||||
await waitFor(() => expect(next).toBeEnabled());
|
||||
await user.click(next);
|
||||
|
||||
await expect(screen.findByText('trace-22')).resolves.toBeInTheDocument();
|
||||
expect(offsets).toStrictEqual([0, 20]);
|
||||
});
|
||||
|
||||
it('offers no page past the next one until that page arrives', async () => {
|
||||
let release = (): void => {};
|
||||
const pageTwo = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
mockPages({ 0: 20, 20: 20 }, { 20: pageTwo });
|
||||
const user = userEvent.setup();
|
||||
renderTracesView();
|
||||
|
||||
const next = await screen.findByRole('button', { name: 'Go to next page' });
|
||||
await waitFor(() => expect(next).toBeEnabled());
|
||||
await user.click(next);
|
||||
|
||||
const pager = screen.getByLabelText('pagination');
|
||||
expect(within(pager).queryByText('3')).not.toBeInTheDocument();
|
||||
|
||||
release();
|
||||
await expect(within(pager).findByText('3')).resolves.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('offers no next page after a short page', async () => {
|
||||
mockPages({ 0: 3 });
|
||||
renderTracesView();
|
||||
|
||||
await screen.findAllByText('frontend');
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'Go to next page' }),
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render } from 'tests/test-utils';
|
||||
|
||||
import TracesView from '../index';
|
||||
|
||||
export const QUERY_RANGE_URL = `${ENVIRONMENT.baseURL}/api/v5/query_range`;
|
||||
|
||||
export const groupedRows = [
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:58.735245Z',
|
||||
data: {
|
||||
'service.name': 'frontend',
|
||||
name: 'HTTP GET',
|
||||
duration_nano: 55306000,
|
||||
span_count: 8,
|
||||
trace_id: '0000000000000000344ded1387b08a7e',
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:59.949129915Z',
|
||||
data: {
|
||||
'service.name': 'demo-app',
|
||||
// intentionally empty to assert the "-" cell
|
||||
name: '',
|
||||
duration_nano: 790949390,
|
||||
span_count: 3,
|
||||
trace_id: 'a364a8e15af3e9a8c866e0528db8b637',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const groupedResponse = (rows: unknown[]): Record<string, unknown> => ({
|
||||
data: { type: 'trace', data: { results: [{ queryName: 'A', rows }] } },
|
||||
});
|
||||
|
||||
export const renderTracesView = (
|
||||
props: Record<string, unknown> = {},
|
||||
): ReturnType<typeof render> =>
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight: 500, itemHeight: 54 }}>
|
||||
<TracesView
|
||||
isFilterApplied={false}
|
||||
setWarning={jest.fn()}
|
||||
setIsLoadingQueries={jest.fn()}
|
||||
{...props}
|
||||
/>
|
||||
</VirtuosoMockContext.Provider>,
|
||||
{},
|
||||
{
|
||||
initialRoute: '/traces-explorer',
|
||||
queryBuilderOverrides: {
|
||||
panelType: PANEL_TYPES.TRACE,
|
||||
stagedQuery: initialQueriesMap.traces,
|
||||
currentQuery: initialQueriesMap.traces,
|
||||
} as any,
|
||||
},
|
||||
);
|
||||
@@ -1,12 +1,10 @@
|
||||
import { TelemetryFieldKey } from 'api/v5/v5';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import type { TableColumnDef } from 'components/TanStackTableView/types';
|
||||
import {
|
||||
getFieldColumn,
|
||||
TracesTableRow,
|
||||
} from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
import { DEFAULT_PER_PAGE_OPTIONS } from 'hooks/queryPagination';
|
||||
|
||||
export const PER_PAGE_OPTIONS: number[] = [10, ...DEFAULT_PER_PAGE_OPTIONS];
|
||||
|
||||
const TRACE_FIELDS = [
|
||||
{ name: 'service.name', fieldContext: 'resource' },
|
||||
@@ -18,7 +16,7 @@ const TRACE_FIELDS = [
|
||||
|
||||
export const columns: TableColumnDef<TracesTableRow>[] = TRACE_FIELDS.map(
|
||||
(field) => ({
|
||||
...getFieldColumn(field),
|
||||
...getFieldColumn(field, PANEL_TYPES.TRACE),
|
||||
enableRemove: false,
|
||||
canBeHidden: false,
|
||||
}),
|
||||
|
||||
@@ -1,42 +1,13 @@
|
||||
import { ENVIRONMENT } from 'constants/env';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { server } from 'mocks-server/server';
|
||||
import { rest } from 'msw';
|
||||
import { VirtuosoMockContext } from 'react-virtuoso';
|
||||
import { render, screen, waitFor } from 'tests/test-utils';
|
||||
import { screen, waitFor } from 'tests/test-utils';
|
||||
|
||||
import TracesView from './index';
|
||||
|
||||
const BASE_URL = ENVIRONMENT.baseURL;
|
||||
const QUERY_RANGE_URL = `${BASE_URL}/api/v5/query_range`;
|
||||
|
||||
const groupedRows = [
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:58.735245Z',
|
||||
data: {
|
||||
'service.name': 'frontend',
|
||||
name: 'HTTP GET',
|
||||
duration_nano: 55306000,
|
||||
span_count: 8,
|
||||
trace_id: '0000000000000000344ded1387b08a7e',
|
||||
},
|
||||
},
|
||||
{
|
||||
timestamp: '2024-07-19T08:39:59.949129915Z',
|
||||
data: {
|
||||
'service.name': 'demo-app',
|
||||
// intentionally empty to assert the "-" cell
|
||||
name: '',
|
||||
duration_nano: 790949390,
|
||||
span_count: 3,
|
||||
trace_id: 'a364a8e15af3e9a8c866e0528db8b637',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const groupedResponse = (rows: unknown[]): Record<string, unknown> => ({
|
||||
data: { type: 'trace', data: { results: [{ queryName: 'A', rows }] } },
|
||||
});
|
||||
import {
|
||||
groupedResponse,
|
||||
groupedRows,
|
||||
QUERY_RANGE_URL,
|
||||
renderTracesView,
|
||||
} from './__tests__/testUtils';
|
||||
|
||||
const mockSuccess = (rows: unknown[] = groupedRows): void => {
|
||||
server.use(
|
||||
@@ -54,29 +25,6 @@ const mockError = (): void => {
|
||||
);
|
||||
};
|
||||
|
||||
const renderTracesView = (
|
||||
props: Record<string, unknown> = {},
|
||||
): ReturnType<typeof render> =>
|
||||
render(
|
||||
<VirtuosoMockContext.Provider value={{ viewportHeight: 500, itemHeight: 54 }}>
|
||||
<TracesView
|
||||
isFilterApplied={false}
|
||||
setWarning={jest.fn()}
|
||||
setIsLoadingQueries={jest.fn()}
|
||||
{...props}
|
||||
/>
|
||||
</VirtuosoMockContext.Provider>,
|
||||
{},
|
||||
{
|
||||
initialRoute: '/traces-explorer',
|
||||
queryBuilderOverrides: {
|
||||
panelType: PANEL_TYPES.TRACE,
|
||||
stagedQuery: initialQueriesMap.traces,
|
||||
currentQuery: initialQueriesMap.traces,
|
||||
} as any,
|
||||
},
|
||||
);
|
||||
|
||||
describe('TracesView (grouped root-span table)', () => {
|
||||
afterEach(() => {
|
||||
server.resetHandlers();
|
||||
@@ -96,8 +44,8 @@ describe('TracesView (grouped root-span table)', () => {
|
||||
// span_count renders as text
|
||||
expect(screen.getByText('8')).toBeInTheDocument();
|
||||
|
||||
// empty field renders "-"
|
||||
expect(screen.getAllByText('-').length).toBeGreaterThanOrEqual(1);
|
||||
// empty field renders the dash icon
|
||||
expect(screen.getAllByTestId('empty-value').length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// trace_id renders as a link to the trace detail
|
||||
const traceLinks = screen.getAllByTestId('trace-id');
|
||||
@@ -115,8 +63,6 @@ describe('TracesView (grouped root-span table)', () => {
|
||||
expect(
|
||||
screen.getByText(/This tab only shows Root Spans/i),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /previous/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /next/i })).toBeInTheDocument();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/No traces yet/i)).toBeInTheDocument();
|
||||
@@ -130,7 +76,5 @@ describe('TracesView (grouped root-span table)', () => {
|
||||
expect(
|
||||
screen.getByText(/This tab only shows Root Spans/i),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /previous/i })).toBeInTheDocument();
|
||||
expect(screen.getByRole('button', { name: /next/i })).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,25 +14,23 @@ import logEvent from 'api/common/logEvent';
|
||||
import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
|
||||
import { ENTITY_VERSION_V5 } from 'constants/app';
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import { initialQueriesMap, PANEL_TYPES } from 'constants/queryBuilder';
|
||||
import { REACT_QUERY_KEY } from 'constants/reactQueryKeys';
|
||||
import { getListViewQuery } from 'container/TracesExplorer/explorerUtils';
|
||||
import { getTraceLink } from 'container/TracesExplorer/ListView/utils';
|
||||
import TracesTable from 'container/TracesExplorer/TracesTable/TracesTable';
|
||||
import { TracesTableRow } from 'container/TracesExplorer/TracesTable/getFieldColumn';
|
||||
import { useKeepRowsForSameQuery } from 'container/TracesExplorer/TracesTable/useKeepRowsForSameQuery';
|
||||
import { useTracesTablePagination } from 'container/TracesExplorer/TracesTable/useTracesTablePagination';
|
||||
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
|
||||
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
|
||||
import { Pagination } from 'hooks/queryPagination';
|
||||
import useUrlQueryData from 'hooks/useUrlQueryData';
|
||||
import { AppState } from 'store/reducers';
|
||||
import { Warning } from 'types/api';
|
||||
import { DataSource } from 'types/common/queryBuilder';
|
||||
import { GlobalReducer } from 'types/reducer/globalTime';
|
||||
import DOCLINKS from 'utils/docLinks';
|
||||
|
||||
import TraceExplorerControls from '../Controls';
|
||||
import { columns, PER_PAGE_OPTIONS } from './configs';
|
||||
import { columns } from './configs';
|
||||
|
||||
import styles from './TracesView.module.scss';
|
||||
|
||||
@@ -59,9 +57,7 @@ function TracesView({
|
||||
minTime,
|
||||
} = useSelector<AppState, GlobalReducer>((state) => state.globalTime);
|
||||
|
||||
const { queryData: paginationQueryData } = useUrlQueryData<Pagination>(
|
||||
QueryParams.pagination,
|
||||
);
|
||||
const pagination = useTracesTablePagination();
|
||||
|
||||
const transformedQuery = useMemo(
|
||||
() => getListViewQuery(stagedQuery || initialQueriesMap.traces),
|
||||
@@ -76,7 +72,7 @@ function TracesView({
|
||||
minTime,
|
||||
stagedQuery,
|
||||
panelType,
|
||||
paginationQueryData,
|
||||
pagination.request,
|
||||
],
|
||||
[
|
||||
globalSelectedTime,
|
||||
@@ -84,7 +80,7 @@ function TracesView({
|
||||
minTime,
|
||||
stagedQuery,
|
||||
panelType,
|
||||
paginationQueryData,
|
||||
pagination.request,
|
||||
],
|
||||
);
|
||||
|
||||
@@ -92,25 +88,27 @@ function TracesView({
|
||||
queryKeyRef.current = queryKey;
|
||||
}
|
||||
|
||||
const { data, isLoading, isFetching, isError, error } = useGetQueryRange(
|
||||
{
|
||||
query: transformedQuery,
|
||||
graphType: panelType || PANEL_TYPES.TRACE,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
globalSelectedInterval: globalSelectedTime,
|
||||
params: {
|
||||
dataSource: 'traces',
|
||||
const { data, isLoading, isFetching, isError, error, isPreviousData } =
|
||||
useGetQueryRange(
|
||||
{
|
||||
query: transformedQuery,
|
||||
graphType: panelType || PANEL_TYPES.TRACE,
|
||||
selectedTime: 'GLOBAL_TIME',
|
||||
globalSelectedInterval: globalSelectedTime,
|
||||
params: {
|
||||
dataSource: 'traces',
|
||||
},
|
||||
tableParams: {
|
||||
pagination: pagination.request,
|
||||
},
|
||||
},
|
||||
tableParams: {
|
||||
pagination: paginationQueryData,
|
||||
ENTITY_VERSION_V5,
|
||||
{
|
||||
queryKey,
|
||||
keepPreviousData: true,
|
||||
enabled: !!stagedQuery && panelType === PANEL_TYPES.TRACE,
|
||||
},
|
||||
},
|
||||
ENTITY_VERSION_V5,
|
||||
{
|
||||
queryKey,
|
||||
enabled: !!stagedQuery && panelType === PANEL_TYPES.TRACE,
|
||||
},
|
||||
);
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (data?.payload) {
|
||||
@@ -119,7 +117,10 @@ function TracesView({
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [data?.payload, data?.warning]);
|
||||
|
||||
const responseData = data?.payload?.data?.newResult?.data?.result[0]?.list;
|
||||
const keepRows = useKeepRowsForSameQuery(isPreviousData);
|
||||
const responseData = keepRows
|
||||
? data?.payload?.data?.newResult?.data?.result[0]?.list
|
||||
: undefined;
|
||||
|
||||
const rows = useMemo<TracesTableRow[]>(
|
||||
() =>
|
||||
@@ -157,18 +158,12 @@ function TracesView({
|
||||
</Typography.Link>
|
||||
</Typography>
|
||||
|
||||
<div className="trace-explorer-controls">
|
||||
<div className={styles.controls}>
|
||||
{headerActions}
|
||||
<DownloadOptionsMenu
|
||||
dataSource={DataSource.TRACES}
|
||||
panelType={PANEL_TYPES.TRACE}
|
||||
/>
|
||||
|
||||
<TraceExplorerControls
|
||||
isLoading={isLoading}
|
||||
totalCount={rows.length}
|
||||
perPageOptions={PER_PAGE_OPTIONS}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -184,6 +179,7 @@ function TracesView({
|
||||
isError={isError}
|
||||
error={error}
|
||||
isFilterApplied={isFilterApplied}
|
||||
pagination={pagination}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
20
frontend/src/container/TracesExplorer/events.ts
Normal file
20
frontend/src/container/TracesExplorer/events.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import logEvent from 'api/common/logEvent';
|
||||
import { PANEL_TYPES } from 'constants/queryBuilder';
|
||||
|
||||
export enum TracesExplorerEvents {
|
||||
OpenTraceClicked = 'Traces Explorer: Open trace clicked',
|
||||
}
|
||||
|
||||
export enum OpenTraceSource {
|
||||
Row = 'row',
|
||||
RowIcon = 'row_icon',
|
||||
TraceId = 'trace_id',
|
||||
SpanDrawer = 'span_drawer',
|
||||
}
|
||||
|
||||
export function logOpenTraceClicked(
|
||||
panelType: PANEL_TYPES,
|
||||
source: OpenTraceSource,
|
||||
): void {
|
||||
void logEvent(TracesExplorerEvents.OpenTraceClicked, { panelType, source });
|
||||
}
|
||||
107
frontend/src/hooks/__tests__/useCloseOnOutsidePress.test.tsx
Normal file
107
frontend/src/hooks/__tests__/useCloseOnOutsidePress.test.tsx
Normal file
@@ -0,0 +1,107 @@
|
||||
import { createPortal } from 'react-dom';
|
||||
import { render, screen, userEvent } from 'tests/test-utils';
|
||||
|
||||
import { useCloseOnOutsidePress } from '../useCloseOnOutsidePress';
|
||||
|
||||
function Harness({
|
||||
enabled = true,
|
||||
onClose,
|
||||
}: {
|
||||
enabled?: boolean;
|
||||
onClose: () => void;
|
||||
}): JSX.Element {
|
||||
const onPressInside = useCloseOnOutsidePress(enabled, onClose);
|
||||
return (
|
||||
<>
|
||||
<div onPointerDownCapture={onPressInside}>
|
||||
<button type="button" data-testid="inside">
|
||||
inside
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="inside-stops"
|
||||
onPointerDown={(e): void => e.stopPropagation()}
|
||||
>
|
||||
inside, stops propagation
|
||||
</button>
|
||||
{createPortal(
|
||||
<button type="button" data-testid="inside-portal">
|
||||
portal
|
||||
</button>,
|
||||
document.body,
|
||||
)}
|
||||
</div>
|
||||
<button type="button" data-testid="outside">
|
||||
outside
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
data-testid="outside-stops"
|
||||
onPointerDown={(e): void => e.stopPropagation()}
|
||||
>
|
||||
outside, stops propagation
|
||||
</button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const flush = (): Promise<void> =>
|
||||
new Promise((resolve) => {
|
||||
setTimeout(resolve);
|
||||
});
|
||||
|
||||
describe('useCloseOnOutsidePress', () => {
|
||||
it('closes on a press outside', async () => {
|
||||
const onClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
render(<Harness onClose={onClose} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId('outside'));
|
||||
await flush();
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('stays open on a press inside, portals included', async () => {
|
||||
const onClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
render(<Harness onClose={onClose} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId('inside'));
|
||||
await userEvent.click(screen.getByTestId('inside-portal'));
|
||||
await flush();
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('closes when the outside element stops propagation', async () => {
|
||||
const onClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
render(<Harness onClose={onClose} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId('outside-stops'));
|
||||
await flush();
|
||||
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('closes on the first outside press after an inside press stops propagation', async () => {
|
||||
const onClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
render(<Harness onClose={onClose} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId('inside-stops'));
|
||||
await flush();
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
|
||||
await userEvent.click(screen.getByTestId('outside'));
|
||||
await flush();
|
||||
expect(onClose).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does nothing while disabled', async () => {
|
||||
const onClose = jest.fn() as jest.MockedFunction<() => void>;
|
||||
render(<Harness enabled={false} onClose={onClose} />);
|
||||
|
||||
await userEvent.click(screen.getByTestId('outside'));
|
||||
await flush();
|
||||
|
||||
expect(onClose).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
51
frontend/src/hooks/useCloseOnOutsidePress.ts
Normal file
51
frontend/src/hooks/useCloseOnOutsidePress.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import {
|
||||
PointerEvent as ReactPointerEvent,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useRef,
|
||||
} from 'react';
|
||||
|
||||
/**
|
||||
* Calls `onClose` on any press outside the elements given the returned handler as
|
||||
* `onPointerDownCapture`. Menus and dialogs rendered in portals still count as
|
||||
* inside: React events follow the component tree.
|
||||
*
|
||||
* The document listener runs in the capture phase, so an outside element that
|
||||
* stops propagation still closes. It runs before React marks the press, so the
|
||||
* check waits for the dispatch to finish.
|
||||
*/
|
||||
export function useCloseOnOutsidePress(
|
||||
enabled: boolean,
|
||||
onClose: () => void,
|
||||
): (event: ReactPointerEvent) => void {
|
||||
const insidePress = useRef<Event | null>(null);
|
||||
const onCloseRef = useRef(onClose);
|
||||
onCloseRef.current = onClose;
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) {
|
||||
return undefined;
|
||||
}
|
||||
const timeouts = new Set<ReturnType<typeof setTimeout>>();
|
||||
|
||||
const handlePointerDown = (event: PointerEvent): void => {
|
||||
const timeout = setTimeout(() => {
|
||||
timeouts.delete(timeout);
|
||||
if (insidePress.current !== event) {
|
||||
onCloseRef.current();
|
||||
}
|
||||
});
|
||||
timeouts.add(timeout);
|
||||
};
|
||||
|
||||
document.addEventListener('pointerdown', handlePointerDown, true);
|
||||
return (): void => {
|
||||
document.removeEventListener('pointerdown', handlePointerDown, true);
|
||||
timeouts.forEach(clearTimeout);
|
||||
};
|
||||
}, [enabled]);
|
||||
|
||||
return useCallback((event: ReactPointerEvent): void => {
|
||||
insidePress.current = event.nativeEvent;
|
||||
}, []);
|
||||
}
|
||||
@@ -13,7 +13,8 @@ import styles from './Events.module.scss';
|
||||
|
||||
interface IEventsTableProps {
|
||||
span: SpanV3;
|
||||
startTime: number;
|
||||
/** Trace start; the "since trace start" offset is hidden without it. */
|
||||
startTime?: number;
|
||||
isSearchVisible: boolean;
|
||||
}
|
||||
|
||||
@@ -80,17 +81,19 @@ function EventsTable(props: IEventsTableProps): JSX.Element {
|
||||
<Typography.Text className={styles.attributeKey}>
|
||||
Start Time
|
||||
</Typography.Text>
|
||||
<div className={styles.timestampContainer}>
|
||||
<Typography.Text className={styles.attributeValue}>
|
||||
{getYAxisFormattedValue(
|
||||
`${(timeUnixNano || 0) / 1e6 - startTime}`,
|
||||
'ms',
|
||||
)}
|
||||
</Typography.Text>
|
||||
<Typography.Text className={styles.timestampText}>
|
||||
since trace start
|
||||
</Typography.Text>
|
||||
</div>
|
||||
{startTime !== undefined && (
|
||||
<div className={styles.timestampContainer}>
|
||||
<Typography.Text className={styles.attributeValue}>
|
||||
{getYAxisFormattedValue(
|
||||
`${(timeUnixNano || 0) / 1e6 - startTime}`,
|
||||
'ms',
|
||||
)}
|
||||
</Typography.Text>
|
||||
<Typography.Text className={styles.timestampText}>
|
||||
since trace start
|
||||
</Typography.Text>
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.timestampContainer}>
|
||||
<Typography.Text className={styles.attributeValue}>
|
||||
{getYAxisFormattedValue(
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { render, screen } from 'tests/test-utils';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import Events from '../Events';
|
||||
|
||||
const SPAN_START_MS = 1_700_000_000_000;
|
||||
|
||||
const span = {
|
||||
span_id: 'span-1',
|
||||
trace_id: 'trace-1',
|
||||
name: 'checkout',
|
||||
timestamp: SPAN_START_MS,
|
||||
duration_nano: 50_000_000,
|
||||
events: [
|
||||
{
|
||||
name: 'cache miss',
|
||||
timeUnixNano: (SPAN_START_MS + 3) * 1e6,
|
||||
attributeMap: {},
|
||||
isError: false,
|
||||
},
|
||||
],
|
||||
} as unknown as SpanV3;
|
||||
|
||||
describe('Events', () => {
|
||||
it('shows the offset from the trace start when it is known', () => {
|
||||
render(<Events span={span} startTime={SPAN_START_MS - 10} isSearchVisible />);
|
||||
|
||||
expect(screen.getByText('since trace start')).toBeInTheDocument();
|
||||
expect(screen.getByText('since span start')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows only the offset from the span start without a trace start', () => {
|
||||
render(<Events span={span} isSearchVisible />);
|
||||
|
||||
expect(screen.queryByText('since trace start')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('since span start')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -110,3 +110,15 @@
|
||||
scrollbar-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
.drawerPanel {
|
||||
.panelBody,
|
||||
.logsFooter,
|
||||
:global(.pretty-view__search-wrapper) {
|
||||
background: var(--l2-background);
|
||||
}
|
||||
|
||||
:global(.pretty-view__search-input) {
|
||||
background: var(--l2-background) !important;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ 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';
|
||||
import { DetailsPanelState } from 'components/DetailsPanel/types';
|
||||
@@ -49,6 +50,7 @@ import OpenInLogsExplorer from './SpanLogs/OpenInLogsExplorer';
|
||||
import SpanLogs from './SpanLogs/SpanLogs';
|
||||
import { useSpanContextLogs } from './SpanLogs/useSpanContextLogs';
|
||||
import SpanAIMessages from './SpanAIMessages/SpanAIMessages';
|
||||
import SpanDrawerHeader from './SpanDrawerHeader';
|
||||
import SpanSummary from './SpanSummary';
|
||||
|
||||
import styles from './SpanDetailsPanel.module.scss';
|
||||
@@ -58,8 +60,12 @@ interface SpanDetailsPanelProps {
|
||||
selectedSpan: SpanV3 | undefined;
|
||||
variant?: SpanDetailVariant;
|
||||
onVariantChange?: (variant: SpanDetailVariant) => void;
|
||||
/** Page-specific actions, shown before the dock mode switcher. */
|
||||
headerActions?: HeaderAction[];
|
||||
traceStartTime?: number;
|
||||
traceEndTime?: number;
|
||||
/** The trace bounds are still being fetched; logs wait for them. */
|
||||
isTraceBoundsLoading?: boolean;
|
||||
}
|
||||
|
||||
// At/above this panel width the summary moves inside the Overview tab (bottom
|
||||
@@ -73,10 +79,12 @@ function SpanDetailsContent({
|
||||
selectedSpan,
|
||||
traceStartTime,
|
||||
traceEndTime,
|
||||
isTraceBoundsLoading = false,
|
||||
}: {
|
||||
selectedSpan: SpanV3;
|
||||
traceStartTime?: number;
|
||||
traceEndTime?: number;
|
||||
isTraceBoundsLoading?: boolean;
|
||||
}): JSX.Element {
|
||||
const [bodyRef, { width: bodyWidth }] = useMeasure<HTMLDivElement>();
|
||||
const spanAttributeActions = useSpanAttributeActions();
|
||||
@@ -168,6 +176,31 @@ function SpanDetailsContent({
|
||||
// [spanAttributeActions, setCopy],
|
||||
// );
|
||||
|
||||
// Without trace bounds the panel speaks only for the span: its own logs
|
||||
// window, and no trace-wide logs check.
|
||||
const hasTraceBounds = !!traceStartTime && !!traceEndTime;
|
||||
const logsTimeRange = useMemo(
|
||||
() =>
|
||||
traceStartTime && traceEndTime
|
||||
? {
|
||||
startTime: traceStartTime - FIVE_MINUTES_IN_MS,
|
||||
endTime: traceEndTime + FIVE_MINUTES_IN_MS,
|
||||
}
|
||||
: {
|
||||
startTime: selectedSpan.timestamp - FIVE_MINUTES_IN_MS,
|
||||
// query_range rejects a fractional end.
|
||||
endTime:
|
||||
Math.ceil(selectedSpan.timestamp + selectedSpan.duration_nano / 1e6) +
|
||||
FIVE_MINUTES_IN_MS,
|
||||
},
|
||||
[
|
||||
traceStartTime,
|
||||
traceEndTime,
|
||||
selectedSpan.timestamp,
|
||||
selectedSpan.duration_nano,
|
||||
],
|
||||
);
|
||||
|
||||
const {
|
||||
logs,
|
||||
isLoading: isLogsLoading,
|
||||
@@ -178,11 +211,9 @@ function SpanDetailsContent({
|
||||
} = useSpanContextLogs({
|
||||
traceId: selectedSpan.trace_id,
|
||||
spanId: selectedSpan.span_id,
|
||||
timeRange: {
|
||||
startTime: (traceStartTime || 0) - FIVE_MINUTES_IN_MS,
|
||||
endTime: (traceEndTime || 0) + FIVE_MINUTES_IN_MS,
|
||||
},
|
||||
isDrawerOpen: true,
|
||||
timeRange: logsTimeRange,
|
||||
checkTraceLogs: hasTraceBounds,
|
||||
enabled: !isTraceBoundsLoading,
|
||||
});
|
||||
|
||||
const infraMetadata = useMemo(() => {
|
||||
@@ -201,8 +232,7 @@ function SpanDetailsContent({
|
||||
}, [selectedSpan]);
|
||||
|
||||
const handleExplorerPageRedirect = useCallback((): void => {
|
||||
const startTimeMs = (traceStartTime || 0) - FIVE_MINUTES_IN_MS;
|
||||
const endTimeMs = (traceEndTime || 0) + FIVE_MINUTES_IN_MS;
|
||||
const { startTime: startTimeMs, endTime: endTimeMs } = logsTimeRange;
|
||||
|
||||
const traceIdFilter = {
|
||||
op: 'AND',
|
||||
@@ -244,14 +274,15 @@ function SpanDetailsContent({
|
||||
searchParams.set(QueryParams.endTime, endTimeMs.toString());
|
||||
|
||||
openInNewTab(`${ROUTES.LOGS_EXPLORER}?${searchParams.toString()}`);
|
||||
}, [selectedSpan.trace_id, traceStartTime, traceEndTime]);
|
||||
}, [selectedSpan.trace_id, logsTimeRange]);
|
||||
|
||||
const emptyLogsStateConfig = useMemo(
|
||||
() => ({
|
||||
...getEmptyLogsListConfig(() => {}),
|
||||
...(!hasTraceBounds && { title: 'No logs found for this span.' }),
|
||||
showClearFiltersButton: false,
|
||||
}),
|
||||
[],
|
||||
[hasTraceBounds],
|
||||
);
|
||||
|
||||
// const keyAttributes = useMemo(() => {
|
||||
@@ -321,11 +352,7 @@ function SpanDetailsContent({
|
||||
</Badge>
|
||||
) : undefined,
|
||||
children: (
|
||||
<Events
|
||||
span={selectedSpan}
|
||||
startTime={traceStartTime || 0}
|
||||
isSearchVisible
|
||||
/>
|
||||
<Events span={selectedSpan} startTime={traceStartTime} isSearchVisible />
|
||||
),
|
||||
},
|
||||
{
|
||||
@@ -336,10 +363,7 @@ function SpanDetailsContent({
|
||||
<SpanLogs
|
||||
traceId={selectedSpan.trace_id}
|
||||
spanId={selectedSpan.span_id}
|
||||
timeRange={{
|
||||
startTime: (traceStartTime || 0) - FIVE_MINUTES_IN_MS,
|
||||
endTime: (traceEndTime || 0) + FIVE_MINUTES_IN_MS,
|
||||
}}
|
||||
timeRange={logsTimeRange}
|
||||
logs={logs}
|
||||
isLoading={isLogsLoading}
|
||||
isError={isLogsError}
|
||||
@@ -394,7 +418,10 @@ function SpanDetailsContent({
|
||||
with the panel's bottom edge — always visible, never scrolls. */}
|
||||
{activeTab === 'logs' && (
|
||||
<div className={styles.logsFooter}>
|
||||
<OpenInLogsExplorer onClick={handleExplorerPageRedirect} />
|
||||
<OpenInLogsExplorer
|
||||
onClick={handleExplorerPageRedirect}
|
||||
disabled={isTraceBoundsLoading}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
@@ -406,11 +433,14 @@ function SpanDetailsPanel({
|
||||
selectedSpan,
|
||||
variant = SpanDetailVariant.DIALOG,
|
||||
onVariantChange,
|
||||
headerActions: pageHeaderActions,
|
||||
traceStartTime,
|
||||
traceEndTime,
|
||||
isTraceBoundsLoading,
|
||||
}: SpanDetailsPanelProps): JSX.Element {
|
||||
const headerActions = useMemo((): HeaderAction[] => {
|
||||
const actions: HeaderAction[] = [
|
||||
...(pageHeaderActions ?? []),
|
||||
// TODO: Add back when driven through separate config for different pages
|
||||
// {
|
||||
// key: 'view-full-trace',
|
||||
@@ -440,7 +470,7 @@ function SpanDetailsPanel({
|
||||
}
|
||||
|
||||
return actions;
|
||||
}, [variant, onVariantChange]);
|
||||
}, [pageHeaderActions, variant, onVariantChange]);
|
||||
|
||||
const PANEL_WIDTH = SPAN_DETAILS_PANEL_MIN_WIDTH;
|
||||
const PANEL_MARGIN_RIGHT = 20;
|
||||
@@ -449,19 +479,28 @@ function SpanDetailsPanel({
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<DetailsHeader
|
||||
title="Span details"
|
||||
onClose={panelState.close}
|
||||
actions={headerActions}
|
||||
className={
|
||||
variant === SpanDetailVariant.DIALOG ? 'floating-panel__drag-handle' : ''
|
||||
}
|
||||
/>
|
||||
{variant === SpanDetailVariant.DRAWER ? (
|
||||
<SpanDrawerHeader
|
||||
title="Span details"
|
||||
onClose={panelState.close}
|
||||
actions={headerActions}
|
||||
/>
|
||||
) : (
|
||||
<DetailsHeader
|
||||
title="Span details"
|
||||
onClose={panelState.close}
|
||||
actions={headerActions}
|
||||
className={
|
||||
variant === SpanDetailVariant.DIALOG ? 'floating-panel__drag-handle' : ''
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{selectedSpan ? (
|
||||
<SpanDetailsContent
|
||||
selectedSpan={selectedSpan}
|
||||
traceStartTime={traceStartTime}
|
||||
traceEndTime={traceEndTime}
|
||||
isTraceBoundsLoading={isTraceBoundsLoading}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.panelBody}>
|
||||
@@ -483,7 +522,8 @@ function SpanDetailsPanel({
|
||||
<DetailsPanelDrawer
|
||||
isOpen={panelState.isOpen}
|
||||
onClose={panelState.close}
|
||||
className={styles.panel}
|
||||
className={cx(styles.panel, styles.drawerPanel)}
|
||||
testId="span-details-drawer"
|
||||
>
|
||||
{content}
|
||||
</DetailsPanelDrawer>
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
.header {
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
height: 48px;
|
||||
padding: 0 var(--spacing-8) 0 var(--spacing-4);
|
||||
border-bottom: 1px solid var(--l1-border);
|
||||
background: var(--l2-background);
|
||||
}
|
||||
|
||||
.divider {
|
||||
height: 16px;
|
||||
margin-inline: 0 var(--spacing-4);
|
||||
}
|
||||
|
||||
.title {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 14px;
|
||||
color: var(--l1-foreground);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
flex-shrink: 0;
|
||||
align-items: center;
|
||||
gap: var(--spacing-4);
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Divider } from '@signozhq/ui/divider';
|
||||
import { X } from '@signozhq/icons';
|
||||
import type { HeaderAction } from 'components/DetailsPanel';
|
||||
|
||||
import styles from './SpanDrawerHeader.module.scss';
|
||||
|
||||
interface SpanDrawerHeaderProps {
|
||||
title: string;
|
||||
onClose: () => void;
|
||||
actions: HeaderAction[];
|
||||
}
|
||||
|
||||
function SpanDrawerHeader({
|
||||
title,
|
||||
onClose,
|
||||
actions,
|
||||
}: SpanDrawerHeaderProps): JSX.Element {
|
||||
return (
|
||||
<div className={styles.header}>
|
||||
<Button
|
||||
variant="ghost"
|
||||
color="secondary"
|
||||
size="md"
|
||||
icon
|
||||
aria-label="Close"
|
||||
onClick={onClose}
|
||||
testId="span-drawer-close"
|
||||
>
|
||||
<X />
|
||||
</Button>
|
||||
<Divider type="vertical" className={styles.divider} />
|
||||
<span className={styles.title}>{title}</span>
|
||||
<div className={styles.actions}>
|
||||
{actions.map((action) => (
|
||||
<div key={action.key}>{action.component}</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default SpanDrawerHeader;
|
||||
@@ -3,17 +3,23 @@ import { Compass } from '@signozhq/icons';
|
||||
|
||||
interface OpenInLogsExplorerProps {
|
||||
onClick: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
// Opens the full Logs Explorer (new tab) filtered to this span's trace.
|
||||
// Placement/alignment is the caller's responsibility.
|
||||
function OpenInLogsExplorer({ onClick }: OpenInLogsExplorerProps): JSX.Element {
|
||||
function OpenInLogsExplorer({
|
||||
onClick,
|
||||
disabled,
|
||||
}: OpenInLogsExplorerProps): JSX.Element {
|
||||
return (
|
||||
<Button
|
||||
variant="solid"
|
||||
color="secondary"
|
||||
size="md"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
disabledTooltip="Loading the trace's time range"
|
||||
prefix={<Compass size={16} />}
|
||||
testId="open-in-explorer-button"
|
||||
>
|
||||
|
||||
@@ -20,7 +20,8 @@ interface UseSpanContextLogsProps {
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
};
|
||||
isDrawerOpen?: boolean;
|
||||
checkTraceLogs?: boolean;
|
||||
enabled?: boolean;
|
||||
}
|
||||
|
||||
interface UseSpanContextLogsReturn {
|
||||
@@ -112,7 +113,8 @@ export const useSpanContextLogs = ({
|
||||
traceId,
|
||||
spanId,
|
||||
timeRange,
|
||||
isDrawerOpen = true,
|
||||
checkTraceLogs = true,
|
||||
enabled = true,
|
||||
}: UseSpanContextLogsProps): UseSpanContextLogsReturn => {
|
||||
const [allLogs, setAllLogs] = useState<ILog[]>([]);
|
||||
const [spanLogIds, setSpanLogIds] = useState<Set<string>>(new Set());
|
||||
@@ -142,7 +144,7 @@ export const useSpanContextLogs = ({
|
||||
timeRange.endTime,
|
||||
],
|
||||
queryFn: () => GetMetricQueryRange(spanQueryPayload, ENTITY_VERSION_V5),
|
||||
enabled: !!traceId && !!spanId,
|
||||
enabled: enabled && !!traceId && !!spanId,
|
||||
staleTime: FIVE_MINUTES_IN_MS,
|
||||
});
|
||||
|
||||
@@ -311,7 +313,11 @@ export const useSpanContextLogs = ({
|
||||
],
|
||||
queryFn: () =>
|
||||
GetMetricQueryRange(traceOnlyQueryPayload as any, ENTITY_VERSION_V5),
|
||||
enabled: isDrawerOpen && !!traceOnlyQueryPayload && spanLogs.length === 0,
|
||||
enabled:
|
||||
enabled &&
|
||||
checkTraceLogs &&
|
||||
!!traceOnlyQueryPayload &&
|
||||
spanLogs.length === 0,
|
||||
staleTime: FIVE_MINUTES_IN_MS,
|
||||
});
|
||||
|
||||
@@ -332,7 +338,7 @@ export const useSpanContextLogs = ({
|
||||
|
||||
return {
|
||||
logs: allLogs,
|
||||
isLoading: isSpanLoading && spanLogs.length === 0,
|
||||
isLoading: (!enabled || isSpanLoading) && spanLogs.length === 0,
|
||||
isError: isSpanError,
|
||||
isFetching: isSpanFetching || isBeforeFetching || isAfterFetching,
|
||||
spanLogIds,
|
||||
|
||||
@@ -1,7 +1,21 @@
|
||||
.traceId {
|
||||
color: var(--accent-primary);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--spacing-1);
|
||||
min-width: 0;
|
||||
|
||||
// Sized to the icon, so the copy button sits flush against the id.
|
||||
--button-padding: 2px;
|
||||
--button-height: auto;
|
||||
--button-width: auto;
|
||||
}
|
||||
|
||||
// A block, since overflow and text-overflow do not apply to the inline span
|
||||
// Typography.Text renders.
|
||||
.value {
|
||||
display: block;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
display: block;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,5 @@
|
||||
import { useCopyToClipboard } from 'react-use';
|
||||
import { Button } from '@signozhq/ui/button';
|
||||
import { Tooltip } from '@signozhq/ui/tooltip';
|
||||
import { toast } from '@signozhq/ui/sonner';
|
||||
import { AppLink } from 'lib/router/AppLink';
|
||||
import { matchRoute } from 'lib/router/matchRoute';
|
||||
import { useAppLocation } from 'lib/router/useAppLocation';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { Typography } from '@signozhq/ui/typography';
|
||||
import CopyButton from 'periscope/components/CopyButton/CopyButton';
|
||||
import { SpanV3 } from 'types/api/trace/getTraceV3';
|
||||
|
||||
import styles from './TraceIdField.module.scss';
|
||||
@@ -14,51 +8,20 @@ interface TraceIdFieldProps {
|
||||
span: SpanV3;
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a span's trace id. When the user is already on the trace detail
|
||||
* page for this trace, clicking the id copies it to the clipboard (the
|
||||
* "navigate" affordance would be a no-op). Otherwise, falls back to the
|
||||
* existing link to the trace detail page.
|
||||
*/
|
||||
export function TraceIdField({ span }: TraceIdFieldProps): JSX.Element {
|
||||
const { pathname } = useAppLocation();
|
||||
const match = matchRoute<'id'>(pathname, ROUTES.TRACE_DETAIL, { exact: true });
|
||||
const [, setCopy] = useCopyToClipboard();
|
||||
|
||||
const isCurrentTrace = match?.params.id === span.trace_id;
|
||||
|
||||
if (isCurrentTrace) {
|
||||
const handleCopy = (): void => {
|
||||
setCopy(span.trace_id);
|
||||
toast.success('Trace ID copied to clipboard', {
|
||||
position: 'top-right',
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Tooltip title="Click to copy trace ID">
|
||||
<Button
|
||||
size="md"
|
||||
variant="link"
|
||||
color="secondary"
|
||||
maxWidth="100%"
|
||||
onClick={handleCopy}
|
||||
>
|
||||
{span.trace_id}
|
||||
</Button>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<AppLink
|
||||
to={{
|
||||
pathname: `/trace/${span.trace_id}`,
|
||||
search: window.location.search,
|
||||
}}
|
||||
className={styles.traceId}
|
||||
>
|
||||
{span.trace_id}
|
||||
</AppLink>
|
||||
<div className={styles.traceId}>
|
||||
<span className={styles.value} title={span.trace_id}>
|
||||
<Typography.Text testId="span-details-trace-id">
|
||||
{span.trace_id}
|
||||
</Typography.Text>
|
||||
</span>
|
||||
<CopyButton
|
||||
value={span.trace_id}
|
||||
size={12}
|
||||
ariaLabel="Copy trace ID"
|
||||
testId="span-details-copy-trace-id"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,6 +33,13 @@
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.aiDot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent-primary);
|
||||
}
|
||||
|
||||
.filterSection {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -137,7 +137,7 @@ function TraceDetailsHeader({
|
||||
badgeValue={traceID}
|
||||
maxCharacters={100}
|
||||
/>
|
||||
<TraceDetailsTabs />
|
||||
<TraceDetailsTabs hasAiSummary={!!traceSummary?.ai} />
|
||||
</div>
|
||||
)}
|
||||
{isOverview && showTraceDetailsHeaderOptions && traceSummary && (
|
||||
|
||||
@@ -8,20 +8,13 @@ import { useTraceDetailsTab } from '../hooks/useTraceDetailsTab';
|
||||
|
||||
import styles from './TraceDetailsHeader.module.scss';
|
||||
|
||||
const TAB_ITEMS = [
|
||||
{
|
||||
value: TraceDetailsTab.Overview,
|
||||
label: 'Overview',
|
||||
testId: 'trace-details-tab-overview',
|
||||
},
|
||||
{
|
||||
value: TraceDetailsTab.Thread,
|
||||
label: 'Thread',
|
||||
testId: 'trace-details-tab-thread',
|
||||
},
|
||||
];
|
||||
interface TraceDetailsTabsProps {
|
||||
hasAiSummary: boolean;
|
||||
}
|
||||
|
||||
function TraceDetailsTabs(): JSX.Element {
|
||||
function TraceDetailsTabs({
|
||||
hasAiSummary,
|
||||
}: TraceDetailsTabsProps): JSX.Element {
|
||||
const { id: traceId = '' } = useAppParams<'id'>();
|
||||
const [tab, setTab] = useTraceDetailsTab();
|
||||
const logTraceEvent = useTraceDetailLogEvent('v3', traceId);
|
||||
@@ -35,6 +28,26 @@ function TraceDetailsTabs(): JSX.Element {
|
||||
void setTab(value as TraceDetailsTab, { history: 'push' });
|
||||
};
|
||||
|
||||
const items = [
|
||||
{
|
||||
value: TraceDetailsTab.Overview,
|
||||
label: 'Overview',
|
||||
testId: 'trace-details-tab-overview',
|
||||
},
|
||||
{
|
||||
value: TraceDetailsTab.Thread,
|
||||
label: 'Thread',
|
||||
testId: 'trace-details-tab-thread',
|
||||
suffix: hasAiSummary ? (
|
||||
<span
|
||||
className={styles.aiDot}
|
||||
aria-hidden
|
||||
data-testid="trace-details-tab-thread-ai-dot"
|
||||
/>
|
||||
) : undefined,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
<div className={styles.tabs}>
|
||||
<ToggleGroup
|
||||
@@ -44,7 +57,7 @@ function TraceDetailsTabs(): JSX.Element {
|
||||
value={tab}
|
||||
onChange={handleChange}
|
||||
size="sm"
|
||||
items={TAB_ITEMS}
|
||||
items={items}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -394,6 +394,27 @@ describe('TraceDetailsHeader – tabs', () => {
|
||||
expect(screen.getByText(metadataText)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows the AI dot on the Thread tab only when the summary has an AI block', () => {
|
||||
renderHeader();
|
||||
expect(
|
||||
screen.queryByTestId('trace-details-tab-thread-ai-dot'),
|
||||
).not.toBeInTheDocument();
|
||||
|
||||
jest.mocked(useTraceSummary).mockReturnValue({
|
||||
data: {
|
||||
...SUMMARY,
|
||||
ai: {
|
||||
tokens: { input: 1, output: 1, cacheRead: 0, cacheWrite: 0, reasoning: 0 },
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
});
|
||||
renderHeader();
|
||||
expect(
|
||||
screen.getByTestId('trace-details-tab-thread-ai-dot'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('clears the filter result when switching to the Thread tab', async () => {
|
||||
const user = userEvent.setup({ delay: null });
|
||||
renderHeader();
|
||||
|
||||
@@ -34,7 +34,8 @@ function ThreadSpanDetails({
|
||||
const [width, setWidth] = useState(RIGHT_DOCK_MIN);
|
||||
const [height, setHeight] = useState(BOTTOM_DOCK_DEFAULT);
|
||||
const { id: traceId = '' } = useAppParams<'id'>();
|
||||
const { data: traceSummary } = useTraceSummary(traceId);
|
||||
const { data: traceSummary, isLoading: isTraceSummaryLoading } =
|
||||
useTraceSummary(traceId);
|
||||
|
||||
const panel = (
|
||||
<SpanDetailsPanel
|
||||
@@ -44,6 +45,7 @@ function ThreadSpanDetails({
|
||||
onVariantChange={onVariantChange}
|
||||
traceStartTime={traceSummary?.startTimestampMillis}
|
||||
traceEndTime={traceSummary?.endTimestampMillis}
|
||||
isTraceBoundsLoading={isTraceSummaryLoading}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useSpanDetailVariant } from '../hooks/useSpanDetailVariant';
|
||||
import { useTraceDetailLogEvent } from '../hooks/useTraceDetailLogEvent';
|
||||
import { useTraceDetailsTab } from '../hooks/useTraceDetailsTab';
|
||||
import { SpanDetailVariant } from '../SpanDetailsPanel/constants';
|
||||
import { useThreadDataLoadedEvent } from './hooks/useThreadDataLoadedEvent';
|
||||
import { useThreadLoadedEvents } from './hooks/useThreadLoadedEvents';
|
||||
import { useThreadSpanSelection } from './hooks/useThreadSpanSelection';
|
||||
import { useThreadView } from './hooks/useThreadView';
|
||||
import { useTraceThread } from './hooks/useTraceThread';
|
||||
@@ -30,10 +30,12 @@ const INITIAL_LOADER_COUNT = 4;
|
||||
interface TraceDetailsThreadProps {
|
||||
// Owned by the page so the load event fires once per trace, not per tab visit.
|
||||
dataLoadedFiredForRef: MutableRefObject<string>;
|
||||
threadEmptyFiredForRef: MutableRefObject<string>;
|
||||
}
|
||||
|
||||
function TraceDetailsThread({
|
||||
dataLoadedFiredForRef,
|
||||
threadEmptyFiredForRef,
|
||||
}: TraceDetailsThreadProps): JSX.Element {
|
||||
const { id: traceId } = useAppParams<'id'>();
|
||||
const [, setTab] = useTraceDetailsTab();
|
||||
@@ -68,17 +70,24 @@ function TraceDetailsThread({
|
||||
const interestedSpanIndex = spans.findIndex(
|
||||
(span) => span.span_id === interestedSpanId,
|
||||
);
|
||||
const hasNoThread =
|
||||
!isLoading &&
|
||||
interestedSpanStatus !== InterestedSpanStatus.NotFound &&
|
||||
(isError || spans.length === 0);
|
||||
|
||||
const selectedSpan = spans.find((span) => span.span_id === selectedSpanId);
|
||||
const [spanDetailVariant, setSpanDetailVariant] = useSpanDetailVariant();
|
||||
const isBottomDocked = spanDetailVariant === SpanDetailVariant.DOCKED;
|
||||
|
||||
const logTraceEvent = useTraceDetailLogEvent('v3', traceId || '');
|
||||
useThreadDataLoadedEvent({
|
||||
useThreadLoadedEvents({
|
||||
traceId: traceId || '',
|
||||
interestedSpanId,
|
||||
hasSpans: spans.length > 0,
|
||||
hasNoThread,
|
||||
spanPanelVariant: spanDetailVariant,
|
||||
firedForRef: dataLoadedFiredForRef,
|
||||
dataLoadedFiredForRef,
|
||||
threadEmptyFiredForRef,
|
||||
logTraceEvent,
|
||||
});
|
||||
useSpanDetailsOpenedEvent({
|
||||
@@ -96,10 +105,6 @@ function TraceDetailsThread({
|
||||
onVariantChange={setSpanDetailVariant}
|
||||
/>
|
||||
);
|
||||
const hasNoThread =
|
||||
!isLoading &&
|
||||
interestedSpanStatus !== InterestedSpanStatus.NotFound &&
|
||||
(isError || spans.length === 0);
|
||||
|
||||
const renderBody = (): JSX.Element => {
|
||||
if (isLoading) {
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { MutableRefObject, ReactNode } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import {
|
||||
GetTraceSummary200,
|
||||
SpantypesGettableTraceSummaryDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { getGetTraceSummaryQueryKey } from 'api/generated/services/tracedetail';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { renderHook, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { TraceDetailLogEvent } from '../../../hooks/useTraceDetailLogEvent';
|
||||
import { SpanDetailVariant } from '../../../SpanDetailsPanel/constants';
|
||||
import { useThreadLoadedEvents } from '../useThreadLoadedEvents';
|
||||
|
||||
const BASE_SUMMARY: SpantypesGettableTraceSummaryDTO = {
|
||||
startTimestampMillis: 1_000,
|
||||
endTimestampMillis: 4_000,
|
||||
totalSpansCount: 12,
|
||||
totalErrorSpansCount: 2,
|
||||
hasMissingSpans: true,
|
||||
rootServiceEntryPoint: 'POST /chat',
|
||||
rootServiceName: 'agent',
|
||||
rootSpanStatusCode: 'STATUS_CODE_ERROR',
|
||||
};
|
||||
|
||||
const SUMMARIES: Record<string, SpantypesGettableTraceSummaryDTO> = {
|
||||
'trace-ai': {
|
||||
...BASE_SUMMARY,
|
||||
ai: {
|
||||
tokens: {
|
||||
input: 1_200,
|
||||
output: 300,
|
||||
cacheRead: 50,
|
||||
cacheWrite: 10,
|
||||
reasoning: 40,
|
||||
},
|
||||
totalCost: 0.0123,
|
||||
},
|
||||
},
|
||||
'trace-ai-next': {
|
||||
...BASE_SUMMARY,
|
||||
endTimestampMillis: 1_500,
|
||||
totalSpansCount: 4,
|
||||
ai: {
|
||||
tokens: { input: 80, output: 20, cacheRead: 0, cacheWrite: 0, reasoning: 0 },
|
||||
totalCost: 0.0004,
|
||||
},
|
||||
},
|
||||
'trace-no-ai': BASE_SUMMARY,
|
||||
};
|
||||
|
||||
export interface ThreadLoadedEventsProps {
|
||||
traceId: string;
|
||||
hasSpans?: boolean;
|
||||
hasNoThread?: boolean;
|
||||
interestedSpanId?: string;
|
||||
spanPanelVariant?: SpanDetailVariant;
|
||||
}
|
||||
|
||||
interface RenderOptions {
|
||||
dataLoadedFiredForRef?: MutableRefObject<string>;
|
||||
threadEmptyFiredForRef?: MutableRefObject<string>;
|
||||
queryClient?: QueryClient;
|
||||
}
|
||||
|
||||
interface RenderResult {
|
||||
logTraceEvent: jest.MockedFunction<TraceDetailLogEvent>;
|
||||
rerender: (props: ThreadLoadedEventsProps) => void;
|
||||
unmount: () => void;
|
||||
queryClient: QueryClient;
|
||||
}
|
||||
|
||||
/** Serves the fixture summaries and returns the trace ids requested, in order. */
|
||||
export function mockTraceSummaries(): string[] {
|
||||
const requests: string[] = [];
|
||||
server.use(
|
||||
rest.get('*/api/v1/traces/:traceId/summary', (req, res, ctx) => {
|
||||
requests.push(req.params.traceId as string);
|
||||
const body: GetTraceSummary200 = {
|
||||
status: 'success',
|
||||
data: SUMMARIES[req.params.traceId as string],
|
||||
};
|
||||
return res(ctx.status(200), ctx.json(body));
|
||||
}),
|
||||
);
|
||||
return requests;
|
||||
}
|
||||
|
||||
export function renderThreadLoadedEvents(
|
||||
initialProps: ThreadLoadedEventsProps,
|
||||
{
|
||||
dataLoadedFiredForRef = { current: '' },
|
||||
threadEmptyFiredForRef = { current: '' },
|
||||
queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
}),
|
||||
}: RenderOptions = {},
|
||||
): RenderResult {
|
||||
const logTraceEvent = jest.fn() as jest.MockedFunction<TraceDetailLogEvent>;
|
||||
const wrapper = ({ children }: { children: ReactNode }): JSX.Element => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
const { rerender, unmount } = renderHook(
|
||||
({
|
||||
traceId,
|
||||
hasSpans = false,
|
||||
hasNoThread = false,
|
||||
interestedSpanId,
|
||||
spanPanelVariant = SpanDetailVariant.DOCKED_RIGHT,
|
||||
}: ThreadLoadedEventsProps) =>
|
||||
useThreadLoadedEvents({
|
||||
traceId,
|
||||
interestedSpanId,
|
||||
hasSpans,
|
||||
hasNoThread,
|
||||
spanPanelVariant,
|
||||
dataLoadedFiredForRef,
|
||||
threadEmptyFiredForRef,
|
||||
logTraceEvent,
|
||||
}),
|
||||
{ initialProps, wrapper },
|
||||
);
|
||||
return { logTraceEvent, rerender, unmount, queryClient };
|
||||
}
|
||||
|
||||
export async function waitForSummary(
|
||||
queryClient: QueryClient,
|
||||
traceId: string,
|
||||
): Promise<void> {
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
queryClient.getQueryData(getGetTraceSummaryQueryKey({ traceID: traceId })),
|
||||
).toBeDefined(),
|
||||
);
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
import { MutableRefObject, ReactNode } from 'react';
|
||||
import { QueryClient, QueryClientProvider } from 'react-query';
|
||||
import {
|
||||
GetTraceSummary200,
|
||||
SpantypesGettableTraceSummaryDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { getGetTraceSummaryQueryKey } from 'api/generated/services/tracedetail';
|
||||
import { rest, server } from 'mocks-server/server';
|
||||
import { renderHook, waitFor } from 'tests/test-utils';
|
||||
|
||||
import { TraceDetailsTab } from '../../../constants';
|
||||
import { TraceDetailEvents } from '../../../events';
|
||||
import { TraceDetailLogEvent } from '../../../hooks/useTraceDetailLogEvent';
|
||||
import { SpanDetailVariant } from '../../../SpanDetailsPanel/constants';
|
||||
import { useThreadDataLoadedEvent } from '../useThreadDataLoadedEvent';
|
||||
|
||||
const SUMMARIES: Record<string, SpantypesGettableTraceSummaryDTO> = {
|
||||
'trace-a': {
|
||||
startTimestampMillis: 1_000,
|
||||
endTimestampMillis: 4_000,
|
||||
totalSpansCount: 12,
|
||||
totalErrorSpansCount: 2,
|
||||
hasMissingSpans: false,
|
||||
rootServiceEntryPoint: 'POST /chat',
|
||||
rootServiceName: 'agent',
|
||||
rootSpanStatusCode: 'STATUS_CODE_ERROR',
|
||||
},
|
||||
'trace-b': {
|
||||
startTimestampMillis: 5_000,
|
||||
endTimestampMillis: 5_500,
|
||||
totalSpansCount: 3,
|
||||
totalErrorSpansCount: 0,
|
||||
hasMissingSpans: false,
|
||||
rootServiceEntryPoint: 'POST /chat',
|
||||
rootServiceName: 'agent',
|
||||
rootSpanStatusCode: 'STATUS_CODE_OK',
|
||||
},
|
||||
};
|
||||
|
||||
interface HookProps {
|
||||
traceId: string;
|
||||
hasSpans: boolean;
|
||||
spanPanelVariant?: SpanDetailVariant;
|
||||
}
|
||||
|
||||
function renderDataLoadedEvent(
|
||||
initialProps: HookProps,
|
||||
firedForRef: MutableRefObject<string> = { current: '' },
|
||||
): {
|
||||
logTraceEvent: jest.MockedFunction<TraceDetailLogEvent>;
|
||||
rerender: (props: HookProps) => void;
|
||||
queryClient: QueryClient;
|
||||
} {
|
||||
const logTraceEvent = jest.fn() as jest.MockedFunction<TraceDetailLogEvent>;
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
const wrapper = ({ children }: { children: ReactNode }): JSX.Element => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
const { rerender } = renderHook(
|
||||
({ traceId, hasSpans, spanPanelVariant }: HookProps) =>
|
||||
useThreadDataLoadedEvent({
|
||||
traceId,
|
||||
hasSpans,
|
||||
spanPanelVariant: spanPanelVariant ?? SpanDetailVariant.DOCKED_RIGHT,
|
||||
firedForRef,
|
||||
logTraceEvent,
|
||||
}),
|
||||
{ initialProps, wrapper },
|
||||
);
|
||||
return { logTraceEvent, rerender, queryClient };
|
||||
}
|
||||
|
||||
describe('useThreadDataLoadedEvent', () => {
|
||||
beforeEach(() => {
|
||||
server.use(
|
||||
rest.get('*/api/v1/traces/:traceId/summary', (req, res, ctx) => {
|
||||
const body: GetTraceSummary200 = {
|
||||
status: 'success',
|
||||
data: SUMMARIES[req.params.traceId as string],
|
||||
};
|
||||
return res(ctx.status(200), ctx.json(body));
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('waits for the trace summary, then reports it as a thread load', async () => {
|
||||
const { logTraceEvent } = renderDataLoadedEvent({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: true,
|
||||
});
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
expect(logTraceEvent).toHaveBeenCalledWith(TraceDetailEvents.DataLoaded, {
|
||||
detailsTab: TraceDetailsTab.Thread,
|
||||
totalSpansCount: 12,
|
||||
traceDurationMs: 3_000,
|
||||
hadErrors: true,
|
||||
spanPanelVariant: SpanDetailVariant.DOCKED_RIGHT,
|
||||
});
|
||||
});
|
||||
|
||||
it('waits for the thread spans even when the summary is already loaded', async () => {
|
||||
const { logTraceEvent, rerender, queryClient } = renderDataLoadedEvent({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: false,
|
||||
});
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
queryClient.getQueryData(
|
||||
getGetTraceSummaryQueryKey({ traceID: 'trace-a' }),
|
||||
),
|
||||
).toBeDefined(),
|
||||
);
|
||||
rerender({ traceId: 'trace-a', hasSpans: false });
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ traceId: 'trace-a', hasSpans: true });
|
||||
|
||||
expect(logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports a trace once, including when the tab is visited again', async () => {
|
||||
const firedForRef = { current: '' };
|
||||
const firstVisit = renderDataLoadedEvent(
|
||||
{ traceId: 'trace-a', hasSpans: true },
|
||||
firedForRef,
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(firstVisit.logTraceEvent).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
firstVisit.rerender({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: true,
|
||||
spanPanelVariant: SpanDetailVariant.DOCKED,
|
||||
});
|
||||
|
||||
const secondVisit = renderDataLoadedEvent(
|
||||
{ traceId: 'trace-a', hasSpans: true },
|
||||
firedForRef,
|
||||
);
|
||||
await waitFor(() =>
|
||||
expect(
|
||||
secondVisit.queryClient.getQueryData(
|
||||
getGetTraceSummaryQueryKey({ traceID: 'trace-a' }),
|
||||
),
|
||||
).toBeDefined(),
|
||||
);
|
||||
secondVisit.rerender({ traceId: 'trace-a', hasSpans: true });
|
||||
|
||||
expect(firstVisit.logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
expect(secondVisit.logTraceEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the next trace with its own summary', async () => {
|
||||
const { logTraceEvent, rerender } = renderDataLoadedEvent({
|
||||
traceId: 'trace-a',
|
||||
hasSpans: true,
|
||||
});
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
|
||||
rerender({ traceId: 'trace-b', hasSpans: true });
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(2));
|
||||
expect(logTraceEvent).toHaveBeenLastCalledWith(
|
||||
TraceDetailEvents.DataLoaded,
|
||||
expect.objectContaining({ totalSpansCount: 3, traceDurationMs: 500 }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,111 @@
|
||||
import { waitFor } from 'tests/test-utils';
|
||||
|
||||
import { TraceDetailsTab } from '../../../constants';
|
||||
import { TraceDetailEvents } from '../../../events';
|
||||
import { SpanDetailVariant } from '../../../SpanDetailsPanel/constants';
|
||||
import {
|
||||
mockTraceSummaries,
|
||||
renderThreadLoadedEvents,
|
||||
ThreadLoadedEventsProps,
|
||||
waitForSummary,
|
||||
} from './threadLoadedEventsTestUtils';
|
||||
|
||||
describe('useThreadLoadedEvents: data loaded', () => {
|
||||
beforeEach(() => {
|
||||
mockTraceSummaries();
|
||||
});
|
||||
|
||||
it('waits for the trace summary, then reports it as a thread load', async () => {
|
||||
const { logTraceEvent } = renderThreadLoadedEvents({
|
||||
traceId: 'trace-ai',
|
||||
hasSpans: true,
|
||||
});
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
expect(logTraceEvent).toHaveBeenCalledWith(TraceDetailEvents.DataLoaded, {
|
||||
detailsTab: TraceDetailsTab.Thread,
|
||||
totalSpansCount: 12,
|
||||
traceDurationMs: 3_000,
|
||||
hadErrors: true,
|
||||
spanPanelVariant: SpanDetailVariant.DOCKED_RIGHT,
|
||||
});
|
||||
});
|
||||
|
||||
it('waits for the thread spans even when the summary is already loaded', async () => {
|
||||
const { logTraceEvent, rerender, queryClient } = renderThreadLoadedEvents({
|
||||
traceId: 'trace-ai',
|
||||
});
|
||||
await waitForSummary(queryClient, 'trace-ai');
|
||||
rerender({ traceId: 'trace-ai' });
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ traceId: 'trace-ai', hasSpans: true });
|
||||
|
||||
expect(logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('reports a trace once, including when the tab is visited again', async () => {
|
||||
const dataLoadedFiredForRef = { current: '' };
|
||||
const props: ThreadLoadedEventsProps = {
|
||||
traceId: 'trace-ai',
|
||||
hasSpans: true,
|
||||
};
|
||||
const firstVisit = renderThreadLoadedEvents(props, { dataLoadedFiredForRef });
|
||||
await waitFor(() =>
|
||||
expect(firstVisit.logTraceEvent).toHaveBeenCalledTimes(1),
|
||||
);
|
||||
firstVisit.rerender({
|
||||
...props,
|
||||
spanPanelVariant: SpanDetailVariant.DOCKED,
|
||||
});
|
||||
|
||||
const secondVisit = renderThreadLoadedEvents(props, {
|
||||
dataLoadedFiredForRef,
|
||||
});
|
||||
await waitForSummary(secondVisit.queryClient, 'trace-ai');
|
||||
secondVisit.rerender(props);
|
||||
|
||||
expect(firstVisit.logTraceEvent).toHaveBeenCalledTimes(1);
|
||||
expect(secondVisit.logTraceEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the next trace with its own summary', async () => {
|
||||
const { logTraceEvent, rerender } = renderThreadLoadedEvents({
|
||||
traceId: 'trace-ai',
|
||||
hasSpans: true,
|
||||
});
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
|
||||
rerender({ traceId: 'trace-ai-next', hasSpans: true });
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(2));
|
||||
expect(logTraceEvent).toHaveBeenLastCalledWith(
|
||||
TraceDetailEvents.DataLoaded,
|
||||
expect.objectContaining({ totalSpansCount: 4, traceDurationMs: 500 }),
|
||||
);
|
||||
});
|
||||
|
||||
it('also reports an empty thread, once each, when an errored thread still holds spans', async () => {
|
||||
const props: ThreadLoadedEventsProps = {
|
||||
traceId: 'trace-ai',
|
||||
hasSpans: true,
|
||||
hasNoThread: true,
|
||||
};
|
||||
const { logTraceEvent, rerender } = renderThreadLoadedEvents(props);
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(2));
|
||||
rerender(props);
|
||||
|
||||
expect(logTraceEvent).toHaveBeenCalledTimes(2);
|
||||
expect(logTraceEvent).toHaveBeenCalledWith(
|
||||
TraceDetailEvents.DataLoaded,
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(logTraceEvent).toHaveBeenCalledWith(
|
||||
TraceDetailEvents.ThreadEmptyWithAiSummary,
|
||||
expect.any(Object),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { waitFor } from 'tests/test-utils';
|
||||
|
||||
import { TraceDetailsTab } from '../../../constants';
|
||||
import { TraceDetailEvents } from '../../../events';
|
||||
import {
|
||||
mockTraceSummaries,
|
||||
renderThreadLoadedEvents,
|
||||
ThreadLoadedEventsProps,
|
||||
waitForSummary,
|
||||
} from './threadLoadedEventsTestUtils';
|
||||
|
||||
describe('useThreadLoadedEvents: thread empty with AI summary', () => {
|
||||
let summaryRequests: string[];
|
||||
|
||||
beforeEach(() => {
|
||||
summaryRequests = mockTraceSummaries();
|
||||
});
|
||||
|
||||
it('reports the trace summary when the thread is empty but the summary has AI usage', async () => {
|
||||
const { logTraceEvent } = renderThreadLoadedEvents({
|
||||
traceId: 'trace-ai',
|
||||
hasNoThread: true,
|
||||
interestedSpanId: 'span-1',
|
||||
});
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
expect(logTraceEvent).toHaveBeenCalledWith(
|
||||
TraceDetailEvents.ThreadEmptyWithAiSummary,
|
||||
{
|
||||
detailsTab: TraceDetailsTab.Thread,
|
||||
spanId: 'span-1',
|
||||
rootServiceName: 'agent',
|
||||
rootServiceEntryPoint: 'POST /chat',
|
||||
totalSpansCount: 12,
|
||||
traceDurationMs: 3_000,
|
||||
hadErrors: true,
|
||||
hasMissingSpans: true,
|
||||
inputTokens: 1_200,
|
||||
outputTokens: 300,
|
||||
cacheReadTokens: 50,
|
||||
cacheWriteTokens: 10,
|
||||
reasoningTokens: 40,
|
||||
totalCost: 0.0123,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('does not report when the summary has no AI usage', async () => {
|
||||
const props: ThreadLoadedEventsProps = {
|
||||
traceId: 'trace-no-ai',
|
||||
hasNoThread: true,
|
||||
};
|
||||
const { logTraceEvent, rerender, queryClient } =
|
||||
renderThreadLoadedEvents(props);
|
||||
await waitForSummary(queryClient, 'trace-no-ai');
|
||||
rerender(props);
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('waits until the thread is known to be empty', async () => {
|
||||
const { logTraceEvent, rerender, queryClient } = renderThreadLoadedEvents({
|
||||
traceId: 'trace-ai',
|
||||
});
|
||||
await waitForSummary(queryClient, 'trace-ai');
|
||||
rerender({ traceId: 'trace-ai' });
|
||||
|
||||
expect(logTraceEvent).not.toHaveBeenCalled();
|
||||
|
||||
rerender({ traceId: 'trace-ai', hasNoThread: true });
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
|
||||
it('reports once per trace and reuses the loaded summary when the tab is visited again', async () => {
|
||||
const threadEmptyFiredForRef = { current: '' };
|
||||
const props: ThreadLoadedEventsProps = {
|
||||
traceId: 'trace-ai',
|
||||
hasNoThread: true,
|
||||
};
|
||||
const first = renderThreadLoadedEvents(props, { threadEmptyFiredForRef });
|
||||
await waitFor(() => expect(first.logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
first.unmount();
|
||||
|
||||
const second = renderThreadLoadedEvents(props, {
|
||||
threadEmptyFiredForRef,
|
||||
queryClient: first.queryClient,
|
||||
});
|
||||
|
||||
expect(second.queryClient.isFetching()).toBe(0);
|
||||
expect(summaryRequests).toStrictEqual(['trace-ai']);
|
||||
expect(second.logTraceEvent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports the next trace with its own summary', async () => {
|
||||
const { logTraceEvent, rerender } = renderThreadLoadedEvents({
|
||||
traceId: 'trace-ai',
|
||||
hasNoThread: true,
|
||||
});
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(1));
|
||||
|
||||
rerender({ traceId: 'trace-ai-next', hasNoThread: true });
|
||||
|
||||
await waitFor(() => expect(logTraceEvent).toHaveBeenCalledTimes(2));
|
||||
expect(logTraceEvent).toHaveBeenLastCalledWith(
|
||||
TraceDetailEvents.ThreadEmptyWithAiSummary,
|
||||
expect.objectContaining({
|
||||
totalSpansCount: 4,
|
||||
inputTokens: 80,
|
||||
totalCost: 0.0004,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,45 +0,0 @@
|
||||
import { MutableRefObject, useEffect } from 'react';
|
||||
import { useGetTraceSummary } from 'api/generated/services/tracedetail';
|
||||
|
||||
import { TraceDetailsTab } from '../../constants';
|
||||
import { TraceDetailEventKeys, TraceDetailEvents } from '../../events';
|
||||
import { TraceDetailLogEvent } from '../../hooks/useTraceDetailLogEvent';
|
||||
import { SpanDetailVariant } from '../../SpanDetailsPanel/constants';
|
||||
|
||||
interface ThreadDataLoadedEventArgs {
|
||||
traceId: string;
|
||||
hasSpans: boolean;
|
||||
spanPanelVariant: SpanDetailVariant;
|
||||
firedForRef: MutableRefObject<string>;
|
||||
logTraceEvent: TraceDetailLogEvent;
|
||||
}
|
||||
|
||||
export function useThreadDataLoadedEvent({
|
||||
traceId,
|
||||
hasSpans,
|
||||
spanPanelVariant,
|
||||
firedForRef,
|
||||
logTraceEvent,
|
||||
}: ThreadDataLoadedEventArgs): void {
|
||||
// No keepPreviousData: a previous trace's summary must not be reported for this one.
|
||||
const { data } = useGetTraceSummary(
|
||||
{ traceID: traceId },
|
||||
{ query: { enabled: !!traceId, refetchOnMount: false } },
|
||||
);
|
||||
const summary = data?.data;
|
||||
|
||||
useEffect(() => {
|
||||
if (!traceId || firedForRef.current === traceId || !hasSpans || !summary) {
|
||||
return;
|
||||
}
|
||||
firedForRef.current = traceId;
|
||||
logTraceEvent(TraceDetailEvents.DataLoaded, {
|
||||
[TraceDetailEventKeys.DetailsTab]: TraceDetailsTab.Thread,
|
||||
[TraceDetailEventKeys.TotalSpansCount]: summary.totalSpansCount,
|
||||
[TraceDetailEventKeys.TraceDurationMs]:
|
||||
summary.endTimestampMillis - summary.startTimestampMillis,
|
||||
[TraceDetailEventKeys.HadErrors]: summary.totalErrorSpansCount > 0,
|
||||
[TraceDetailEventKeys.SpanPanelVariant]: spanPanelVariant,
|
||||
});
|
||||
}, [traceId, hasSpans, summary, spanPanelVariant, firedForRef, logTraceEvent]);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { MutableRefObject, useEffect } from 'react';
|
||||
import { useGetTraceSummary } from 'api/generated/services/tracedetail';
|
||||
|
||||
import { TraceDetailEvents } from '../../events';
|
||||
import { TraceDetailLogEvent } from '../../hooks/useTraceDetailLogEvent';
|
||||
import { SpanDetailVariant } from '../../SpanDetailsPanel/constants';
|
||||
import {
|
||||
getThreadDataLoadedEventAttributes,
|
||||
getThreadEmptyWithAiEventAttributes,
|
||||
} from '../utils';
|
||||
|
||||
interface ThreadLoadedEventsArgs {
|
||||
traceId: string;
|
||||
interestedSpanId?: string;
|
||||
hasSpans: boolean;
|
||||
hasNoThread: boolean;
|
||||
spanPanelVariant: SpanDetailVariant;
|
||||
dataLoadedFiredForRef: MutableRefObject<string>;
|
||||
threadEmptyFiredForRef: MutableRefObject<string>;
|
||||
logTraceEvent: TraceDetailLogEvent;
|
||||
}
|
||||
|
||||
export function useThreadLoadedEvents({
|
||||
traceId,
|
||||
interestedSpanId,
|
||||
hasSpans,
|
||||
hasNoThread,
|
||||
spanPanelVariant,
|
||||
dataLoadedFiredForRef,
|
||||
threadEmptyFiredForRef,
|
||||
logTraceEvent,
|
||||
}: ThreadLoadedEventsArgs): void {
|
||||
// No keepPreviousData: a previous trace's summary must not be reported for this one.
|
||||
const { data } = useGetTraceSummary(
|
||||
{ traceID: traceId },
|
||||
{ query: { enabled: !!traceId, refetchOnMount: false } },
|
||||
);
|
||||
const summary = data?.data;
|
||||
|
||||
useEffect(() => {
|
||||
if (!traceId || !summary) {
|
||||
return;
|
||||
}
|
||||
// Not exclusive: an errored thread can still hold spans, so each event keeps its own ref.
|
||||
if (hasSpans && dataLoadedFiredForRef.current !== traceId) {
|
||||
dataLoadedFiredForRef.current = traceId;
|
||||
logTraceEvent(
|
||||
TraceDetailEvents.DataLoaded,
|
||||
getThreadDataLoadedEventAttributes(summary, spanPanelVariant),
|
||||
);
|
||||
}
|
||||
if (hasNoThread && summary.ai && threadEmptyFiredForRef.current !== traceId) {
|
||||
threadEmptyFiredForRef.current = traceId;
|
||||
logTraceEvent(
|
||||
TraceDetailEvents.ThreadEmptyWithAiSummary,
|
||||
getThreadEmptyWithAiEventAttributes(summary, interestedSpanId),
|
||||
);
|
||||
}
|
||||
}, [
|
||||
traceId,
|
||||
interestedSpanId,
|
||||
hasSpans,
|
||||
hasNoThread,
|
||||
summary,
|
||||
spanPanelVariant,
|
||||
dataLoadedFiredForRef,
|
||||
threadEmptyFiredForRef,
|
||||
logTraceEvent,
|
||||
]);
|
||||
}
|
||||
@@ -1,7 +1,13 @@
|
||||
import type { SpantypesThreadSpanDTO } from 'api/generated/services/sigNoz.schemas';
|
||||
import type {
|
||||
SpantypesGettableTraceSummaryDTO,
|
||||
SpantypesThreadSpanDTO,
|
||||
} from 'api/generated/services/sigNoz.schemas';
|
||||
import { isAxiosError } from 'axios';
|
||||
|
||||
import { collectToolCallKeys } from '../AIThreadMessage/utils';
|
||||
import { TraceDetailsTab } from '../constants';
|
||||
import { TraceDetailEventKeys } from '../events';
|
||||
import { SpanDetailVariant } from '../SpanDetailsPanel/constants';
|
||||
import { InterestedSpanStatus, ThreadSpan } from './types';
|
||||
|
||||
/** Derives SpanV3's `timestamp` and `service.name`, as the waterfall does. */
|
||||
@@ -47,3 +53,44 @@ export function getInterestedSpanStatus(
|
||||
? InterestedSpanStatus.Found
|
||||
: InterestedSpanStatus.NoIOMessages;
|
||||
}
|
||||
|
||||
function getThreadSummaryAttributes(
|
||||
summary: SpantypesGettableTraceSummaryDTO,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
[TraceDetailEventKeys.DetailsTab]: TraceDetailsTab.Thread,
|
||||
[TraceDetailEventKeys.TotalSpansCount]: summary.totalSpansCount,
|
||||
[TraceDetailEventKeys.TraceDurationMs]:
|
||||
summary.endTimestampMillis - summary.startTimestampMillis,
|
||||
[TraceDetailEventKeys.HadErrors]: summary.totalErrorSpansCount > 0,
|
||||
};
|
||||
}
|
||||
|
||||
export function getThreadDataLoadedEventAttributes(
|
||||
summary: SpantypesGettableTraceSummaryDTO,
|
||||
spanPanelVariant: SpanDetailVariant,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
...getThreadSummaryAttributes(summary),
|
||||
[TraceDetailEventKeys.SpanPanelVariant]: spanPanelVariant,
|
||||
};
|
||||
}
|
||||
|
||||
export function getThreadEmptyWithAiEventAttributes(
|
||||
summary: SpantypesGettableTraceSummaryDTO,
|
||||
interestedSpanId: string | undefined,
|
||||
): Record<string, unknown> {
|
||||
return {
|
||||
...getThreadSummaryAttributes(summary),
|
||||
[TraceDetailEventKeys.SpanId]: interestedSpanId,
|
||||
[TraceDetailEventKeys.RootServiceName]: summary.rootServiceName,
|
||||
[TraceDetailEventKeys.RootServiceEntryPoint]: summary.rootServiceEntryPoint,
|
||||
[TraceDetailEventKeys.HasMissingSpans]: summary.hasMissingSpans,
|
||||
[TraceDetailEventKeys.InputTokens]: summary.ai?.tokens.input,
|
||||
[TraceDetailEventKeys.OutputTokens]: summary.ai?.tokens.output,
|
||||
[TraceDetailEventKeys.CacheReadTokens]: summary.ai?.tokens.cacheRead,
|
||||
[TraceDetailEventKeys.CacheWriteTokens]: summary.ai?.tokens.cacheWrite,
|
||||
[TraceDetailEventKeys.ReasoningTokens]: summary.ai?.tokens.reasoning,
|
||||
[TraceDetailEventKeys.TotalCost]: summary.ai?.totalCost,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ export enum TraceDetailEvents {
|
||||
SpanPercentileAttributeChanged = 'Trace Detail: Span percentile attribute changed',
|
||||
SpanDetailsOpened = 'Trace Detail: Span details opened',
|
||||
DetailsTabChanged = 'Trace Detail: Details tab changed',
|
||||
ThreadEmptyWithAiSummary = 'Trace Detail: Thread empty with AI summary',
|
||||
}
|
||||
|
||||
export enum TraceDetailEventKeys {
|
||||
@@ -48,6 +49,16 @@ export enum TraceDetailEventKeys {
|
||||
Selected = 'selected',
|
||||
// Data loaded / span details opened: which tab the user is on
|
||||
DetailsTab = 'detailsTab',
|
||||
// Thread empty with AI summary (reuses SpanId, DetailsTab, TotalSpansCount, TraceDurationMs, HadErrors)
|
||||
RootServiceName = 'rootServiceName',
|
||||
RootServiceEntryPoint = 'rootServiceEntryPoint',
|
||||
HasMissingSpans = 'hasMissingSpans',
|
||||
InputTokens = 'inputTokens',
|
||||
OutputTokens = 'outputTokens',
|
||||
CacheReadTokens = 'cacheReadTokens',
|
||||
CacheWriteTokens = 'cacheWriteTokens',
|
||||
ReasoningTokens = 'reasoningTokens',
|
||||
TotalCost = 'totalCost',
|
||||
}
|
||||
|
||||
export type TraceDetailView = 'v2' | 'v3';
|
||||
|
||||
@@ -17,6 +17,7 @@ function TraceDetailsV3(): JSX.Element {
|
||||
// between traces (the route component stays mounted) re-fires it once each.
|
||||
const dataLoadedFiredForRef = useRef<string>('');
|
||||
const threadDataLoadedFiredForRef = useRef<string>('');
|
||||
const threadEmptyFiredForRef = useRef<string>('');
|
||||
|
||||
const handleFilteredSpansChange = useCallback(
|
||||
(spanIds: string[], isActive: boolean): void => {
|
||||
@@ -40,7 +41,10 @@ function TraceDetailsV3(): JSX.Element {
|
||||
dataLoadedFiredForRef={dataLoadedFiredForRef}
|
||||
/>
|
||||
) : (
|
||||
<TraceDetailsThread dataLoadedFiredForRef={threadDataLoadedFiredForRef} />
|
||||
<TraceDetailsThread
|
||||
dataLoadedFiredForRef={threadDataLoadedFiredForRef}
|
||||
threadEmptyFiredForRef={threadEmptyFiredForRef}
|
||||
/>
|
||||
)}
|
||||
</TraceDetailsWrapper>
|
||||
);
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { SpantypesPostableTraceAggregationsDTO } from 'api/generated/servic
|
||||
import { LOCALSTORAGE } from 'constants/localStorage';
|
||||
import { USER_PREFERENCES } from 'constants/userPreferences';
|
||||
import { screen, userEvent, within } from 'storybook/test';
|
||||
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
import type { QueryRangeRequestV5, RawRow } from 'types/api/v5/queryRange';
|
||||
|
||||
import {
|
||||
choiceControl,
|
||||
@@ -150,6 +150,12 @@ export const traceDetailsMocks = defineStoryMocks({
|
||||
value: 8,
|
||||
max: 20,
|
||||
}),
|
||||
traceOnlyLogs: toggleControl('Logs only on the trace', {
|
||||
group: PANEL,
|
||||
description:
|
||||
'The span has no logs of its own but the trace does, which is the Logs tab\'s "view logs for the current trace" state.',
|
||||
value: false,
|
||||
}),
|
||||
exportState: choiceControl<ExportState>('Trace export', {
|
||||
group: EXPORT,
|
||||
description:
|
||||
@@ -165,6 +171,12 @@ export const traceDetailsMocks = defineStoryMocks({
|
||||
errors: values.errors,
|
||||
traceStart: traceStartOf(),
|
||||
};
|
||||
const spanLogRowsFor = (body: QueryRangeRequestV5): RawRow[] => {
|
||||
const scope = spanLogScopeOf(body);
|
||||
const count =
|
||||
values.traceOnlyLogs && scope !== 'trace' ? 0 : values.spanLogs;
|
||||
return spanLogRows(count, trace, scope);
|
||||
};
|
||||
|
||||
return [
|
||||
rest.post('http://localhost/api/v1/export_raw_data', (_req, res, ctx) => {
|
||||
@@ -266,9 +278,7 @@ export const traceDetailsMocks = defineStoryMocks({
|
||||
|
||||
if (requestType === 'raw') {
|
||||
return queryRangeV5RawResponse(
|
||||
signalOf(body) === 'logs'
|
||||
? spanLogRows(values.spanLogs, trace, spanLogScopeOf(body))
|
||||
: spanMatchRows(trace),
|
||||
signalOf(body) === 'logs' ? spanLogRowsFor(body) : spanMatchRows(trace),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
focusSpanIndex,
|
||||
scenarioSpanCount,
|
||||
spanIdAt,
|
||||
STORY_TRACE_ID,
|
||||
} from './__story_mockdata__/traceDetails';
|
||||
import {
|
||||
openRowMenu,
|
||||
@@ -249,18 +248,35 @@ export const SpanPercentileOpen: Story = {
|
||||
},
|
||||
};
|
||||
|
||||
/** The span's trace id clicked in the panel, which copies it. */
|
||||
export const TraceIdCopiedToast: Story = {
|
||||
/** The span has no logs of its own but its trace does, so the Logs tab points to the trace's. */
|
||||
export const SpanPanelTraceOnlyLogs: Story = {
|
||||
args: { traceOnlyLogs: true },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByRole('tab', { name: /Logs/ }, untilLoaded),
|
||||
);
|
||||
await expect(
|
||||
await within(canvasElement).findByText(
|
||||
'No logs found for selected span. View logs for the current trace.',
|
||||
undefined,
|
||||
untilLoaded,
|
||||
),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
/** The span panel's trace id copied with its copy button, which turns into a check. */
|
||||
export const TraceIdCopied: Story = {
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await within(canvasElement).findByRole(
|
||||
'button',
|
||||
{ name: STORY_TRACE_ID },
|
||||
{ name: 'Copy trace ID' },
|
||||
untilLoaded,
|
||||
),
|
||||
);
|
||||
await expect(
|
||||
await screen.findByText('Trace ID copied to clipboard'),
|
||||
await within(canvasElement).findByRole('button', { name: 'Copied' }),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
13
frontend/src/pages/TracesExplorer/TracesExplorer.module.scss
Normal file
13
frontend/src/pages/TracesExplorer/TracesExplorer.module.scss
Normal file
@@ -0,0 +1,13 @@
|
||||
.views {
|
||||
padding: 8px 0;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.tableView {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.insetView {
|
||||
flex: 1;
|
||||
padding-inline: 8px;
|
||||
}
|
||||
@@ -21,15 +21,6 @@
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.traces-explorer-views {
|
||||
padding: 8px;
|
||||
margin-bottom: 24px;
|
||||
|
||||
.ant-tabs-tabpane {
|
||||
padding: 0 8px;
|
||||
}
|
||||
}
|
||||
|
||||
.qb-search-view-container {
|
||||
padding: 8px;
|
||||
|
||||
@@ -47,22 +38,6 @@
|
||||
}
|
||||
}
|
||||
|
||||
.trace-explorer-list-view {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.trace-explorer-traces-view {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.trace-explorer-table-view {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.trace-explorer-time-series-view {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.trace-explorer-page {
|
||||
// Meant to fix the query builder colors
|
||||
--input-background: var(--l2-background);
|
||||
|
||||
@@ -168,16 +168,17 @@ describe('TracesExplorer -', () => {
|
||||
),
|
||||
);
|
||||
|
||||
const { getByText } = renderWithTracesExplorerRouter(<TracesExplorer />);
|
||||
renderWithTracesExplorerRouter(<TracesExplorer />);
|
||||
|
||||
await screen.findByText(FILTER_SERVICE_NAME);
|
||||
|
||||
await screen.findByText('demo-app');
|
||||
expect(getByText('options_menu.options')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByTestId('periscope-btn-options-traces'),
|
||||
).toBeInTheDocument();
|
||||
|
||||
// test if pagination is there
|
||||
expect(getByText('Previous')).toBeInTheDocument();
|
||||
expect(getByText('Next')).toBeInTheDocument();
|
||||
// the list scrolls instead of paging
|
||||
expect(screen.queryByTestId('pagination-page-size')).not.toBeInTheDocument();
|
||||
|
||||
// column interaction is covered in E2E tests as its a complex interaction
|
||||
});
|
||||
|
||||
@@ -55,6 +55,8 @@ import {
|
||||
} from './aiActions';
|
||||
import TimeSeriesView from './TimeSeriesView';
|
||||
|
||||
import styles from './TracesExplorer.module.scss';
|
||||
|
||||
import './TracesExplorer.styles.scss';
|
||||
|
||||
function TracesExplorer(): JSX.Element {
|
||||
@@ -272,13 +274,13 @@ function TracesExplorer(): JSX.Element {
|
||||
<QuerySection />
|
||||
</div>
|
||||
|
||||
<div className="traces-explorer-views">
|
||||
<div className={styles.views}>
|
||||
{isCancelled && (
|
||||
<QueryCancelledPlaceholder subText='Click "Run Query" to load traces.' />
|
||||
)}
|
||||
|
||||
{!isCancelled && selectedView === ExplorerViews.LIST && (
|
||||
<div className="trace-explorer-list-view">
|
||||
<div className={styles.tableView}>
|
||||
<ListView
|
||||
isFilterApplied={isFilterApplied}
|
||||
setWarning={setWarning}
|
||||
@@ -290,7 +292,7 @@ function TracesExplorer(): JSX.Element {
|
||||
)}
|
||||
|
||||
{!isCancelled && selectedView === ExplorerViews.TRACE && (
|
||||
<div className="trace-explorer-traces-view">
|
||||
<div className={styles.tableView}>
|
||||
<TracesView
|
||||
isFilterApplied={isFilterApplied}
|
||||
setWarning={setWarning}
|
||||
@@ -302,7 +304,7 @@ function TracesExplorer(): JSX.Element {
|
||||
)}
|
||||
|
||||
{!isCancelled && selectedView === ExplorerViews.TIMESERIES && (
|
||||
<div className="trace-explorer-time-series-view">
|
||||
<div className={styles.insetView}>
|
||||
<TimeSeriesView
|
||||
dataSource={DataSource.TRACES}
|
||||
isFilterApplied={isFilterApplied}
|
||||
@@ -315,7 +317,7 @@ function TracesExplorer(): JSX.Element {
|
||||
)}
|
||||
|
||||
{!isCancelled && selectedView === ExplorerViews.TABLE && (
|
||||
<div className="trace-explorer-table-view">
|
||||
<div className={styles.insetView}>
|
||||
<TableView
|
||||
setWarning={setWarning}
|
||||
setIsLoadingQueries={setIsLoadingQueries}
|
||||
|
||||
@@ -6,7 +6,9 @@
|
||||
import { rest } from 'msw';
|
||||
import { QueryParams } from 'constants/query';
|
||||
import ROUTES from 'constants/routes';
|
||||
import { USER_PREFERENCES } from 'constants/userPreferences';
|
||||
import { ExplorerViews } from 'pages/LogsExplorer/utils';
|
||||
import { spanPercentilesResponse } from 'pages/TraceDetailsV3/stories/__story_mockdata__/traceDetails';
|
||||
import type { QueryRangeRequestV5 } from 'types/api/v5/queryRange';
|
||||
import { explorerViewToPanelType } from 'utils/explorerUtils';
|
||||
|
||||
@@ -27,6 +29,10 @@ import {
|
||||
import {
|
||||
exportDashboardsResponse,
|
||||
savedTraceViewsResponse,
|
||||
SPAN_LOGS_STATES,
|
||||
spanLogRows,
|
||||
spanLogScopeOf,
|
||||
type SpanLogsState,
|
||||
traceAttributeValuesResponse,
|
||||
traceFieldKeysResponse,
|
||||
traceFieldValues,
|
||||
@@ -34,8 +40,11 @@ import {
|
||||
traceQuickFiltersResponse,
|
||||
traceRootSpanRows,
|
||||
traceSpanRows,
|
||||
TRACE_SUMMARY_STATES,
|
||||
traceSummaryResponse,
|
||||
TRACES_EXPLORER_VIEWS,
|
||||
TRACES_TABS,
|
||||
type TraceSummaryState,
|
||||
type TracesTab,
|
||||
} from './__story_mockdata__/traces';
|
||||
|
||||
@@ -65,6 +74,8 @@ const tracesRoute = ({ tab, view }: RouteValues): string => {
|
||||
interface RawQuerySpec {
|
||||
limit?: number;
|
||||
offset?: number;
|
||||
signal?: string;
|
||||
filter?: { expression?: string };
|
||||
}
|
||||
|
||||
const rawSpecOf = (body: QueryRangeRequestV5): RawQuerySpec => {
|
||||
@@ -73,6 +84,9 @@ const rawSpecOf = (body: QueryRangeRequestV5): RawQuerySpec => {
|
||||
return spec as RawQuerySpec;
|
||||
};
|
||||
|
||||
// The summary has no window of its own; its bounds wrap the span the list showed.
|
||||
const listWindow = { start: 0, end: 0 };
|
||||
|
||||
export const tracesMocks = defineStoryMocks({
|
||||
controls: {
|
||||
tab: choiceControl<TracesTab>('Tab', {
|
||||
@@ -92,9 +106,9 @@ export const tracesMocks = defineStoryMocks({
|
||||
spans: countControl('Spans', {
|
||||
group: LIST,
|
||||
description:
|
||||
'Spans the endpoint has, one root span per trace in the Trace view. The table asks for a page at a time, so a higher count paginates.',
|
||||
'Spans the endpoint has, one root span per trace in the Trace view. The list loads 100 more as it scrolls to the end; the Trace view pages 20 at a time.',
|
||||
value: 24,
|
||||
max: 40,
|
||||
max: 250,
|
||||
}),
|
||||
errors: toggleControl('Failing spans', {
|
||||
group: LIST,
|
||||
@@ -102,6 +116,20 @@ export const tracesMocks = defineStoryMocks({
|
||||
'Answers 503 on the spans of the services that fail, which is what the status column and the error colouring read.',
|
||||
value: true,
|
||||
}),
|
||||
traceSummary: choiceControl<TraceSummaryState>('Trace summary', {
|
||||
group: LIST,
|
||||
description:
|
||||
'What the span drawer gets for the trace start and end. Not found falls back to span-only logs; loading holds the logs tab.',
|
||||
options: TRACE_SUMMARY_STATES,
|
||||
value: 'found',
|
||||
}),
|
||||
spanLogs: choiceControl<SpanLogsState>('Span logs', {
|
||||
group: LIST,
|
||||
description:
|
||||
"What the span drawer's Logs tab gets. `span`: the span's logs with context either side; `trace only`: none for the span but some for the trace; `none`; `loading` and `error` hold or fail only the log queries.",
|
||||
options: SPAN_LOGS_STATES,
|
||||
value: 'span',
|
||||
}),
|
||||
warning: toggleControl('Query warning', {
|
||||
group: LIST,
|
||||
description: 'Attaches a warning to the response, next to the toolbar.',
|
||||
@@ -169,6 +197,96 @@ export const tracesMocks = defineStoryMocks({
|
||||
response.json(exportDashboardsResponse),
|
||||
),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v1/span_percentile',
|
||||
response.json(spanPercentilesResponse),
|
||||
),
|
||||
|
||||
// Answers on its own control rather than the Data one, so the drawer's
|
||||
// fallback and waiting states are reachable with the list loaded.
|
||||
rest.get(
|
||||
'http://localhost/api/v1/traces/:traceId/summary',
|
||||
(req, res, ctx) => {
|
||||
if (values.traceSummary === 'loading') {
|
||||
return res(ctx.delay('infinite'));
|
||||
}
|
||||
const summary =
|
||||
values.traceSummary === 'found'
|
||||
? traceSummaryResponse({
|
||||
traceId: String(req.params.traceId),
|
||||
count: values.spans,
|
||||
...listWindow,
|
||||
})
|
||||
: null;
|
||||
|
||||
return summary
|
||||
? res(ctx.status(200), ctx.json(summary))
|
||||
: 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',
|
||||
response.json((req) => ({
|
||||
status: 'success',
|
||||
data: {
|
||||
name: String(req.params.name),
|
||||
description: 'storybook',
|
||||
valueType: 'array',
|
||||
defaultValue: [],
|
||||
allowedValues: [],
|
||||
allowedScopes: ['user'],
|
||||
value:
|
||||
String(req.params.name) ===
|
||||
USER_PREFERENCES.SPAN_PERCENTILE_RESOURCE_ATTRIBUTES
|
||||
? ['service.name']
|
||||
: [],
|
||||
},
|
||||
})),
|
||||
),
|
||||
|
||||
// The drawer's log queries answer on their own control, so they can hang or
|
||||
// fail with the list loaded. Anything else falls through to the next handler.
|
||||
rest.post('http://localhost/api/v5/query_range', async (req, res, ctx) => {
|
||||
const body = (await req.json()) as QueryRangeRequestV5;
|
||||
const { signal, filter } = rawSpecOf(body);
|
||||
if (signal !== 'logs') {
|
||||
return undefined;
|
||||
}
|
||||
if (values.spanLogs === 'loading') {
|
||||
return res(ctx.delay('infinite'));
|
||||
}
|
||||
if (values.spanLogs === 'error') {
|
||||
return res(
|
||||
ctx.status(500),
|
||||
ctx.json({ status: 'error', error: 'storybook logs failure' }),
|
||||
);
|
||||
}
|
||||
|
||||
const expression = filter?.expression ?? '';
|
||||
const scope = spanLogScopeOf(expression);
|
||||
const answers =
|
||||
values.spanLogs === 'span' ||
|
||||
(values.spanLogs === 'trace only' && scope === 'trace');
|
||||
|
||||
return res(
|
||||
ctx.status(200),
|
||||
ctx.json(
|
||||
queryRangeV5RawResponse(
|
||||
answers
|
||||
? spanLogRows({
|
||||
scope,
|
||||
expression,
|
||||
startMicros: body.start,
|
||||
endMicros: body.end,
|
||||
})
|
||||
: [],
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
|
||||
rest.post(
|
||||
'http://localhost/api/v5/query_range',
|
||||
response.json(async (req) => {
|
||||
@@ -195,6 +313,9 @@ export const tracesMocks = defineStoryMocks({
|
||||
: undefined;
|
||||
|
||||
if (requestType === 'raw' || requestType === 'trace') {
|
||||
listWindow.start = start;
|
||||
listWindow.end = end;
|
||||
|
||||
return queryRangeV5RawResponse(
|
||||
requestType === 'trace' ? traceRootSpanRows(rows) : traceSpanRows(rows),
|
||||
{
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
typeFilter,
|
||||
} from 'components/QueryBuilderV2/QueryV2/QuerySearch/stories/__story_mockdata__/querySearch.play';
|
||||
import { ExplorerViews } from 'pages/LogsExplorer/utils';
|
||||
import { expect, screen, userEvent, waitFor } from 'storybook/test';
|
||||
import { expect, screen, userEvent, waitFor, within } from 'storybook/test';
|
||||
|
||||
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
|
||||
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
|
||||
@@ -25,7 +25,7 @@ const pageStory = storyMocks(tracesMocks, { layout: 'app' });
|
||||
* Route: `/traces-explorer`.
|
||||
*/
|
||||
const meta = {
|
||||
title: 'Pages/Traces/Explorer',
|
||||
title: 'Pages/Traces/Explorer/Overview',
|
||||
tags: ['play'],
|
||||
component: TracesModulePage,
|
||||
...pageStory,
|
||||
@@ -58,19 +58,56 @@ const openQuickFiltersSettings = async (): Promise<void> => {
|
||||
|
||||
/**
|
||||
* The Explorer tab on a full window of spans: the org's quick filters down the
|
||||
* left, the query builder and the view switcher above, and the list paging ten
|
||||
* spans at a time with the failing ones answering 503.
|
||||
* left, the query builder and the view switcher above, and the span list with
|
||||
* the failing ones answering 503.
|
||||
*/
|
||||
export const Default: Story = {};
|
||||
|
||||
/**
|
||||
* The Trace view, which shows one row per trace: its root span, the root
|
||||
* duration and how many spans the trace has.
|
||||
* duration and how many spans the trace has, twenty traces to a page.
|
||||
*/
|
||||
export const RootSpans: Story = {
|
||||
args: { view: ExplorerViews.TRACE },
|
||||
};
|
||||
|
||||
/**
|
||||
* The Trace view on its second page. The API sends no total, so the pager
|
||||
* offers one more page after each full one.
|
||||
*/
|
||||
export const RootSpansNextPage: Story = {
|
||||
args: { view: ExplorerViews.TRACE, spans: 50 },
|
||||
play: async (): Promise<void> => {
|
||||
await userEvent.click(
|
||||
await screen.findByRole('button', { name: 'Go to next page' }, untilLoaded),
|
||||
);
|
||||
const pager = screen.getByLabelText('pagination');
|
||||
|
||||
await expect(
|
||||
await within(pager).findByText('3', undefined, untilLoaded),
|
||||
).toBeVisible();
|
||||
},
|
||||
};
|
||||
|
||||
/** The span list scrolled to its end, with the next 100 spans loaded under the first. */
|
||||
export const ListNextPage: Story = {
|
||||
args: { spans: 150 },
|
||||
play: async ({ canvasElement }): Promise<void> => {
|
||||
// Scrolls again on every attempt, since each loaded page moves the end.
|
||||
await waitFor(async (): Promise<void> => {
|
||||
const scroller = canvasElement.querySelector<HTMLElement>(
|
||||
'[data-virtuoso-scroller]',
|
||||
);
|
||||
|
||||
await expect(scroller).not.toBeNull();
|
||||
(scroller as HTMLElement).scrollTop = (scroller as HTMLElement).scrollHeight;
|
||||
await expect(
|
||||
canvasElement.querySelector('tr[data-index="120"]'),
|
||||
).not.toBeNull();
|
||||
}, untilLoaded);
|
||||
},
|
||||
};
|
||||
|
||||
/** The charted view of the same trace query. */
|
||||
export const Timeseries: Story = {
|
||||
args: { view: ExplorerViews.TIMESERIES },
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user