Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/percent-encoded-chart-urls.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@hyperdx/app': patch
---

Percent-encode Chart Explorer and temporary dashboard URL state so shared links survive Slack, Teams, and terminals.
5 changes: 3 additions & 2 deletions packages/app/src/DBChartPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { useCallback, useMemo, useRef, useState } from 'react';
import dynamic from 'next/dynamic';
import Head from 'next/head';
import Link from 'next/link';
import { parseAsJson, parseAsString, useQueryState } from 'nuqs';
import { parseAsString, useQueryState } from 'nuqs';
import { useForm } from 'react-hook-form';
import { useHotkeys } from 'react-hotkeys-hook';
import { Badge, Separator } from '@clickhouse/click-ui';
Expand Down Expand Up @@ -44,6 +44,7 @@ import { useDefaultTimeRange, useNewTimeQuery } from '@/timeQuery';
import { useLocalStorage } from '@/utils';
import { buildInlineAlertPayload } from '@/utils/alerts';
import { getApiErrorMessage } from '@/utils/apiErrors';
import { parseAsJsonEncoded } from '@/utils/queryParsers';

import OnboardingModal from './components/OnboardingModal';

Expand Down Expand Up @@ -232,7 +233,7 @@ function DBChartExplorerPage() {

const [rawChartConfig, setChartConfig] = useQueryState(
'config',
parseAsJson<SavedChartConfig>().withDefault({
parseAsJsonEncoded<SavedChartConfig>().withDefault({
...DEFAULT_CHART_CONFIG,
source: sources?.[0]?.id ?? '',
connection: sources?.[0]?.connection,
Expand Down
4 changes: 3 additions & 1 deletion packages/app/src/__tests__/dashboard.remote.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,11 @@ jest.mock('@mantine/notifications', () => ({
notifications: { show: jest.fn() },
}));
jest.mock('nuqs', () => ({
parseAsJson: jest.fn(),
useQueryState: jest.fn(),
}));
jest.mock('@/utils/queryParsers', () => ({
parseAsJsonEncoded: jest.fn(),
}));

// Capture each mutation's `mutationFn` so the tests can invoke it directly
// without standing up a full React Query provider. Each `useMutation()`
Expand Down
4 changes: 3 additions & 1 deletion packages/app/src/__tests__/dashboard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ jest.mock('@mantine/notifications', () => ({
notifications: { show: jest.fn() },
}));
jest.mock('nuqs', () => ({
parseAsJson: jest.fn(),
useQueryState: jest.fn(),
}));
jest.mock('@/utils/queryParsers', () => ({
parseAsJsonEncoded: jest.fn(),
}));
jest.mock('@tanstack/react-query', () => ({
useQuery: jest.fn(),
useMutation: jest.fn(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ jest.mock('@mantine/notifications', () => ({
notifications: { show: jest.fn() },
}));
jest.mock('nuqs', () => ({
parseAsJson: () => ({}),
useQueryState: () => [localDashboardValue, setLocalDashboard],
}));
jest.mock('@/utils/queryParsers', () => ({
parseAsJsonEncoded: () => ({}),
}));
jest.mock('@tanstack/react-query', () => ({
useMutation: () => ({ mutate: jest.fn() }),
useQuery: () => ({ data: undefined, isFetching: false }),
Expand Down
5 changes: 3 additions & 2 deletions packages/app/src/dashboard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useCallback, useMemo, useState } from 'react';
import { parseAsJson, useQueryState } from 'nuqs';
import { useQueryState } from 'nuqs';
import {
DashboardContainer,
DashboardFilter,
Expand All @@ -17,6 +17,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';

import { hashCode } from '@/utils';

import { parseAsJsonEncoded } from './utils/queryParsers';
import api, {
hdxServer,
useCompleteOnboardingTask,
Expand Down Expand Up @@ -238,7 +239,7 @@ export function useDashboard({

const [localDashboard, setLocalDashboard] = useQueryState(
'dashboard',
parseAsJson<Dashboard>(),
parseAsJsonEncoded<Dashboard>(),
);

const updateDashboard = useUpdateDashboard();
Expand Down
33 changes: 33 additions & 0 deletions packages/app/src/utils/__tests__/queryParsers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,39 @@ describe('parseAsJsonEncoded', () => {
});
});

describe('chart config URL round-trip', () => {
// A synthetic raw-SQL chart config with the characters that break raw JSON
// links in chat clients and terminals.
const config = {
name: 'Synthetic chart',
configType: 'sql' as const,
connection: 'synthetic-connection',
source: 'synthetic-source',
sqlTemplate: `SELECT
'frontend [web]' AS "service + tier",
'100%' AS "percent %"
FROM synthetic_logs`,
};
const parser = parseAsJsonEncoded<typeof config>();
const serialized = parser.serialize(config);

it('round-trips a multi-line SQL config', () => {
expect(serialized).toBe(encodeURIComponent(JSON.stringify(config)));
expect(parser.parse(serialized)).toEqual(config);
});

it('contains no raw JSON punctuation, spaces, or newlines', () => {
expect(serialized).not.toMatch(/[{}[\]"+ \\\s]/);
// Literal '%' and JSON's escaped newline are both percent-encoded.
expect(serialized).toContain('%25');
expect(serialized).toContain('%5Cn');
});

it('still parses the raw JSON written by the old nuqs parser', () => {
expect(parser.parse(JSON.stringify(config))).toEqual(config);
});
});

describe('parseAsSortingStateString', () => {
describe('parse', () => {
it('parses a single column with DESC', () => {
Expand Down
88 changes: 70 additions & 18 deletions packages/app/tests/e2e/features/source-name-deeplink.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,32 @@ function sourcePicker(page: Page, index = 0) {
return page.getByPlaceholder('Data Source').nth(index);
}

/** Minimal builder config that can actually query the seeded log source. */
function chartConfig(source: string, connection: string) {
return {
name: '',
select: [
{
aggFn: 'count',
aggCondition: '',
aggConditionLanguage: 'lucene',
valueExpression: '',
},
],
where: '',
whereLanguage: 'lucene',
displayType: 'line',
granularity: 'auto',
alignDateRangeToGranularity: true,
source,
connection,
};
}

function chartConfigParam(page: Page): string {
return new URL(page.url()).searchParams.get('config') ?? '';
}

async function expectParamCanonicalized(
page: Page,
param: string,
Expand Down Expand Up @@ -461,24 +487,7 @@ test.describe('Source name deeplinks', { tag: ['@full-stack'] }, () => {

// A minimal builder config with the source given by *name*. `connection`
// comes from the API so the chart can actually query — /chart autoRuns.
const config = {
name: '',
select: [
{
aggFn: 'count',
aggCondition: '',
aggConditionLanguage: 'lucene',
valueExpression: '',
},
],
where: '',
whereLanguage: 'lucene',
displayType: 'line',
granularity: 'auto',
alignDateRangeToGranularity: true,
source: DEFAULT_LOGS_SOURCE_NAME,
connection: logsSource.connection,
};
const config = chartConfig(DEFAULT_LOGS_SOURCE_NAME, logsSource.connection);

await page.goto(
`/chart?config=${encodeURIComponent(JSON.stringify(config))}`,
Expand All @@ -499,6 +508,49 @@ test.describe('Source name deeplinks', { tag: ['@full-stack'] }, () => {
).toBeVisible({ timeout: 20000 });
});

test('opens a legacy raw-JSON chart link and rewrites it percent-encoded', async ({
page,
}) => {
const logSources = await getSources(page, 'log');
const logsSource = logSources.find(
(s: { name: string }) => s.name === DEFAULT_LOGS_SOURCE_NAME,
);
expect(logsSource).toBeDefined();

const config = {
...chartConfig(DEFAULT_LOGS_SOURCE_NAME, logsSource.connection),
name: 'Synthetic chart',
};
// The old nuqs serializer wrote literal JSON and used '+' for spaces,
// which chat clients and terminals treat as the end of the link.
const legacyParam = JSON.stringify(config).replace(/ /g, '+');
await page.goto(`/chart?config=${legacyParam}`);

await expect(page.getByTestId('chart-explorer-page')).toBeVisible({
timeout: 15000,
});
const chartForm = page.getByTestId('chart-explorer-form');
await expect(chartForm.getByTestId('source-selector')).toHaveValue(
DEFAULT_LOGS_SOURCE_NAME,
{ timeout: 15000 },
);
await expect(
page.locator('.recharts-responsive-container').first(),
).toBeVisible({ timeout: 20000 });

// The page writes config back on load. The new serializer must leave only
// %XX sequences in the URL — no raw JSON punctuation, spaces, or '+'s.
await expect
.poll(() => chartConfigParam(page), { timeout: 15000 })
.toMatch(/^%7B/);
const encodedConfig = chartConfigParam(page);
expect(encodedConfig).not.toMatch(/[{}[\]"+ \\\s]/);
const parsed: unknown = JSON.parse(decodeURIComponent(encodedConfig));
expect(parsed).toEqual(
expect.objectContaining({ source: expect.any(String) }),
);
});

test('warns and keeps the link when the session source does not exist', async ({
page,
}) => {
Expand Down
Loading