Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix: added download button in trace page (#10613)

Tushar Vats79b4c2e4b0fe
diff --git a/frontend/src/api/v1/download/downloadExportData.ts b/frontend/src/api/v1/download/downloadExportData.ts
index 30bc7b25dd..73004b5a0f 100644
--- a/frontend/src/api/v1/download/downloadExportData.ts
+++ b/frontend/src/api/v1/download/downloadExportData.ts
@@ -8,42 +8,32 @@ export const downloadExportData = async (
props: ExportRawDataProps,
): Promise<void> => {
try {
- const queryParams = new URLSearchParams();
-
- queryParams.append('start', String(props.start));
- queryParams.append('end', String(props.end));
- queryParams.append('filter', props.filter);
- props.columns.forEach((col) => {
- queryParams.append('columns', col);
- });
- queryParams.append('order_by', props.orderBy);
- queryParams.append('limit', String(props.limit));
- queryParams.append('format', props.format);
-
- const response = await axios.get<Blob>(`export_raw_data?${queryParams}`, {
- responseType: 'blob', // Important: tell axios to handle response as blob
- decompress: true, // Enable automatic decompression
- headers: {
- Accept: 'application/octet-stream', // Tell server we expect binary data
+ const response = await axios.post<Blob>(
+ `export_raw_data?format=${encodeURIComponent(props.format)}`,
+ props.body,
+ {
+ responseType: 'blob',
+ decompress: true,
+ headers: {
+ Accept: 'application/octet-stream',
+ 'Content-Type': 'application/json',
+ },
+ timeout: 0,
},
- timeout: 0,
- });
+ );
- // Only proceed if the response status is 200
if (response.status !== 200) {
throw new Error(
`Failed to download data: server returned status ${response.status}`,
);
}
- // Create blob URL from response data
+
const blob = new Blob([response.data], { type: 'application/octet-stream' });
const url = window.URL.createObjectURL(blob);
- // Create and configure download link
const link = document.createElement('a');
link.href = url;
- // Get filename from Content-Disposition header or generate timestamped default
const filename =
response.headers['content-disposition']
?.split('filename=')[1]
@@ -51,7 +41,6 @@ export const downloadExportData = async (
link.setAttribute('download', filename);
- // Trigger download
document.body.appendChild(link);
link.click();
link.remove();
diff --git a/frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.styles.scss b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.styles.scss
similarity index 71%
rename from frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.styles.scss
rename to frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.styles.scss
index e9f2d92df3..ca9f81e5c3 100644
--- a/frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.styles.scss
+++ b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.styles.scss
@@ -1,11 +1,11 @@
-.logs-download-popover {
+.download-popover {
.ant-popover-inner {
border-radius: 4px;
- border: 1px solid var(--bg-slate-400);
+ border: 1px solid var(--l3-border);
background: linear-gradient(
139deg,
- var(--bg-ink-400) 0%,
- var(--bg-ink-500) 98.68%
+ var(--l2-background) 0%,
+ var(--l3-background) 98.68%
);
box-shadow: 4px 10px 16px 2px rgba(0, 0, 0, 0.2);
backdrop-filter: blur(20px);
@@ -19,7 +19,7 @@
.title {
display: flex;
- color: var(--bg-slate-50);
+ color: var(--l3-foreground);
font-family: Inter;
font-size: 11px;
font-style: normal;
@@ -38,7 +38,7 @@
flex-direction: column;
:global(.ant-radio-wrapper) {
- color: var(--bg-vanilla-400);
+ color: var(--foreground);
font-family: Inter;
font-size: 13px;
}
@@ -46,7 +46,7 @@
.horizontal-line {
height: 1px;
- background: var(--bg-slate-400);
+ background: var(--l3-border);
}
.export-button {
@@ -59,27 +59,27 @@
}
.lightMode {
- .logs-download-popover {
+ .download-popover {
.ant-popover-inner {
- border: 1px solid var(--bg-vanilla-300);
+ border: 1px solid var(--l2-border);
background: linear-gradient(
139deg,
- var(--bg-vanilla-100) 0%,
- var(--bg-vanilla-300) 98.68%
+ var(--background) 0%,
+ var(--l1-background) 98.68%
);
box-shadow: 4px 10px 16px 2px rgba(255, 255, 255, 0.2);
}
.export-options-container {
.title {
- color: var(--bg-ink-200);
+ color: var(--l2-foreground);
}
:global(.ant-radio-wrapper) {
- color: var(--bg-ink-400);
+ color: var(--foreground);
}
.horizontal-line {
- background: var(--bg-vanilla-300);
+ background: var(--l2-border);
}
}
}
diff --git a/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.test.tsx b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.test.tsx
new file mode 100644
index 0000000000..6de2dfc1be
--- /dev/null
+++ b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.test.tsx
@@ -0,0 +1,331 @@
+// eslint-disable-next-line no-restricted-imports
+import { Provider } from 'react-redux';
+import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { message } from 'antd';
+import configureStore from 'redux-mock-store';
+import store from 'store';
+import { Query } from 'types/api/queryBuilder/queryBuilderData';
+import { EQueryType } from 'types/common/dashboard';
+import { DataSource, StringOperators } from 'types/common/queryBuilder';
+
+import '@testing-library/jest-dom';
+
+import { DownloadFormats, DownloadRowCounts } from './constants';
+import DownloadOptionsMenu from './DownloadOptionsMenu';
+
+const mockDownloadExportData = jest.fn().mockResolvedValue(undefined);
+jest.mock('api/v1/download/downloadExportData', () => ({
+ downloadExportData: (...args: any[]): any => mockDownloadExportData(...args),
+ default: (...args: any[]): any => mockDownloadExportData(...args),
+}));
+
+jest.mock('antd', () => {
+ const actual = jest.requireActual('antd');
+ return {
+ ...actual,
+ message: {
+ success: jest.fn(),
+ error: jest.fn(),
+ },
+ };
+});
+
+const mockUseQueryBuilder = jest.fn();
+jest.mock('hooks/queryBuilder/useQueryBuilder', () => ({
+ useQueryBuilder: (): any => mockUseQueryBuilder(),
+}));
+
+const mockStore = configureStore([]);
+const createMockReduxStore = (): any =>
+ mockStore({
+ ...store.getState(),
+ });
+
+const createMockStagedQuery = (dataSource: DataSource): Query => ({
+ id: 'test-query-id',
+ queryType: EQueryType.QUERY_BUILDER,
+ builder: {
+ queryData: [
+ {
+ queryName: 'A',
+ dataSource,
+ aggregateOperator: StringOperators.NOOP,
+ aggregateAttribute: {
+ id: '',
+ dataType: '' as any,
+ key: '',
+ type: '',
+ },
+ aggregations: [{ expression: 'count()' }],
+ functions: [],
+ filter: { expression: 'status = 200' },
+ filters: { items: [], op: 'AND' },
+ groupBy: [],
+ expression: 'A',
+ disabled: false,
+ having: { expression: '' } as any,
+ limit: null,
+ stepInterval: null,
+ orderBy: [{ columnName: 'timestamp', order: 'desc' }],
+ legend: '',
+ selectColumns: [],
+ },
+ ],
+ queryFormulas: [],
+ queryTraceOperator: [],
+ },
+ promql: [],
+ clickhouse_sql: [],
+});
+
+const renderWithStore = (dataSource: DataSource): void => {
+ const mockReduxStore = createMockReduxStore();
+ render(
+ <Provider store={mockReduxStore}>
+ <DownloadOptionsMenu dataSource={dataSource} />
+ </Provider>,
+ );
+};
+
+describe.each([
+ [DataSource.LOGS, 'logs'],
+ [DataSource.TRACES, 'traces'],
+])('DownloadOptionsMenu for %s', (dataSource, signal) => {
+ const testId = `periscope-btn-download-${dataSource}`;
+
+ beforeEach(() => {
+ mockDownloadExportData.mockReset().mockResolvedValue(undefined);
+ (message.success as jest.Mock).mockReset();
+ (message.error as jest.Mock).mockReset();
+ mockUseQueryBuilder.mockReturnValue({
+ stagedQuery: createMockStagedQuery(dataSource),
+ });
+ });
+
+ it('renders download button', () => {
+ renderWithStore(dataSource);
+ const button = screen.getByTestId(testId);
+ expect(button).toBeInTheDocument();
+ expect(button).toHaveClass('periscope-btn', 'ghost');
+ });
+
+ it('shows popover with export options when download button is clicked', () => {
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+ expect(screen.getByText('FORMAT')).toBeInTheDocument();
+ expect(screen.getByText('Number of Rows')).toBeInTheDocument();
+ expect(screen.getByText('Columns')).toBeInTheDocument();
+ });
+
+ it('allows changing export format', () => {
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+
+ const csvRadio = screen.getByRole('radio', { name: 'csv' });
+ const jsonlRadio = screen.getByRole('radio', { name: 'jsonl' });
+
+ expect(csvRadio).toBeChecked();
+ fireEvent.click(jsonlRadio);
+ expect(jsonlRadio).toBeChecked();
+ expect(csvRadio).not.toBeChecked();
+ });
+
+ it('allows changing row limit', () => {
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+
+ const tenKRadio = screen.getByRole('radio', { name: '10k' });
+ const fiftyKRadio = screen.getByRole('radio', { name: '50k' });
+
+ expect(tenKRadio).toBeChecked();
+ fireEvent.click(fiftyKRadio);
+ expect(fiftyKRadio).toBeChecked();
+ expect(tenKRadio).not.toBeChecked();
+ });
+
+ it('allows changing columns scope', () => {
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+
+ const allColumnsRadio = screen.getByRole('radio', { name: 'All' });
+ const selectedColumnsRadio = screen.getByRole('radio', { name: 'Selected' });
+
+ expect(allColumnsRadio).toBeChecked();
+ fireEvent.click(selectedColumnsRadio);
+ expect(selectedColumnsRadio).toBeChecked();
+ expect(allColumnsRadio).not.toBeChecked();
+ });
+
+ it('calls downloadExportData with correct format and POST body', async () => {
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+ fireEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(mockDownloadExportData).toHaveBeenCalledTimes(1);
+ const callArgs = mockDownloadExportData.mock.calls[0][0];
+ expect(callArgs.format).toBe(DownloadFormats.CSV);
+ expect(callArgs.body).toBeDefined();
+ expect(callArgs.body.requestType).toBe('raw');
+ expect(callArgs.body.compositeQuery.queries).toHaveLength(1);
+
+ const query = callArgs.body.compositeQuery.queries[0];
+ expect(query.type).toBe('builder_query');
+ expect(query.spec.signal).toBe(signal);
+ expect(query.spec.limit).toBe(DownloadRowCounts.TEN_K);
+ });
+ });
+
+ it('clears groupBy and having in the export payload', async () => {
+ const mockQuery = createMockStagedQuery(dataSource);
+ mockQuery.builder.queryData[0].groupBy = [
+ { key: 'service', dataType: 'string' as any, type: '' },
+ ];
+ mockQuery.builder.queryData[0].having = {
+ expression: 'count() > 10',
+ } as any;
+
+ mockUseQueryBuilder.mockReturnValue({ stagedQuery: mockQuery });
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+ fireEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(mockDownloadExportData).toHaveBeenCalledTimes(1);
+ const callArgs = mockDownloadExportData.mock.calls[0][0];
+ const query = callArgs.body.compositeQuery.queries[0];
+ expect(query.spec.groupBy).toBeUndefined();
+ expect(query.spec.having).toEqual({ expression: '' });
+ });
+ });
+
+ it('keeps selectColumns when column scope is Selected', async () => {
+ const mockQuery = createMockStagedQuery(dataSource);
+ mockQuery.builder.queryData[0].selectColumns = [
+ { name: 'http.status', fieldDataType: 'int64', fieldContext: 'attribute' },
+ ] as any;
+
+ mockUseQueryBuilder.mockReturnValue({ stagedQuery: mockQuery });
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+ fireEvent.click(screen.getByRole('radio', { name: 'Selected' }));
+ fireEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(mockDownloadExportData).toHaveBeenCalledTimes(1);
+ const callArgs = mockDownloadExportData.mock.calls[0][0];
+ const query = callArgs.body.compositeQuery.queries[0];
+ expect(query.spec.selectFields).toEqual([
+ expect.objectContaining({
+ name: 'http.status',
+ fieldDataType: 'int64',
+ }),
+ ]);
+ });
+ });
+
+ it('sends no selectFields when column scope is All', async () => {
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+ fireEvent.click(screen.getByRole('radio', { name: 'All' }));
+ fireEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(mockDownloadExportData).toHaveBeenCalledTimes(1);
+ const callArgs = mockDownloadExportData.mock.calls[0][0];
+ const query = callArgs.body.compositeQuery.queries[0];
+ expect(query.spec.selectFields).toBeUndefined();
+ });
+ });
+
+ it('handles successful export with success message', async () => {
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+ fireEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(message.success).toHaveBeenCalledWith(
+ 'Export completed successfully',
+ );
+ });
+ });
+
+ it('handles export failure with error message', async () => {
+ mockDownloadExportData.mockRejectedValueOnce(new Error('Server error'));
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+ fireEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(message.error).toHaveBeenCalledWith(
+ `Failed to export ${dataSource}. Please try again.`,
+ );
+ });
+ });
+
+ it('handles UI state correctly during export process', async () => {
+ let resolveDownload: () => void;
+ mockDownloadExportData.mockImplementationOnce(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveDownload = resolve;
+ }),
+ );
+ renderWithStore(dataSource);
+
+ fireEvent.click(screen.getByTestId(testId));
+ expect(screen.getByRole('dialog')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByText('Export'));
+
+ expect(screen.getByTestId(testId)).toBeDisabled();
+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
+
+ resolveDownload!();
+
+ await waitFor(() => {
+ expect(screen.getByTestId(testId)).not.toBeDisabled();
+ });
+ });
+});
+
+describe('DownloadOptionsMenu for traces with queryTraceOperator', () => {
+ const dataSource = DataSource.TRACES;
+ const testId = `periscope-btn-download-${dataSource}`;
+
+ beforeEach(() => {
+ mockDownloadExportData.mockReset().mockResolvedValue(undefined);
+ (message.success as jest.Mock).mockReset();
+ });
+
+ it('applies limit and clears groupBy on queryTraceOperator entries', async () => {
+ const query = createMockStagedQuery(dataSource);
+ query.builder.queryTraceOperator = [
+ {
+ ...query.builder.queryData[0],
+ queryName: 'TraceOp1',
+ expression: 'TraceOp1',
+ groupBy: [{ key: 'service', dataType: 'string' as any, type: '' }],
+ },
+ ];
+
+ mockUseQueryBuilder.mockReturnValue({ stagedQuery: query });
+ renderWithStore(dataSource);
+ fireEvent.click(screen.getByTestId(testId));
+ fireEvent.click(screen.getByRole('radio', { name: '50k' }));
+ fireEvent.click(screen.getByText('Export'));
+
+ await waitFor(() => {
+ expect(mockDownloadExportData).toHaveBeenCalledTimes(1);
+ const callArgs = mockDownloadExportData.mock.calls[0][0];
+ const queries = callArgs.body.compositeQuery.queries;
+ const traceOpQuery = queries.find((q: any) => q.spec.name === 'TraceOp1');
+ if (traceOpQuery) {
+ expect(traceOpQuery.spec.limit).toBe(DownloadRowCounts.FIFTY_K);
+ expect(traceOpQuery.spec.groupBy).toBeUndefined();
+ }
+ });
+ });
+});
diff --git a/frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.tsx b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.tsx
similarity index 57%
rename from frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.tsx
rename to frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.tsx
index 5951fb6544..7b9d522719 100644
--- a/frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.tsx
+++ b/frontend/src/components/DownloadOptionsMenu/DownloadOptionsMenu.tsx
@@ -1,8 +1,8 @@
import { useCallback, useMemo, useState } from 'react';
-import { Button, message, Popover, Radio, Tooltip, Typography } from 'antd';
-import { downloadExportData } from 'api/v1/download/downloadExportData';
+import { Button, Popover, Radio, Tooltip, Typography } from 'antd';
+import { useExportRawData } from 'hooks/useDownloadOptionsMenu/useDownloadOptionsMenu';
import { Download, DownloadIcon, Loader2 } from 'lucide-react';
-import { TelemetryFieldKey } from 'types/api/v5/queryRange';
+import { DataSource } from 'types/common/queryBuilder';
import {
DownloadColumnsScopes,
@@ -10,75 +10,34 @@ import {
DownloadRowCounts,
} from './constants';
-import './LogsDownloadOptionsMenu.styles.scss';
+import './DownloadOptionsMenu.styles.scss';
-function convertTelemetryFieldKeyToText(key: TelemetryFieldKey): string {
- const prefix = key.fieldContext ? `${key.fieldContext}.` : '';
- const suffix = key.fieldDataType ? `:${key.fieldDataType}` : '';
- return `${prefix}${key.name}${suffix}`;
+interface DownloadOptionsMenuProps {
+ dataSource: DataSource;
}
-interface LogsDownloadOptionsMenuProps {
- startTime: number;
- endTime: number;
- filter: string;
- columns: TelemetryFieldKey[];
- orderBy: string;
-}
-
-export default function LogsDownloadOptionsMenu({
- startTime,
- endTime,
- filter,
- columns,
- orderBy,
-}: LogsDownloadOptionsMenuProps): JSX.Element {
+export default function DownloadOptionsMenu({
+ dataSource,
+}: DownloadOptionsMenuProps): JSX.Element {
const [exportFormat, setExportFormat] = useState<string>(DownloadFormats.CSV);
const [rowLimit, setRowLimit] = useState<number>(DownloadRowCounts.TEN_K);
const [columnsScope, setColumnsScope] = useState<string>(
DownloadColumnsScopes.ALL,
);
- const [isDownloading, setIsDownloading] = useState<boolean>(false);
const [isPopoverOpen, setIsPopoverOpen] = useState<boolean>(false);
- const handleExportRawData = useCallback(async (): Promise<void> => {
- setIsPopoverOpen(false);
- try {
- setIsDownloading(true);
- const downloadOptions = {
- source: 'logs',
- start: startTime,
- end: endTime,
- columns:
- columnsScope === DownloadColumnsScopes.SELECTED
- ? columns.map((col) => convertTelemetryFieldKeyToText(col))
- : [],
- filter,
- orderBy,
- format: exportFormat,
- limit: rowLimit,
- };
+ const { isDownloading, handleExportRawData } = useExportRawData({
+ dataSource,
+ });
- await downloadExportData(downloadOptions);
- message.success('Export completed successfully');
- } catch (error) {
- console.error('Error exporting logs:', error);
- message.error('Failed to export logs. Please try again.');
- } finally {
- setIsDownloading(false);
- }
- }, [
- startTime,
- endTime,
- columnsScope,
- columns,
- filter,
- orderBy,
- exportFormat,
- rowLimit,
- setIsDownloading,
- setIsPopoverOpen,
- ]);
+ const handleExport = useCallback(async (): Promise<void> => {
+ setIsPopoverOpen(false);
+ await handleExportRawData({
+ format: exportFormat,
+ rowLimit,
+ clearSelectColumns: columnsScope === DownloadColumnsScopes.ALL,
+ });
+ }, [exportFormat, rowLimit, columnsScope, handleExportRawData]);
const popoverContent = useMemo(
() => (
@@ -129,7 +88,7 @@ export default function LogsDownloadOptionsMenu({
<Button
type="primary"
icon={<Download size={16} />}
- onClick={handleExportRawData}
+ onClick={handleExport}
className="export-button"
disabled={isDownloading}
loading={isDownloading}
@@ -138,7 +97,7 @@ export default function LogsDownloadOptionsMenu({
</Button>
</div>
),
- [exportFormat, rowLimit, columnsScope, isDownloading, handleExportRawData],
+ [exportFormat, rowLimit, columnsScope, isDownloading, handleExport],
);
return (
@@ -149,19 +108,19 @@ export default function LogsDownloadOptionsMenu({
arrow={false}
open={isPopoverOpen}
onOpenChange={setIsPopoverOpen}
- rootClassName="logs-download-popover"
+ rootClassName="download-popover"
>
<Tooltip title="Download" placement="top">
<Button
className="periscope-btn ghost"
icon={
isDownloading ? (
- <Loader2 size={18} className="animate-spin" />
+ <Loader2 size={14} className="animate-spin" />
) : (
- <DownloadIcon size={15} />
+ <DownloadIcon size={14} />
)
}
- data-testid="periscope-btn-download-options"
+ data-testid={`periscope-btn-download-${dataSource}`}
disabled={isDownloading}
/>
</Tooltip>
diff --git a/frontend/src/components/LogsDownloadOptionsMenu/constants.ts b/frontend/src/components/DownloadOptionsMenu/constants.ts
similarity index 100%
rename from frontend/src/components/LogsDownloadOptionsMenu/constants.ts
rename to frontend/src/components/DownloadOptionsMenu/constants.ts
diff --git a/frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.test.tsx b/frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.test.tsx
deleted file mode 100644
index a1bccd5be7..0000000000
--- a/frontend/src/components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu.test.tsx
+++ /dev/null
@@ -1,341 +0,0 @@
-import { fireEvent, render, screen, waitFor } from '@testing-library/react';
-import { message } from 'antd';
-import { ENVIRONMENT } from 'constants/env';
-import { server } from 'mocks-server/server';
-import { rest } from 'msw';
-import { TelemetryFieldKey } from 'types/api/v5/queryRange';
-
-import '@testing-library/jest-dom';
-
-import { DownloadFormats, DownloadRowCounts } from './constants';
-import LogsDownloadOptionsMenu from './LogsDownloadOptionsMenu';
-
-// Mock antd message
-jest.mock('antd', () => {
- const actual = jest.requireActual('antd');
- return {
- ...actual,
- message: {
- success: jest.fn(),
- error: jest.fn(),
- },
- };
-});
-
-const TEST_IDS = {
- DOWNLOAD_BUTTON: 'periscope-btn-download-options',
-} as const;
-
-interface TestProps {
- startTime: number;
- endTime: number;
- filter: string;
- columns: TelemetryFieldKey[];
- orderBy: string;
-}
-
-const createTestProps = (): TestProps => ({
- startTime: 1631234567890,
- endTime: 1631234567999,
- filter: 'status = 200',
- columns: [
- {
- name: 'http.status',
- fieldContext: 'attribute',
- fieldDataType: 'int64',
- } as TelemetryFieldKey,
- ],
- orderBy: 'timestamp:desc',
-});
-
-const testRenderContent = (props: TestProps): void => {
- render(
- <LogsDownloadOptionsMenu
- startTime={props.startTime}
- endTime={props.endTime}
- filter={props.filter}
- columns={props.columns}
- orderBy={props.orderBy}
- />,
- );
-};
-
-const testSuccessResponse = (res: any, ctx: any): any =>
- res(
- ctx.status(200),
- ctx.set('Content-Type', 'application/octet-stream'),
- ctx.set('Content-Disposition', 'attachment; filename="export.csv"'),
- ctx.body('id,value\n1,2\n'),
- );
-
-describe('LogsDownloadOptionsMenu', () => {
- const BASE_URL = ENVIRONMENT.baseURL;
- const EXPORT_URL = `${BASE_URL}/api/v1/export_raw_data`;
- let requestSpy: jest.Mock<any, any>;
- const setupDefaultServer = (): void => {
- server.use(
- rest.get(EXPORT_URL, (req, res, ctx) => {
- const params = req.url.searchParams;
- const payload = {
- start: Number(params.get('start')),
- end: Number(params.get('end')),
- filter: params.get('filter'),
- columns: params.getAll('columns'),
- order_by: params.get('order_by'),
- limit: Number(params.get('limit')),
- format: params.get('format'),
- };
- requestSpy(payload);
- return testSuccessResponse(res, ctx);
- }),
- );
- };
-
- // Mock URL.createObjectURL used by download logic
- const originalCreateObjectURL = URL.createObjectURL;
- const originalRevokeObjectURL = URL.revokeObjectURL;
-
- beforeEach(() => {
- requestSpy = jest.fn();
- setupDefaultServer();
- (message.success as jest.Mock).mockReset();
- (message.error as jest.Mock).mockReset();
- // jsdom doesn't implement it by default
- ((URL as unknown) as {
- createObjectURL: (b: Blob) => string;
- }).createObjectURL = jest.fn(() => 'blob:mock');
- ((URL as unknown) as {
- revokeObjectURL: (u: string) => void;
- }).revokeObjectURL = jest.fn();
- });
-
- beforeAll(() => {
- server.listen();
- });
-
- afterEach(() => {
- server.resetHandlers();
- });
-
- afterAll(() => {
- server.close();
- // restore
- URL.createObjectURL = originalCreateObjectURL;
- URL.revokeObjectURL = originalRevokeObjectURL;
- });
-
- it('renders download button', () => {
- const props = createTestProps();
- testRenderContent(props);
-
- const button = screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON);
- expect(button).toBeInTheDocument();
- expect(button).toHaveClass('periscope-btn', 'ghost');
- });
-
- it('shows popover with export options when download button is clicked', () => {
- const props = createTestProps();
- render(
- <LogsDownloadOptionsMenu
- startTime={props.startTime}
- endTime={props.endTime}
- filter={props.filter}
- columns={props.columns}
- orderBy={props.orderBy}
- />,
- );
-
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
-
- expect(screen.getByRole('dialog')).toBeInTheDocument();
- expect(screen.getByText('FORMAT')).toBeInTheDocument();
- expect(screen.getByText('Number of Rows')).toBeInTheDocument();
- expect(screen.getByText('Columns')).toBeInTheDocument();
- });
-
- it('allows changing export format', () => {
- const props = createTestProps();
- testRenderContent(props);
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
-
- const csvRadio = screen.getByRole('radio', { name: 'csv' });
- const jsonlRadio = screen.getByRole('radio', { name: 'jsonl' });
-
- expect(csvRadio).toBeChecked();
- fireEvent.click(jsonlRadio);
- expect(jsonlRadio).toBeChecked();
- expect(csvRadio).not.toBeChecked();
- });
-
- it('allows changing row limit', () => {
- const props = createTestProps();
- testRenderContent(props);
-
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
-
- const tenKRadio = screen.getByRole('radio', { name: '10k' });
- const fiftyKRadio = screen.getByRole('radio', { name: '50k' });
-
- expect(tenKRadio).toBeChecked();
- fireEvent.click(fiftyKRadio);
- expect(fiftyKRadio).toBeChecked();
- expect(tenKRadio).not.toBeChecked();
- });
-
- it('allows changing columns scope', () => {
- const props = createTestProps();
- testRenderContent(props);
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
-
- const allColumnsRadio = screen.getByRole('radio', { name: 'All' });
- const selectedColumnsRadio = screen.getByRole('radio', { name: 'Selected' });
-
- expect(allColumnsRadio).toBeChecked();
- fireEvent.click(selectedColumnsRadio);
- expect(selectedColumnsRadio).toBeChecked();
- expect(allColumnsRadio).not.toBeChecked();
- });
-
- it('calls downloadExportData with correct parameters when export button is clicked (Selected columns)', async () => {
- const props = createTestProps();
- testRenderContent(props);
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
- fireEvent.click(screen.getByRole('radio', { name: 'Selected' }));
- fireEvent.click(screen.getByText('Export'));
-
- await waitFor(() => {
- expect(requestSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- start: props.startTime,
- end: props.endTime,
- columns: ['attribute.http.status:int64'],
- filter: props.filter,
- order_by: props.orderBy,
- format: DownloadFormats.CSV,
- limit: DownloadRowCounts.TEN_K,
- }),
- );
- });
- });
-
- it('calls downloadExportData with correct parameters when export button is clicked', async () => {
- const props = createTestProps();
- testRenderContent(props);
-
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
- fireEvent.click(screen.getByRole('radio', { name: 'All' }));
- fireEvent.click(screen.getByText('Export'));
-
- await waitFor(() => {
- expect(requestSpy).toHaveBeenCalledWith(
- expect.objectContaining({
- start: props.startTime,
- end: props.endTime,
- columns: [],
- filter: props.filter,
- order_by: props.orderBy,
- format: DownloadFormats.CSV,
- limit: DownloadRowCounts.TEN_K,
- }),
- );
- });
- });
-
- it('handles successful export with success message', async () => {
- const props = createTestProps();
- testRenderContent(props);
-
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
- fireEvent.click(screen.getByText('Export'));
-
- await waitFor(() => {
- expect(message.success).toHaveBeenCalledWith(
- 'Export completed successfully',
- );
- });
- });
-
- it('handles export failure with error message', async () => {
- // Override handler to return 500 for this test
- server.use(rest.get(EXPORT_URL, (_req, res, ctx) => res(ctx.status(500))));
- const props = createTestProps();
- testRenderContent(props);
-
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
- fireEvent.click(screen.getByText('Export'));
-
- await waitFor(() => {
- expect(message.error).toHaveBeenCalledWith(
- 'Failed to export logs. Please try again.',
- );
- });
- });
-
- it('handles UI state correctly during export process', async () => {
- server.use(
- rest.get(EXPORT_URL, (_req, res, ctx) => testSuccessResponse(res, ctx)),
- );
- const props = createTestProps();
- testRenderContent(props);
-
- // Open popover
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
- expect(screen.getByRole('dialog')).toBeInTheDocument();
-
- // Start export
- fireEvent.click(screen.getByText('Export'));
-
- // Check button is disabled during export
- expect(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON)).toBeDisabled();
-
- // Check popover is closed immediately after export starts
- expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
-
- // Wait for export to complete and verify button is enabled again
- await waitFor(() => {
- expect(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON)).not.toBeDisabled();
- });
- });
-
- it('uses filename from Content-Disposition and triggers download click', async () => {
- server.use(
- rest.get(EXPORT_URL, (_req, res, ctx) =>
- res(
- ctx.status(200),
- ctx.set('Content-Type', 'application/octet-stream'),
- ctx.set('Content-Disposition', 'attachment; filename="report.jsonl"'),
- ctx.body('row\n'),
- ),
- ),
- );
-
- const originalCreateElement = document.createElement.bind(document);
- const anchorEl = originalCreateElement('a') as HTMLAnchorElement;
- const setAttrSpy = jest.spyOn(anchorEl, 'setAttribute');
- const clickSpy = jest.spyOn(anchorEl, 'click');
- const removeSpy = jest.spyOn(anchorEl, 'remove');
- const createElSpy = jest
- .spyOn(document, 'createElement')
- .mockImplementation((tagName: any): any =>
- tagName === 'a' ? anchorEl : originalCreateElement(tagName),
- );
- const appendSpy = jest.spyOn(document.body, 'appendChild');
-
- const props = createTestProps();
- testRenderContent(props);
-
- fireEvent.click(screen.getByTestId(TEST_IDS.DOWNLOAD_BUTTON));
- fireEvent.click(screen.getByText('Export'));
-
- await waitFor(() => {
- expect(appendSpy).toHaveBeenCalledWith(anchorEl);
- expect(setAttrSpy).toHaveBeenCalledWith('download', 'report.jsonl');
- expect(clickSpy).toHaveBeenCalled();
- expect(removeSpy).toHaveBeenCalled();
- });
- expect(anchorEl.getAttribute('download')).toBe('report.jsonl');
-
- createElSpy.mockRestore();
- appendSpy.mockRestore();
- });
-});
diff --git a/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx b/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx
index 28a9b3c698..080f022260 100644
--- a/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx
+++ b/frontend/src/container/LogsExplorerViews/LogsActionsContainer.tsx
@@ -1,5 +1,5 @@
import { Switch, Typography } from 'antd';
-import LogsDownloadOptionsMenu from 'components/LogsDownloadOptionsMenu/LogsDownloadOptionsMenu';
+import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
import LogsFormatOptionsMenu from 'components/LogsFormatOptionsMenu/LogsFormatOptionsMenu';
import ListViewOrderBy from 'components/OrderBy/ListViewOrderBy';
import { LOCALSTORAGE } from 'constants/localStorage';
@@ -21,8 +21,6 @@ function LogsActionsContainer({
isLoading,
isError,
isSuccess,
- minTime,
- maxTime,
}: {
listQuery: any;
selectedPanelType: PANEL_TYPES;
@@ -34,8 +32,6 @@ function LogsActionsContainer({
isLoading: boolean;
isError: boolean;
isSuccess: boolean;
- minTime: number;
- maxTime: number;
}): JSX.Element {
const { options, config } = useOptionsMenu({
storageKey: LOCALSTORAGE.LOGS_LIST_OPTIONS,
@@ -96,13 +92,7 @@ function LogsActionsContainer({
/>
</div>
<div className="download-options-container">
- <LogsDownloadOptionsMenu
- startTime={minTime}
- endTime={maxTime}
- filter={listQuery?.filter?.expression || ''}
- columns={config.addColumn?.value || []}
- orderBy={orderBy}
- />
+ <DownloadOptionsMenu dataSource={DataSource.LOGS} />
</div>
<div className="format-options-container">
<LogsFormatOptionsMenu
diff --git a/frontend/src/container/LogsExplorerViews/index.tsx b/frontend/src/container/LogsExplorerViews/index.tsx
index 4e30a21fb6..3ab538b74b 100644
--- a/frontend/src/container/LogsExplorerViews/index.tsx
+++ b/frontend/src/container/LogsExplorerViews/index.tsx
@@ -444,8 +444,6 @@ function LogsExplorerViewsContainer({
isLoading={isLoading}
isError={isError}
isSuccess={isSuccess}
- minTime={minTime}
- maxTime={maxTime}
/>
)}
diff --git a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
index 31b1468abc..637c0b9a3f 100644
--- a/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
+++ b/frontend/src/container/LogsExplorerViews/tests/LogsExplorerViews.test.tsx
@@ -168,7 +168,7 @@ describe('LogsExplorerViews -', () => {
lodsQueryServerRequest();
const { queryByTestId } = renderer();
- const periscopeDownloadButtonTestId = 'periscope-btn-download-options';
+ const periscopeDownloadButtonTestId = 'periscope-btn-download-logs';
const periscopeFormatButtonTestId = 'periscope-btn-format-options';
// Test that the periscope button is present
diff --git a/frontend/src/container/TracesExplorer/ListView/ListView.styles.scss b/frontend/src/container/TracesExplorer/ListView/ListView.styles.scss
index 26549c6a22..3f46699604 100644
--- a/frontend/src/container/TracesExplorer/ListView/ListView.styles.scss
+++ b/frontend/src/container/TracesExplorer/ListView/ListView.styles.scss
@@ -1,6 +1,7 @@
.trace-explorer-controls {
display: flex;
justify-content: flex-end;
+ align-items: center;
gap: 8px;
.order-by-container {
diff --git a/frontend/src/container/TracesExplorer/ListView/index.tsx b/frontend/src/container/TracesExplorer/ListView/index.tsx
index e44574665b..c472c202e2 100644
--- a/frontend/src/container/TracesExplorer/ListView/index.tsx
+++ b/frontend/src/container/TracesExplorer/ListView/index.tsx
@@ -11,6 +11,7 @@ import {
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import logEvent from 'api/common/logEvent';
+import DownloadOptionsMenu from 'components/DownloadOptionsMenu/DownloadOptionsMenu';
import ErrorInPlace from 'components/ErrorInPlace/ErrorInPlace';
import ListViewOrderBy from 'components/OrderBy/ListViewOrderBy';
import { ResizeTable } from 'components/ResizeTable';
@@ -238,6 +239,8 @@ function ListView({
/>
</div>
+ <DownloadOptionsMenu dataSource={DataSource.TRACES} />
+
<TraceExplorerControls
isLoading={isFetching}
totalCount={totalCount}
diff --git a/frontend/src/hooks/useDownloadOptionsMenu/useDownloadOptionsMenu.ts b/frontend/src/hooks/useDownloadOptionsMenu/useDownloadOptionsMenu.ts
new file mode 100644
index 0000000000..3aef11a2bf
--- /dev/null
+++ b/frontend/src/hooks/useDownloadOptionsMenu/useDownloadOptionsMenu.ts
@@ -0,0 +1,95 @@
+import { useCallback, useState } from 'react';
+// eslint-disable-next-line no-restricted-imports
+import { useSelector } from 'react-redux';
+import { message } from 'antd';
+import { downloadExportData } from 'api/v1/download/downloadExportData';
+import { prepareQueryRangePayloadV5 } from 'api/v5/v5';
+import { PANEL_TYPES } from 'constants/queryBuilder';
+import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
+import { AppState } from 'store/reducers';
+import { DataSource } from 'types/common/queryBuilder';
+import { GlobalReducer } from 'types/reducer/globalTime';
+
+interface ExportOptions {
+ format: string;
+ rowLimit: number;
+ clearSelectColumns: boolean;
+}
+
+interface UseExportRawDataProps {
+ dataSource: DataSource;
+}
+
+interface UseExportRawDataReturn {
+ isDownloading: boolean;
+ handleExportRawData: (options: ExportOptions) => Promise<void>;
+}
+
+export function useExportRawData({
+ dataSource,
+}: UseExportRawDataProps): UseExportRawDataReturn {
+ const [isDownloading, setIsDownloading] = useState<boolean>(false);
+
+ const { stagedQuery } = useQueryBuilder();
+
+ const { selectedTime: globalSelectedInterval } = useSelector<
+ AppState,
+ GlobalReducer
+ >((state) => state.globalTime);
+
+ const handleExportRawData = useCallback(
+ async ({
+ format,
+ rowLimit,
+ clearSelectColumns,
+ }: ExportOptions): Promise<void> => {
+ if (!stagedQuery) {
+ return;
+ }
+
+ try {
+ setIsDownloading(true);
+
+ const exportQuery = {
+ ...stagedQuery,
+ builder: {
+ ...stagedQuery.builder,
+ queryData: stagedQuery.builder.queryData.map((qd) => ({
+ ...qd,
+ groupBy: [],
+ having: { expression: '' },
+ limit: rowLimit,
+ ...(clearSelectColumns && { selectColumns: [] }),
+ })),
+ queryTraceOperator: (stagedQuery.builder.queryTraceOperator || []).map(
+ (traceOp) => ({
+ ...traceOp,
+ groupBy: [],
+ having: { expression: '' },
+ limit: rowLimit,
+ ...(clearSelectColumns && { selectColumns: [] }),
+ }),
+ ),
+ },
+ };
+
+ const { queryPayload } = prepareQueryRangePayloadV5({
+ query: exportQuery,
+ graphType: PANEL_TYPES.LIST,
+ selectedTime: 'GLOBAL_TIME',
+ globalSelectedInterval,
+ });
+
+ await downloadExportData({ format, body: queryPayload });
+ message.success('Export completed successfully');
+ } catch (error) {
+ message.error(`Failed to export ${dataSource}. Please try again.`);
+ } finally {
+ setIsDownloading(false);
+ }
+ },
+ [stagedQuery, globalSelectedInterval, dataSource],
+ );
+
+ return { isDownloading, handleExportRawData };
+}
diff --git a/frontend/src/types/api/exportRawData/getExportRawData.ts b/frontend/src/types/api/exportRawData/getExportRawData.ts
index 0548c6dcf5..e9c47cbac2 100644
--- a/frontend/src/types/api/exportRawData/getExportRawData.ts
+++ b/frontend/src/types/api/exportRawData/getExportRawData.ts
@@ -1,10 +1,6 @@
+import { QueryRangePayloadV5 } from 'types/api/v5/queryRange';
+
export interface ExportRawDataProps {
- source: string;
format: string;
- start: number;
- end: number;
- columns: string[];
- filter: string;
- orderBy: string;
- limit: number;
+ body: QueryRangePayloadV5;
}