Compare commits

..

5 Commits

Author SHA1 Message Date
Gaurav Tewari
a15ac6bfbd chore: css conventios 2026-07-28 20:28:22 +05:30
Gaurav Tewari
529e4b9d0f feat: update styles 2026-07-28 19:51:39 +05:30
Gaurav Tewari
4b597a3d8e chore: revert bg color change 2026-07-28 12:53:14 +05:30
Gaurav Tewari
3909cec9d6 feat: add warning popover 2026-07-28 12:43:36 +05:30
Gaurav Tewari
5ab9802e00 fix: update css styles 2026-07-28 00:21:26 +05:30
101 changed files with 726 additions and 2362 deletions

View File

@@ -7238,10 +7238,6 @@ components:
$ref: '#/components/schemas/RuletypesAlertState'
overallStateChanged:
type: boolean
relatedLogsLink:
type: string
relatedTracesLink:
type: string
ruleId:
type: string
ruleName:

View File

@@ -8320,14 +8320,6 @@ export interface RulestatehistorytypesGettableRuleStateHistoryDTO {
* @type boolean
*/
overallStateChanged: boolean;
/**
* @type string
*/
relatedLogsLink?: string;
/**
* @type string
*/
relatedTracesLink?: string;
/**
* @type string
*/

View File

@@ -18,10 +18,7 @@ import {
import { EQueryType } from 'types/common/dashboard';
import { DataSource, ReduceOperators } from 'types/common/queryBuilder';
import {
convertBuilderQueriesToV5,
prepareQueryRangePayloadV5,
} from './prepareQueryRangePayloadV5';
import { prepareQueryRangePayloadV5 } from './prepareQueryRangePayloadV5';
jest.mock('lib/getStartEndRangeTime', () => ({
__esModule: true,
@@ -902,36 +899,3 @@ describe('prepareQueryRangePayloadV5', () => {
expect(logSpec.filter).toStrictEqual({ expression: '' });
});
});
describe('convertBuilderQueriesToV5 having normalization', () => {
const buildSpec = (having: unknown): MetricBuilderQuery => {
const [envelope] = convertBuilderQueriesToV5(
{
A: {
dataSource: DataSource.METRICS,
queryName: 'A',
aggregations: [{ metricName: 'm', spaceAggregation: 'p99' }],
having,
} as unknown as IBuilderQuery,
},
'time_series',
PANEL_TYPES.TIME_SERIES,
);
return envelope.spec as MetricBuilderQuery;
};
it.each([
['a legacy V4 array', []],
['a blank empty-object having', { expression: '' }],
['a whitespace-only having', { expression: ' ' }],
['a nullish having', undefined],
])('drops %s (serializes to undefined)', (_label, having) => {
expect(buildSpec(having).having).toBeUndefined();
});
it('preserves a real having expression', () => {
expect(buildSpec({ expression: 'count() > 5' }).having).toStrictEqual({
expression: 'count() > 5',
});
});
});

View File

@@ -134,21 +134,6 @@ function getFilter(queryData: IBuilderQuery): Filter {
};
}
/**
* Normalizes a builder query's `having` to the V5 shape, treating "no having filter" as absent.
* V4 stored it as an array; V5 expects `{ expression }`. An array (legacy), a nullish value, or a
* blank expression — the query builder seeds `{ expression: '' }` for an empty having — all mean
* "no having" and must serialize to `undefined`. Emitting an empty `{ expression: '' }` sends a
* no-op filter and, because a saved panel never carries one, reads an untouched panel as dirty.
*/
function normalizeHaving(having: unknown): Having | undefined {
if (having == null || Array.isArray(having)) {
return undefined;
}
const { expression } = having as Having;
return expression?.trim() ? (having as Having) : undefined;
}
function createBaseSpec(
queryData: IBuilderQuery,
requestType: RequestType,
@@ -196,7 +181,12 @@ function createBaseSpec(
)
: undefined,
legend: isEmpty(queryData.legend) ? undefined : queryData.legend,
having: normalizeHaving(queryData.having),
// V4 uses having as array, V5 uses having as object with expression field
// If having is an array (V4 format), treat it as undefined for V5
having:
isEmpty(queryData.having) || Array.isArray(queryData.having)
? undefined
: (queryData?.having as Having),
functions: isEmpty(queryData.functions)
? undefined
: queryData.functions.map((func: QueryFunction): QueryFunction => {
@@ -424,7 +414,10 @@ function createTraceOperatorBaseSpec(
)
: undefined,
legend: isEmpty(legend) ? undefined : legend,
having: normalizeHaving(having),
// V4 uses having as array, V5 uses having as object with expression field
// If having is an array (V4 format), treat it as undefined for V5
having:
isEmpty(having) || Array.isArray(having) ? undefined : (having as Having),
selectFields: isEmpty(nonEmptySelectColumns)
? undefined
: nonEmptySelectColumns?.map(

View File

@@ -213,9 +213,7 @@ describe.each([
const callArgs = mockDownloadExportData.mock.calls[0][0];
const query = callArgs.body.compositeQuery.queries[0];
expect(query.spec.groupBy).toBeUndefined();
// An empty having ({ expression: '' }) is a no-op filter and serializes to
// undefined — same as the cleared groupBy above.
expect(query.spec.having).toBeUndefined();
expect(query.spec.having).toStrictEqual({ expression: '' });
});
});

View File

@@ -20,7 +20,6 @@ import {
import { Color } from '@signozhq/design-tokens';
import { Button, Select } from 'antd';
import { Checkbox } from '@signozhq/ui/checkbox';
import { TooltipProvider, TooltipSimple } from '@signozhq/ui/tooltip';
import { Typography } from '@signozhq/ui/typography';
import cx from 'classnames';
import TextToolTip from 'components/TextToolTip/TextToolTip';
@@ -34,7 +33,6 @@ import { CustomMultiSelectProps, CustomTagProps, OptionData } from './types';
import {
ALL_SELECTED_VALUE,
filterOptionsBySearch,
findOptionLabelText,
handleScrollToBottom,
prioritizeOrAddOptionForMultiSelect,
SPACEKEY,
@@ -1939,7 +1937,7 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
}
};
const tag = (
return (
<div
className={cx('ant-select-selection-item', {
'ant-select-selection-item-active': isActive,
@@ -1969,32 +1967,13 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
)}
</div>
);
// `label` arrives already cut to maxTagTextLength, so the reveal reads the
// option's own text (falling back to the raw value for freeform tags).
return (
<TooltipSimple
side="top"
delayDuration={300}
title={findOptionLabelText(options, value)}
>
{tag}
</TooltipSimple>
);
}
// Fallback for safety, should not be reached
return <div />;
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[
isAllSelected,
activeChipIndex,
selectedChips,
selectedValues,
maxTagCount,
options,
],
[isAllSelected, activeChipIndex, selectedChips, selectedValues, maxTagCount],
);
// Simple onClear handler to prevent clearing ALL
@@ -2013,58 +1992,51 @@ const CustomMultiSelect: React.FC<CustomMultiSelectProps> = ({
// ===== Component Rendering =====
return (
// Self-provided so the per-tag tooltips work wherever this select is rendered,
// without every consumer having to sit under an app-level provider.
<TooltipProvider>
<div
className={cx('custom-multiselect-wrapper', {
'all-selected': allOptionShown || isAllSelected,
<div
className={cx('custom-multiselect-wrapper', {
'all-selected': allOptionShown || isAllSelected,
})}
>
{(allOptionShown || isAllSelected) && !searchText && (
<div className="all-text">ALL</div>
)}
<Select
ref={selectRef}
className={cx('custom-multiselect', className, {
'has-selection': selectedChips.length > 0 && !isAllSelected,
'is-all-selected': isAllSelected,
})}
>
{(allOptionShown || isAllSelected) && !searchText && (
<div className="all-text">ALL</div>
)}
<Select
ref={selectRef}
className={cx('custom-multiselect', className, {
'has-selection': selectedChips.length > 0 && !isAllSelected,
'is-all-selected': isAllSelected,
})}
placeholder={placeholder}
mode="multiple"
showSearch
filterOption={false}
onSearch={handleSearch}
value={displayValue}
onChange={(newValue): void => {
handleInternalChange(newValue, false);
}}
onClear={onClearHandler}
onDropdownVisibleChange={handleDropdownVisibleChange}
open={isOpen}
defaultActiveFirstOption={defaultActiveFirstOption}
popupMatchSelectWidth={dropdownMatchSelectWidth}
allowClear={allowClear}
getPopupContainer={getPopupContainer ?? popupContainer}
suffixIcon={<ChevronDown style={{ cursor: 'default' }} size="md" />}
dropdownRender={customDropdownRender}
menuItemSelectedIcon={null}
popupClassName={cx(
'custom-multiselect-dropdown-container',
popupClassName,
)}
notFoundContent={<div className="empty-message">{noDataMessage}</div>}
onKeyDown={handleKeyDown}
tagRender={tagRender as any}
placement={placement}
listHeight={300}
searchValue={searchText}
maxTagTextLength={maxTagTextLength}
maxTagCount={isAllSelected ? undefined : maxTagCount}
{...rest}
/>
</div>
</TooltipProvider>
placeholder={placeholder}
mode="multiple"
showSearch
filterOption={false}
onSearch={handleSearch}
value={displayValue}
onChange={(newValue): void => {
handleInternalChange(newValue, false);
}}
onClear={onClearHandler}
onDropdownVisibleChange={handleDropdownVisibleChange}
open={isOpen}
defaultActiveFirstOption={defaultActiveFirstOption}
popupMatchSelectWidth={dropdownMatchSelectWidth}
allowClear={allowClear}
getPopupContainer={getPopupContainer ?? popupContainer}
suffixIcon={<ChevronDown style={{ cursor: 'default' }} size="md" />}
dropdownRender={customDropdownRender}
menuItemSelectedIcon={null}
popupClassName={cx('custom-multiselect-dropdown-container', popupClassName)}
notFoundContent={<div className="empty-message">{noDataMessage}</div>}
onKeyDown={handleKeyDown}
tagRender={tagRender as any}
placement={placement}
listHeight={300}
searchValue={searchText}
maxTagTextLength={maxTagTextLength}
maxTagCount={isAllSelected ? undefined : maxTagCount}
{...rest}
/>
</div>
);
};

View File

@@ -1,66 +0,0 @@
import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import CustomMultiSelect from '../CustomMultiSelect';
const OPTIONS = [
{ label: 'checkout-service-prod', value: 'checkout-service-prod' },
{ label: 'payments-service-prod', value: 'payments-service-prod' },
{ label: 'cart-service-prod', value: 'cart-service-prod' },
];
const SELECTED = ['checkout-service-prod', 'payments-service-prod'];
function renderSelect(): void {
render(
<TooltipProvider>
<CustomMultiSelect
options={OPTIONS}
value={SELECTED}
maxTagCount={1}
maxTagTextLength={10}
maxTagPlaceholder={(omitted): string => `+${omitted.length}`}
/>
</TooltipProvider>,
);
}
/** Hovers an element and lets the tooltip's open delay elapse. */
async function hover(element: HTMLElement): Promise<void> {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
await user.hover(element);
act(() => {
jest.advanceTimersByTime(500);
});
}
describe('CustomMultiSelect tag tooltip', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it("reveals a tag's untruncated value on hover", async () => {
renderSelect();
await hover(screen.getByText('checkout-s...'));
expect(screen.getByRole('tooltip')).toHaveTextContent(
'checkout-service-prod',
);
});
// The `+N` placeholder stays the caller's to render — several callers already wrap
// it in a tooltip of their own, and a second one would stack on top.
it('leaves the +N overflow placeholder untouched', async () => {
renderSelect();
await hover(screen.getByText('+1'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
});
});

View File

@@ -109,21 +109,6 @@ export const prioritizeOrAddOptionForMultiSelect = (
return [...flatOutSelectedOptions, ...filteredOptions];
};
export const findOptionLabelText = (
options: OptionData[],
value: string,
): string => {
const match = options
.flatMap((option) =>
'options' in option && Array.isArray(option.options)
? option.options
: [option],
)
.find((option) => option.value === value);
return typeof match?.label === 'string' ? match.label : value;
};
/**
* Filters options based on search text
*/

View File

@@ -1,20 +0,0 @@
@use '../../styles/scrollbar' as *;
// Padding for the tooltip body that hosts a scroll area: the right side is given
// up so the scrollbar can sit flush against the tooltip's edge instead of floating
// inset from it. `.scrollArea` puts that spacing back between the text and the bar.
.tooltipContent {
--tooltip-padding: var(--spacing-2) 0 var(--spacing-2) var(--spacing-4);
}
// How tall a hover reveal grows before its content starts scrolling.
.scrollArea {
max-height: 480px;
overflow-y: auto;
// Keep the page behind the tooltip still once the list hits its end.
overscroll-behavior: contain;
// Gap between the content and the scrollbar (or the tooltip edge when short).
padding-right: var(--spacing-4);
@include custom-scrollbar;
}

View File

@@ -1,25 +0,0 @@
import type { ReactNode } from 'react';
import styles from './TooltipScrollArea.module.scss';
interface TooltipScrollAreaProps {
children: ReactNode;
}
/**
* Pass as the hosting tooltip's content class (`tooltipContentProps`) so its
* padding makes room for the scroll area's own edge handling.
*/
export const TOOLTIP_SCROLL_CONTENT_CLASS = styles.tooltipContent;
/**
* Scroll container for hover reveals that list an unbounded number of items (tag
* chips, variable values): caps the tooltip's height and scrolls past it. Plain CSS
* overflow with a pinned-visible thin scrollbar — a tooltip is transient, so an
* auto-hiding scrollbar would leave no hint that there is more below.
*/
function TooltipScrollArea({ children }: TooltipScrollAreaProps): JSX.Element {
return <div className={styles.scrollArea}>{children}</div>;
}
export default TooltipScrollArea;

View File

@@ -1,6 +1,11 @@
.warning-popover-overlay {
--antd-arrow-background-color: var(--l2-background);
}
.warning-content {
display: flex;
flex-direction: column;
background-color: var(--l2-background);
// === SECTION: Summary (Top)
&__summary-section {
@@ -10,16 +15,25 @@
&__summary {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: var(--spacing-8);
padding: 16px;
}
&__summary-left {
display: flex;
align-items: baseline;
align-items: flex-start;
gap: 8px;
}
&__icon-wrapper {
display: flex;
align-items: center;
flex-shrink: 0;
height: var(--spacing-12);
}
&__summary-text {
display: flex;
flex-direction: column;

View File

@@ -2,6 +2,7 @@ import { ReactNode, useMemo } from 'react';
import { Color } from '@signozhq/design-tokens';
import { Button, Popover, PopoverProps } from 'antd';
import ErrorIcon from 'assets/Error';
import cx from 'classnames';
import OverlayScrollbar from 'components/OverlayScrollbar/OverlayScrollbar';
import { BookOpenText, ChevronsDown, TriangleAlert } from '@signozhq/icons';
import KeyValueLabel from 'periscope/components/KeyValueLabel';
@@ -30,16 +31,18 @@ export function WarningContent({ warning }: WarningContentProps): JSX.Element {
{/* Summary Header */}
<section className="warning-content__summary-section">
<header className="warning-content__summary">
<div className="warning-content__summary-left">
<div className="warning-content__icon-wrapper">
<ErrorIcon />
</div>
{(warningCode || warningMessage) && (
<div className="warning-content__summary-left">
<div className="warning-content__icon-wrapper">
<ErrorIcon />
</div>
<div className="warning-content__summary-text">
<h2 className="warning-content__warning-code">{warningCode}</h2>
<p className="warning-content__warning-message">{warningMessage}</p>
<div className="warning-content__summary-text">
<h2 className="warning-content__warning-code">{warningCode}</h2>
<p className="warning-content__warning-message">{warningMessage}</p>
</div>
</div>
</div>
)}
{warningUrl && (
<div className="warning-content__summary-right">
@@ -154,6 +157,10 @@ function WarningPopover({
overlayInnerStyle={{ padding: 0 }}
autoAdjustOverflow
{...popoverProps}
overlayClassName={cx(
'warning-popover-overlay',
popoverProps.overlayClassName,
)}
>
{children || (
<TriangleAlert

View File

@@ -113,15 +113,3 @@
align-items: center;
gap: 4px;
}
// Hidden tags revealed on hovering the `+N` badge: the same chips as inline, one per
// line (easier to scan than a wrapped cloud) and width-capped so a long tag wraps
// instead of stretching the tooltip off-screen.
.overflowTags {
display: flex;
max-width: 360px;
flex-direction: column;
align-items: flex-start;
gap: 4px;
overflow-wrap: anywhere;
}

View File

@@ -20,9 +20,6 @@ import { linkifyText } from 'utils/linkifyText';
import { openInNewTab } from 'utils/navigation';
import styles from './DashboardInfo.module.scss';
import { TOOLTIP_SCROLL_CONTENT_CLASS } from 'components/TooltipScrollArea/TooltipScrollArea';
import TagsOverflowTooltip from './TagsOverflowTooltip';
import { DASHBOARD_NAME_MAX_LENGTH } from '../../constants';
import { useDashboardStore } from '../../store/useDashboardStore';
@@ -234,10 +231,7 @@ function DashboardInfo({
<TagBadge key={tag}>{tag}</TagBadge>
))}
{remainingTags.length > 0 && (
<TooltipSimple
title={<TagsOverflowTooltip tags={remainingTags} />}
tooltipContentProps={{ className: TOOLTIP_SCROLL_CONTENT_CLASS }}
>
<TooltipSimple title={remainingTags.join(', ')}>
<span data-testid="dashboard-tags-overflow">
<TagBadge>+{remainingTags.length}</TagBadge>
</span>

View File

@@ -1,23 +0,0 @@
import TagBadge from 'components/TagBadge/TagBadge';
import TooltipScrollArea from 'components/TooltipScrollArea/TooltipScrollArea';
import styles from './DashboardInfo.module.scss';
interface TagsOverflowTooltipProps {
/** The tags the cluster isn't showing inline. */
tags: string[];
}
function TagsOverflowTooltip({ tags }: TagsOverflowTooltipProps): JSX.Element {
return (
<TooltipScrollArea>
<div className={styles.overflowTags} data-testid="dashboard-tags-tooltip">
{tags.map((tag) => (
<TagBadge key={tag}>{tag}</TagBadge>
))}
</div>
</TooltipScrollArea>
);
}
export default TagsOverflowTooltip;

View File

@@ -1,21 +0,0 @@
import { render, screen } from '@testing-library/react';
import TagsOverflowTooltip from '../TagsOverflowTooltip';
describe('TagsOverflowTooltip', () => {
it('renders every hidden tag as its own chip', () => {
render(
<TagsOverflowTooltip tags={['production', 'team-checkout', 'tier-1']} />,
);
const chips = screen
.getByTestId('dashboard-tags-tooltip')
.querySelectorAll('[data-slot="badge"]');
expect(Array.from(chips).map((chip) => chip.textContent)).toStrictEqual([
'production',
'team-checkout',
'tier-1',
]);
});
});

View File

@@ -2,7 +2,7 @@
from the collapsible config sections above by the same hairline divider. */
.divider {
height: 1px;
background: var(--l1-border);
background: var(--l2-border);
margin: 18px 0;
}

View File

@@ -1,4 +1,4 @@
import { Flame } from '@signozhq/icons';
import { Bell } from '@signozhq/icons';
import type { DashboardtypesPanelDTO } from 'api/generated/services/sigNoz.schemas';
import { getPanelDefinition } from 'pages/DashboardPageV2/DashboardContainer/Panels/registry';
import { useCreateAlertFromPanel } from 'pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useCreateAlertFromPanel';
@@ -38,7 +38,7 @@ function ConfigActions({
<div className={styles.list}>
<ConfigActionRow
testId="panel-editor-v2-create-alert"
icon={<Flame size={14} />}
icon={<Bell size={14} />}
label="Create alert"
onClick={(): void => createAlert(panel, panelId)}
/>

View File

@@ -1,5 +1,3 @@
@use '../../../../../styles/scrollbar' as *;
.config {
display: flex;
flex-direction: column;
@@ -8,24 +6,33 @@
background-color: var(--l1-background);
overflow-y: auto;
overflow-x: hidden;
padding-bottom: 44px;
@include custom-scrollbar;
//TODO: replace this with custom-scrollbar mixin
// Thin, unobtrusive scrollbar (replaces the chunky native bar).
$thumb: color-mix(in srgb, var(--bg-vanilla-100) 16%, transparent);
scrollbar-width: thin;
scrollbar-color: $thumb transparent;
&::-webkit-scrollbar {
width: 8px;
}
&::-webkit-scrollbar-track {
background: transparent;
}
&::-webkit-scrollbar-thumb {
background: $thumb;
border-radius: 999px;
border: 2px solid transparent;
background-clip: padding-box;
}
}
.heading {
padding: 16px;
display: flex;
align-items: center;
gap: 8px;
}
.marker {
display: inline-block;
width: 8px;
height: 4px;
border-radius: 20px;
background-color: var(--primary);
margin-bottom: 18px;
padding: 16px 16px 0 16px;
}
.title {
@@ -42,10 +49,11 @@
.eyebrow {
display: block;
margin: 0 2px 10px;
font-size: 11px;
font-weight: 600;
padding: 16px;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--l1-foreground);
}
@@ -53,7 +61,7 @@
display: flex;
flex-direction: column;
gap: 16px;
padding: 16px;
padding: 0 16px;
}
.field {
@@ -63,19 +71,20 @@
}
.divider {
// flex-shrink:0 keeps the 1px line from collapsing to 0 once the pane
// content overflows and the flex column starts shrinking its children.
flex-shrink: 0;
height: 1px;
background: var(--l1-border);
background: var(--l2-border);
margin: 18px 0;
}
.sectionsContainer {
padding: 0 16px;
}
.sections {
display: flex;
flex-direction: column;
& > * {
padding: 0 16px;
border-top: 1px solid var(--l1-border);
& > * + * {
border-top: 1px solid var(--l2-border);
}
}

View File

@@ -77,10 +77,8 @@ function ConfigPane({
return (
<div className={styles.config}>
<header className={styles.heading}>
<span className={styles.marker} />
<Typography.Text>Panel Details</Typography.Text>
<Typography.Text>Panel settings</Typography.Text>
</header>
<div className={styles.divider} />
<div className={styles.group}>
<div className={styles.field}>
@@ -110,7 +108,7 @@ function ConfigPane({
<>
<div className={styles.divider} />
<div className={styles.sectionsContainer}>
<span className={styles.eyebrow}>DISPLAY OPTIONS</span>
<span className={styles.eyebrow}>Display</span>
<div className={styles.sections}>
{sections.map((config) => (
<SectionSlot

View File

@@ -1,39 +0,0 @@
import { Plus } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { TooltipSimple } from '@signozhq/ui/tooltip';
interface SectionHeaderQuickAddConfig {
label: string;
testId: string;
}
interface SectionHeaderQuickAddProps {
action: SectionHeaderQuickAddConfig;
/** Expands the section and runs the editor's registered add handler. */
onClick: () => void;
}
/** Quick-add control rendered in a configuration section's header, beside the chevron. */
function SectionHeaderQuickAdd({
action,
onClick,
}: SectionHeaderQuickAddProps): JSX.Element {
return (
<TooltipSimple title="Quick Add" side="top" arrow>
<Button
type="button"
variant="ghost"
color="secondary"
size="icon"
aria-label={action.label}
// Not `testId`: TooltipTrigger's Slot merge overwrites it with undefined.
data-testid={action.testId}
onClick={onClick}
>
<Plus size={15} />
</Button>
</TooltipSimple>
);
}
export default SectionHeaderQuickAdd;

View File

@@ -1,4 +1,3 @@
import { type ReactNode, useCallback, useRef, useState } from 'react';
import type { DashboardtypesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import {
type PanelFormattingSlice,
@@ -10,41 +9,19 @@ import {
import type { SectionEditorContext } from '../sectionContext';
import { resolveSectionEditor } from '../sectionRegistry';
import SettingsSection from '../SettingsSection/SettingsSection';
import SectionHeaderQuickAdd from './SectionHeaderQuickAdd';
// `yAxisUnit` is derived from the spec below, not forwarded, so it's omitted.
type SectionSlotProps = {
config: SectionConfig;
spec: DashboardtypesPanelSpecDTO;
onChangeSpec: (next: DashboardtypesPanelSpecDTO) => void;
} & Omit<SectionEditorContext, 'yAxisUnit' | 'registerHeaderAction'>;
// Per-section header content; `trigger` expands the section and runs the editor's handler.
const SECTION_HEADER_SLOT: Partial<
Record<SectionKind, (trigger: () => void) => ReactNode>
> = {
[SectionKind.Thresholds]: (trigger): ReactNode => (
<SectionHeaderQuickAdd
action={{
label: 'Add Threshold',
testId: 'panel-editor-v2-add-threshold-header',
}}
onClick={trigger}
/>
),
[SectionKind.ContextLinks]: (trigger): ReactNode => (
<SectionHeaderQuickAdd
action={{
label: 'Add Context Link',
testId: 'panel-editor-v2-add-link-header',
}}
onClick={trigger}
/>
),
};
} & Omit<SectionEditorContext, 'yAxisUnit'>;
/**
* Renders one configuration section: its collapsible wrapper plus the registered editor
* for `config.kind`. Renders nothing when the kind has no editor yet.
* for `config.kind`, wired through the registry's spec lens. Renders nothing when the
* kind has no editor yet (sections roll out incrementally), so a kind can declare a
* section before its editor exists.
*/
function SectionSlot({
config,
@@ -59,43 +36,13 @@ function SectionSlot({
stepInterval,
metricUnit,
}: SectionSlotProps): JSX.Element | null {
const editor = resolveSectionEditor(config.kind);
// Controlled so the header slot can expand on click; list sections open when populated.
const [open, setOpen] = useState(() => {
if (config.kind === SectionKind.Visualization) {
return true;
}
const value = editor?.get(spec);
return Array.isArray(value) && value.length > 0;
});
// The editor mounts only while open, so a collapsed-click defers the handler until it registers.
const actionHandlerRef = useRef<(() => void) | null>(null);
const pendingActionRef = useRef(false);
const registerHeaderAction = useCallback(
(handler: (() => void) | null): void => {
actionHandlerRef.current = handler;
if (handler && pendingActionRef.current) {
pendingActionRef.current = false;
handler();
}
},
[],
);
const triggerHeaderAction = useCallback((): void => {
setOpen(true);
if (actionHandlerRef.current) {
actionHandlerRef.current();
} else {
pendingActionRef.current = true;
}
}, []);
// A kind can hide a section based on current spec state (e.g. Histogram legend once
// queries are merged) — skip it before resolving the editor.
if (config.isHidden?.(spec)) {
return null;
}
const editor = resolveSectionEditor(config.kind);
if (!editor) {
return null;
}
@@ -104,19 +51,17 @@ function SectionSlot({
const { Component, get, update } = editor;
// Atomic sections carry no `controls`; controlled ones do.
const controls = 'controls' in config ? config.controls : undefined;
// Forwarded to editors that scope to the panel's unit (e.g. the thresholds unit picker).
// The panel's formatting unit, forwarded to editors that scope to it (thresholds
// restrict their unit picker to this unit's category, as in V1).
const yAxisUnit = (spec.plugin.spec as { formatting?: PanelFormattingSlice })
.formatting?.unit;
const headerSlot = SECTION_HEADER_SLOT[config.kind]?.(triggerHeaderAction);
return (
<SettingsSection
title={title}
icon={<Icon size={15} />}
open={open}
onOpenChange={setOpen}
headerSlot={headerSlot}
// Open Visualization by default so the type switcher is visible.
defaultOpen={config.kind === SectionKind.Visualization}
>
<Component
value={get(spec)}
@@ -131,7 +76,6 @@ function SectionSlot({
queryType={queryType}
stepInterval={stepInterval}
metricUnit={metricUnit}
registerHeaderAction={registerHeaderAction}
/>
</SettingsSection>
);

View File

@@ -1,72 +0,0 @@
import { useState } from 'react';
import type { DashboardtypesPanelSpecDTO } from 'api/generated/services/sigNoz.schemas';
import {
type SectionConfig,
SectionKind,
ThresholdVariant,
} from 'pages/DashboardPageV2/DashboardContainer/Panels/types/sections';
import { render, screen, userEvent } from 'tests/test-utils';
import SectionSlot from '../SectionSlot';
const THRESHOLDS_CONFIG: SectionConfig = {
kind: SectionKind.Thresholds,
controls: { variant: ThresholdVariant.LABEL },
};
function makeSpec(thresholds: unknown[] = []): DashboardtypesPanelSpecDTO {
return {
display: { name: 'CPU' },
plugin: { kind: 'signoz/TimeSeriesPanel', spec: { thresholds } },
queries: [],
} as unknown as DashboardtypesPanelSpecDTO;
}
// Stateful harness so onChange feeds back into the spec (as ConfigPane owns it).
function Harness({ initial = [] }: { initial?: unknown[] } = {}): JSX.Element {
const [spec, setSpec] = useState<DashboardtypesPanelSpecDTO>(
makeSpec(initial),
);
return (
<SectionSlot config={THRESHOLDS_CONFIG} spec={spec} onChangeSpec={setSpec} />
);
}
describe('SectionSlot header action', () => {
it('shows the header "+" while the section is collapsed', () => {
render(<Harness />);
// Collapsed: body (inline add) hidden, but the header quick-add is available.
expect(
screen.queryByTestId('panel-editor-v2-add-threshold'),
).not.toBeInTheDocument();
expect(
screen.getByTestId('panel-editor-v2-add-threshold-header'),
).toBeInTheDocument();
});
it('starts expanded when the section already has items', () => {
render(
<Harness initial={[{ value: 80, color: '#F5B225', label: 'High' }]} />,
);
// Body is shown on mount (no header click needed) because content exists.
expect(
screen.getByTestId('panel-editor-v2-add-threshold'),
).toBeInTheDocument();
expect(screen.getByText('High')).toBeInTheDocument();
});
it('expands the section and adds a threshold when the header "+" is clicked', async () => {
const user = userEvent.setup();
render(<Harness />);
await user.click(screen.getByTestId('panel-editor-v2-add-threshold-header'));
// Expanded, with a fresh row opened in edit mode.
expect(
screen.getByTestId('panel-editor-v2-add-threshold'),
).toBeInTheDocument();
expect(screen.getByTestId('threshold-value-0')).toBeInTheDocument();
});
});

View File

@@ -1,19 +1,10 @@
.header {
display: flex;
align-items: center;
gap: 6px;
gap: 11px;
width: 100%;
height: 44px;
}
// Disclosure control (icon tile + title); fills the row so the action slot and chevron sit right.
.toggle {
display: flex;
flex: 1;
align-items: center;
gap: 11px;
min-width: 0;
padding: 0 !important;
padding: 0 4px;
border: none;
background: transparent;
cursor: pointer;
@@ -46,6 +37,8 @@
}
.chevron {
flex: none;
color: var(--l2-border);
transition: transform 0.15s ease;
&.open {

View File

@@ -1,6 +1,5 @@
import { type ReactNode, useState } from 'react';
import { ChevronDown } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import { Typography } from '@signozhq/ui/typography';
import cx from 'classnames';
@@ -10,74 +9,45 @@ interface SettingsSectionProps {
title: string;
icon?: ReactNode;
defaultOpen?: boolean;
/** Controlled open state; when set, the section defers to `onOpenChange`. */
open?: boolean;
onOpenChange?: (open: boolean) => void;
/** Rendered between the title and the chevron. */
headerSlot?: ReactNode;
children: ReactNode;
}
/**
* Collapsible container for one configuration section in the V2 panel editor's ConfigPane.
* Collapsible container for one configuration section in the V2 panel editor's
* ConfigPane. Header shows an icon tile (accented when expanded), the title, and a
* rotating chevron; sections are separated by hairline dividers (no surrounding boxes),
* matching the Configure-panel design.
*/
function SettingsSection({
title,
icon,
defaultOpen = false,
open,
onOpenChange,
headerSlot,
children,
}: SettingsSectionProps): JSX.Element {
const [internalOpen, setInternalOpen] = useState(defaultOpen);
const isControlled = open !== undefined;
const isOpen = isControlled ? open : internalOpen;
const toggle = (): void => {
const next = !isOpen;
if (!isControlled) {
setInternalOpen(next);
}
onOpenChange?.(next);
};
const [isOpen, setIsOpen] = useState(defaultOpen);
const serializedTitle = title.toLowerCase().replace(/\s+/g, '-');
return (
<section className={styles.section}>
<div className={styles.header}>
<button
type="button"
className={styles.toggle}
aria-expanded={isOpen}
data-testid={`config-section-${serializedTitle}`}
onClick={toggle}
>
{icon && (
<span className={cx(styles.iconTile, { [styles.iconTileOpen]: isOpen })}>
{icon}
</span>
)}
<Typography.Text className={styles.title}>{title}</Typography.Text>
</button>
{headerSlot}
<Button
type="button"
variant="ghost"
color="secondary"
size="icon"
prefix={
<ChevronDown
size={15}
className={cx(styles.chevron, { [styles.open]: isOpen })}
/>
}
aria-label={isOpen ? `Collapse ${title}` : `Expand ${title}`}
tabIndex={-1}
onClick={toggle}
<button
type="button"
className={styles.header}
aria-expanded={isOpen}
data-testid={`config-section-${serializedTitle}`}
onClick={(): void => setIsOpen((prev) => !prev)}
>
{icon && (
<span className={cx(styles.iconTile, { [styles.iconTileOpen]: isOpen })}>
{icon}
</span>
)}
<Typography.Text className={styles.title}>{title}</Typography.Text>
<ChevronDown
size={15}
className={cx(styles.chevron, { [styles.open]: isOpen })}
/>
</div>
</button>
{isOpen && <div className={styles.body}>{children}</div>}
</section>
);

View File

@@ -1,56 +0,0 @@
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import SettingsSection from '../SettingsSection';
describe('SettingsSection', () => {
it('renders an arbitrary headerSlot node beside the header', () => {
render(
<SettingsSection
title="Thresholds"
headerSlot={
<button type="button" aria-label="custom action" data-testid="my-action" />
}
>
<div>body</div>
</SettingsSection>,
);
expect(screen.getByTestId('my-action')).toBeInTheDocument();
});
it('is collapsed by default: hides the body until the header is clicked', async () => {
const user = userEvent.setup();
render(
<SettingsSection title="Thresholds">
<div data-testid="body">body</div>
</SettingsSection>,
);
expect(screen.queryByTestId('body')).not.toBeInTheDocument();
await user.click(screen.getByTestId('config-section-thresholds'));
expect(screen.getByTestId('body')).toBeInTheDocument();
});
it('defers to onOpenChange when open is controlled', async () => {
const user = userEvent.setup();
const onOpenChange = jest.fn();
const { rerender } = render(
<SettingsSection title="Thresholds" open={false} onOpenChange={onOpenChange}>
<div data-testid="body">body</div>
</SettingsSection>,
);
expect(screen.queryByTestId('body')).not.toBeInTheDocument();
await user.click(screen.getByTestId('config-section-thresholds'));
expect(onOpenChange).toHaveBeenCalledWith(true);
rerender(
<SettingsSection title="Thresholds" open onOpenChange={onOpenChange}>
<div data-testid="body">body</div>
</SettingsSection>,
);
expect(screen.getByTestId('body')).toBeInTheDocument();
});
});

View File

@@ -1,13 +1,20 @@
import { useState } from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
import type {
DashboardtypesPanelDTO,
DashboardtypesPanelSpecDTO,
} from 'api/generated/services/sigNoz.schemas';
import { render, screen, userEvent } from 'tests/test-utils';
import { EQueryType } from 'types/common/dashboard';
import ConfigPane from '../ConfigPane';
// The Actions group's hook navigates/logs; stub it so ConfigPane renders without a router.
jest.mock(
'pages/DashboardPageV2/DashboardContainer/PanelsAndSectionsLayout/Panel/hooks/useCreateAlertFromPanel',
() => ({
useCreateAlertFromPanel: (): jest.Mock => jest.fn(),
}),
);
function spec(unit?: string): DashboardtypesPanelSpecDTO {
return {
display: { name: 'CPU', description: 'usage' },
@@ -33,23 +40,7 @@ function renderConfigPane(
panelId: 'panel-1',
...overrides,
};
// Stateful so typed edits feed back into the spec, as the panel editor owns it.
function Harness(): JSX.Element {
const [currentSpec, setCurrentSpec] = useState(props.spec);
return (
<ConfigPane
{...props}
spec={currentSpec}
onChangeSpec={(next): void => {
props.onChangeSpec(next);
setCurrentSpec(next);
}}
/>
);
}
render(<Harness />);
render(<ConfigPane {...props} />);
return props;
}
@@ -63,15 +54,14 @@ describe('ConfigPane', () => {
);
});
it('reports title edits through onChangeSpec (into spec.display)', async () => {
const user = userEvent.setup();
it('reports title edits through onChangeSpec (into spec.display)', () => {
const { onChangeSpec } = renderConfigPane();
const title = screen.getByTestId('panel-editor-v2-title');
await user.clear(title);
await user.type(title, 'Memory');
fireEvent.change(screen.getByTestId('panel-editor-v2-title'), {
target: { value: 'Memory' },
});
expect(onChangeSpec).toHaveBeenLastCalledWith(
expect(onChangeSpec).toHaveBeenCalledWith(
expect.objectContaining({
display: { name: 'Memory', description: 'usage' },
}),

View File

@@ -1,10 +1,6 @@
// Fill the section field so the select lines up with the other full-width controls.
.select {
width: 100%;
:global(.ant-select-selector) {
border-color: var(--l2-border) !important;
}
}
.item {

View File

@@ -5,7 +5,7 @@
gap: 12px;
padding: 12px 14px;
border: 1px solid var(--l2-border);
border-radius: 2px;
border-radius: 6px;
background: var(--l2-background-60);
}

View File

@@ -1,5 +1,3 @@
@use '../../../../../../../styles/scrollbar' as *;
.container {
display: flex;
flex-direction: column;
@@ -7,7 +5,6 @@
}
.list {
@include custom-scrollbar;
width: 100%;
}

View File

@@ -21,6 +21,4 @@ export interface SectionEditorContext {
stepInterval?: number;
/** Unit the selected metric was sent with; drives the unit selector's mismatch warning. */
metricUnit?: string;
/** An editor registers the handler its header action (e.g. a quick-add "+") triggers; `null` to clear. */
registerHeaderAction?: (handler: (() => void) | null) => void;
}

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useState } from 'react';
import { useState } from 'react';
import { Plus } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import type { DashboardtypesLinkDTO } from 'api/generated/services/sigNoz.schemas';
@@ -7,7 +7,6 @@ import type {
SectionKind,
} from 'pages/DashboardPageV2/DashboardContainer/Panels/types/sections';
import type { SectionEditorContext } from '../../sectionContext';
import ContextLinkDialog from './ContextLinkDialog';
import ContextLinkListItem from './ContextLinkListItem';
import { useContextLinkVariables } from './useContextLinkVariables';
@@ -22,9 +21,7 @@ import styles from './ContextLinksSection.module.scss';
function ContextLinksSection({
value,
onChange,
registerHeaderAction,
}: SectionEditorProps<SectionKind.ContextLinks> &
Pick<SectionEditorContext, 'registerHeaderAction'>): JSX.Element {
}: SectionEditorProps<SectionKind.ContextLinks>): JSX.Element {
const links = value ?? [];
const variables = useContextLinkVariables();
@@ -34,16 +31,6 @@ function ContextLinksSection({
index: null,
});
const openAddDialog = useCallback(
(): void => setDialog({ open: true, index: null }),
[],
);
useEffect(() => {
registerHeaderAction?.(openAddDialog);
return (): void => registerHeaderAction?.(null);
}, [registerHeaderAction, openAddDialog]);
const removeAt = (index: number): void =>
onChange(links.filter((_, i) => i !== index));
@@ -79,7 +66,7 @@ function ContextLinksSection({
color="secondary"
prefix={<Plus size={14} />}
data-testid="panel-editor-v2-add-link"
onClick={openAddDialog}
onClick={(): void => setDialog({ open: true, index: null })}
>
Add Context Link
</Button>

View File

@@ -8,9 +8,6 @@
:global(.ant-select) {
width: 100%;
}
:global(.ant-select-selector) {
border-color: var(--l2-border) !important;
}
}
// Stacked per-column unit pickers; each column keeps the standard field layout.

View File

@@ -96,9 +96,6 @@
:global(.ant-select) {
width: 100%;
}
:global(.ant-select-selector) {
border-color: var(--l2-border) !important;
}
}
.invalidUnit {

View File

@@ -1,4 +1,4 @@
import { useCallback, useEffect, useRef, useState } from 'react';
import { useRef, useState } from 'react';
import { Plus } from '@signozhq/icons';
import { Button } from '@signozhq/ui/button';
import {
@@ -63,10 +63,7 @@ type ThresholdsSectionProps = {
/** `variant` picks the row editor + element shape; defaults to `label`. */
controls?: { variant?: ThresholdVariant };
onChange: (next: AnyThreshold[]) => void;
} & Pick<
SectionEditorContext,
'yAxisUnit' | 'tableColumns' | 'registerHeaderAction'
>;
} & Pick<SectionEditorContext, 'yAxisUnit' | 'tableColumns'>;
/**
* Edits the `thresholds` slice for every panel kind. All variants share the same
@@ -80,7 +77,6 @@ function ThresholdsSection({
onChange,
yAxisUnit,
tableColumns = [],
registerHeaderAction,
}: ThresholdsSectionProps): JSX.Element {
const variant = controls?.variant ?? ThresholdVariant.LABEL;
const thresholds = value ?? [];
@@ -97,17 +93,12 @@ function ThresholdsSection({
onChange(thresholds.map((t, i) => (i === index ? next : t)));
};
const addThreshold = useCallback((): void => {
const current = value ?? [];
onChange([...current, defaultThreshold(variant, tableColumns)]);
setEditingIndex(current.length);
setUnsavedIndex(current.length);
}, [value, onChange, variant, tableColumns]);
useEffect(() => {
registerHeaderAction?.(addThreshold);
return (): void => registerHeaderAction?.(null);
}, [registerHeaderAction, addThreshold]);
const addThreshold = (): void => {
const nextIndex = thresholds.length;
onChange([...thresholds, defaultThreshold(variant, tableColumns)]);
setEditingIndex(nextIndex);
setUnsavedIndex(nextIndex);
};
const beginEdit = (index: number): void => {
editSnapshot.current = thresholds[index] ?? null;

View File

@@ -5,7 +5,6 @@ import { DialogWrapper } from '@signozhq/ui/dialog';
import { Divider } from '@signozhq/ui/divider';
import { Typography } from '@signozhq/ui/typography';
import logEvent from 'api/common/logEvent';
import HeaderRightSection from 'components/HeaderRightSection/HeaderRightSection';
import { useConfirmableAction } from 'hooks/useConfirmableAction';
import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';
@@ -68,11 +67,6 @@ function Header({
<Typography.Text>Configure panel</Typography.Text>
</div>
<div className={styles.actions}>
<HeaderRightSection
enableAnnouncements={false}
enableShare={false}
enableFeedback={false}
/>
{showSwitchToView && (
<Button
variant="outlined"

View File

@@ -1,69 +0,0 @@
import { MemoryRouter } from 'react-router-dom';
import { render, screen } from '@testing-library/react';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import { useIsAIAssistantEnabled } from 'hooks/useIsAIAssistantEnabled';
import Header from '../Header';
jest.mock('hooks/useIsAIAssistantEnabled', () => ({
useIsAIAssistantEnabled: jest.fn(),
}));
jest.mock('hooks/useGetTenantLicense', () => ({
useGetTenantLicense: (): unknown => ({
isCloudUser: true,
isEnterpriseSelfHostedUser: false,
}),
}));
jest.mock('api/common/logEvent', () => ({
__esModule: true,
default: jest.fn(),
}));
const mockUseIsAIAssistantEnabled = useIsAIAssistantEnabled as jest.Mock;
function renderHeader(): void {
// AppLayout supplies the TooltipProvider in the app; the header is rendered bare here.
render(
<MemoryRouter>
<TooltipProvider>
<Header
isDirty={false}
isSaving={false}
onSave={jest.fn()}
onClose={jest.fn()}
/>
</TooltipProvider>
</MemoryRouter>,
);
}
describe('PanelEditor Header', () => {
afterEach(() => {
mockUseIsAIAssistantEnabled.mockReset();
});
// The editor is a full page, so the side nav's Noz entry point is gone while it is
// open — the header has to offer it instead.
it('offers Noz alongside the editor actions', () => {
mockUseIsAIAssistantEnabled.mockReturnValue(true);
renderHeader();
expect(screen.getByRole('button', { name: 'Open Noz' })).toBeInTheDocument();
expect(screen.getByTestId('panel-editor-v2-save')).toBeInTheDocument();
expect(screen.getByTestId('panel-editor-v2-close')).toBeInTheDocument();
});
it('omits Noz when the AI assistant is disabled', () => {
mockUseIsAIAssistantEnabled.mockReturnValue(false);
renderHeader();
expect(
screen.queryByRole('button', { name: 'Open Noz' }),
).not.toBeInTheDocument();
expect(screen.getByTestId('panel-editor-v2-save')).toBeInTheDocument();
});
});

View File

@@ -9,7 +9,7 @@ import type { Query } from 'types/api/queryBuilder/queryBuilderData';
import { DataSource } from 'types/common/queryBuilder';
import { AllTheProviders } from 'tests/test-utils';
import { fromPerses, toPerses } from '../../../queryV5/persesQueryAdapters';
import { toPerses } from '../../../queryV5/persesQueryAdapters';
import { usePanelEditorQuerySync } from '../usePanelEditorQuerySync';
// Exercises the REAL query builder provider (not mocks) so the dirty check is
@@ -45,28 +45,6 @@ function makePanel(queries: DashboardtypesQueryDTO[]): DashboardtypesPanelDTO {
} as unknown as DashboardtypesPanelDTO;
}
/** Providers whose URL already carries `query` as the compositeQuery param (a mid-edit refresh). */
function makeUrlWrapper(
query: Query,
): ({ children }: { children: React.ReactNode }) => JSX.Element {
const params = new URLSearchParams();
params.set(
QueryParams.compositeQuery,
encodeURIComponent(JSON.stringify(query)),
);
return function UrlWrapper({
children,
}: {
children: React.ReactNode;
}): JSX.Element {
return (
<AllTheProviders initialRoute={`/?${params.toString()}`}>
{children}
</AllTheProviders>
);
};
}
describe('usePanelEditorQuerySync (real query builder)', () => {
it('an untouched existing panel is NOT query-dirty on mount', async () => {
const saved = makeSavedQueries();
@@ -134,80 +112,6 @@ describe('usePanelEditorQuerySync (real query builder)', () => {
expect(result.current.isQueryDirty).toBe(false);
});
it('a saved panel with no `having` is NOT dirty on mount (builder seeds an empty having)', async () => {
// Reproduces the reported bug: a panel saved as a bare signoz/BuilderQuery that never
// carried a `having`. On editor open the builder hydrates from the URL and
// prepareQueryBuilderData seeds an empty `{ expression: '' }`, so a verbatim envelope
// compare flags the untouched panel as dirty. Seed via the URL (not resetQuery) so the
// hydration path that synthesizes the having actually runs.
const savedNoHaving: DashboardtypesQueryDTO[] = [
{
kind: 'time_series',
spec: {
name: 'A',
plugin: {
kind: 'signoz/BuilderQuery',
spec: {
name: 'A',
signal: 'metrics',
source: '',
aggregations: [
{
metricName: 'signoz_latency.bucket',
temporality: 'delta',
timeAggregation: '',
spaceAggregation: 'p99',
},
],
disabled: false,
filter: { expression: 'service.name IN $service_name' },
groupBy: [
{
name: 'service.name',
signal: '',
fieldContext: 'resource',
fieldDataType: '',
},
],
order: [
{
key: {
name: '__result',
signal: '',
fieldContext: '',
fieldDataType: '',
},
direction: 'desc',
},
],
limit: 100,
legend: '',
},
},
},
},
] as unknown as DashboardtypesQueryDTO[];
// The editor puts the (having-less) seed query into the URL; the provider then hydrates
// from it, which is where the empty having is added.
const seededInUrl = fromPerses(savedNoHaving, panelType);
const { result } = renderHook(
() =>
usePanelEditorQuerySync({
draft: makePanel(savedNoHaving),
panelType,
setSpec: jest.fn(),
refetch: jest.fn(),
savedQueries: savedNoHaving,
}),
{ wrapper: makeUrlWrapper(seededInUrl) },
);
await waitFor(() => expect(result.current.isQueryDirty).toBe(false));
expect(result.current.isQueryDirty).toBe(false);
});
it('retains an in-editor query edit carried in the URL across a refresh (and reads dirty)', async () => {
// Simulate a refresh mid-edit: the saved panel is unchanged, but the URL still
// carries the last-run (edited) query. The builder must hydrate from the URL —
@@ -226,8 +130,23 @@ describe('usePanelEditorQuerySync (real query builder)', () => {
],
},
};
const params = new URLSearchParams();
params.set(
QueryParams.compositeQuery,
encodeURIComponent(JSON.stringify(editedInUrl)),
);
const setSpec = jest.fn();
const wrapper = ({
children,
}: {
children: React.ReactNode;
}): JSX.Element => (
<AllTheProviders initialRoute={`/?${params.toString()}`}>
{children}
</AllTheProviders>
);
const { result } = renderHook(
() =>
usePanelEditorQuerySync({
@@ -238,7 +157,7 @@ describe('usePanelEditorQuerySync (real query builder)', () => {
refetch: jest.fn(),
savedQueries: saved,
}),
{ wrapper: makeUrlWrapper(editedInUrl) },
{ wrapper },
);
// The URL edit is retained → dirty, and it's synced into the draft so the

View File

@@ -1,24 +1,16 @@
@use '../../../../../../styles/scrollbar' as *;
// Centred, vertically-stacked panel state (no query / no data / error). Fills
// the panel body below the header and centres its content both axes. When the
// panel is too small to fit icon + text + actions, it scrolls instead of
// clipping the buttons at the edge (`safe center` keeps the top reachable).
// the panel body below the header and centres its content both axes.
.message {
flex: 1;
display: flex;
flex-direction: column;
align-items: center;
justify-content: safe center;
justify-content: center;
gap: 6px;
padding: 16px;
text-align: center;
min-height: 0;
min-width: 0;
overflow: auto;
// Match the shared panel scrollbar (chart legend, table/list panels).
@include custom-scrollbar;
}
// Muted glyph in a soft tinted disc so the icon reads as decorative chrome
@@ -59,5 +51,4 @@
justify-content: center;
gap: 8px;
margin-top: 8px;
max-width: 100%;
}

View File

@@ -83,32 +83,6 @@ describe('preparePieData', () => {
]);
});
it('substitutes a legend format template with the group-by values', () => {
const table = tableWith(
[
{
name: 'service.name',
queryName: 'A',
isValueColumn: false,
id: 'service.name',
},
{ name: 'count', queryName: 'A', isValueColumn: true, id: 'A' },
],
[
{ data: { 'service.name': 'adservice', A: 100 } },
{ data: { 'service.name': 'cartservice', A: 200 } },
],
{ legend: 'service.name = {{service.name}}' },
);
const slices = preparePieData(args([table]));
expect(slices.map((s) => s.label)).toStrictEqual([
'service.name = adservice',
'service.name = cartservice',
]);
});
it('prefixes the group when multiple value columns are grouped', () => {
const table = tableWith(
[

View File

@@ -14,16 +14,15 @@ import type {
TelemetrytypesTelemetryFieldKeyDTO,
} from 'api/generated/services/sigNoz.schemas';
import {
Antenna,
BarChart,
Columns3,
Hash,
Link2,
Layers,
LayoutDashboard,
Link,
Palette,
PencilRuler,
Scale3D,
Signpost,
Wallpaper,
Ruler,
SlidersHorizontal,
} from '@signozhq/icons';
// Derived from an actual icon component so the type stays exact (size is a
@@ -158,14 +157,14 @@ export type SectionConfig =
// Per-section title + sidebar icon. Pure data; the editor component + spec lens
// live in the ConfigPane section registry.
export const SECTION_METADATA = {
[SectionKind.Formatting]: { title: 'Formatting & Units', icon: PencilRuler },
[SectionKind.Axes]: { title: 'Axes', icon: Scale3D },
[SectionKind.Legend]: { title: 'Legend', icon: Signpost },
[SectionKind.Formatting]: { title: 'Formatting & Units', icon: Hash },
[SectionKind.Axes]: { title: 'Axes', icon: Ruler },
[SectionKind.Legend]: { title: 'Legend', icon: Layers },
[SectionKind.ChartAppearance]: { title: 'Chart appearance', icon: Palette },
[SectionKind.Visualization]: { title: 'Visualization', icon: Wallpaper },
[SectionKind.Visualization]: { title: 'Visualization', icon: LayoutDashboard },
[SectionKind.Buckets]: { title: 'Histogram / Buckets', icon: BarChart },
[SectionKind.Thresholds]: { title: 'Thresholds', icon: Antenna },
[SectionKind.ContextLinks]: { title: 'Context Links', icon: Link2 },
[SectionKind.Thresholds]: { title: 'Thresholds', icon: SlidersHorizontal },
[SectionKind.ContextLinks]: { title: 'Context Links', icon: Link },
[SectionKind.Columns]: { title: 'Columns', icon: Columns3 },
} as const satisfies Record<SectionKind, SectionMetadata>;

View File

@@ -67,16 +67,6 @@
vertical-align: bottom;
}
// The values behind a pill's `+N`, one bullet each, width-capped so a long value
// wraps instead of stretching the tooltip off-screen.
.overflowValues {
max-width: 360px;
margin: 0;
padding-left: 14px;
list-style: disc outside;
overflow-wrap: anywhere;
}
// Shared by the Text and value selectors: strips the antd control chrome so the
// selector blends into the variable pill.
.control {
@@ -138,3 +128,13 @@
min-width: 0 !important;
}
}
.overflowTooltip {
display: flex;
flex-direction: column;
gap: 2px;
}
.overflowName {
font-weight: var(--font-weight-medium);
}

View File

@@ -9,13 +9,28 @@ import { selectVariablesExpanded } from '../store/slices/collapseSlice';
import { useDashboardStore } from '../store/useDashboardStore';
import AddVariableFull from './components/AddVariable/AddVariableFull';
import AddVariableIcon from './components/AddVariable/AddVariableIcon';
import { TOOLTIP_SCROLL_CONTENT_CLASS } from 'components/TooltipScrollArea/TooltipScrollArea';
import HiddenVariablesTooltip from './components/HiddenVariablesTooltip/HiddenVariablesTooltip';
import type { VariableSelection } from './selectionTypes';
import { useVariableSelection } from './hooks/useVariableSelection';
import VariableSelector from './components/VariableSelector/VariableSelector';
import styles from './VariablesBar.module.scss';
// Short display of a variable's current selection, for the collapsed +N tooltip.
function formatSelection(selection: VariableSelection | undefined): string {
if (!selection) {
return '—';
}
if (selection.allSelected) {
return 'ALL';
}
const { value } = selection;
if (Array.isArray(value)) {
return value.length > 0 ? value.join(', ') : '—';
}
return value === '' || value === null || value === undefined
? '—'
: String(value);
}
interface VariablesBarProps {
dashboard: DashboardtypesGettableDashboardV2DTO;
}
@@ -115,12 +130,15 @@ function VariablesBar({ dashboard }: VariablesBarProps): JSX.Element | null {
) : (
<TooltipSimple
side="top"
tooltipContentProps={{ className: TOOLTIP_SCROLL_CONTENT_CLASS }}
title={
<HiddenVariablesTooltip
variables={hiddenVariables}
selections={selection}
/>
<div className={styles.overflowTooltip}>
{hiddenVariables.map((variable) => (
<div key={variable.name}>
<span className={styles.overflowName}>{variable.name}</span>:{' '}
{formatSelection(selection[variable.name])}
</div>
))}
</div>
}
>
{moreButton}

View File

@@ -1,84 +0,0 @@
import { render, screen } from '@testing-library/react';
import {
emptyVariableFormModel,
type VariableFormModel,
} from '../../DashboardSettings/Variables/variableFormModel';
import type { VariableSelectionMap } from '../selectionTypes';
import HiddenVariablesTooltip from '../components/HiddenVariablesTooltip/HiddenVariablesTooltip';
function variable(name: string): VariableFormModel {
return { ...emptyVariableFormModel(), name };
}
function renderTooltip(
names: string[],
selections: VariableSelectionMap,
): HTMLElement {
render(
<HiddenVariablesTooltip
variables={names.map(variable)}
selections={selections}
/>,
);
return screen.getByTestId('hidden-variables-tooltip');
}
describe('HiddenVariablesTooltip', () => {
it('names each hidden variable with a $ prefix, apart from its value', () => {
renderTooltip(['env', 'service'], {
env: { value: 'production', allSelected: false },
service: { value: ['checkout', 'cart'], allSelected: false },
});
expect(screen.getByText('$env')).toBeInTheDocument();
expect(screen.getByText('$service')).toBeInTheDocument();
});
it('bullets out a variable holding several values', () => {
renderTooltip(['service'], {
service: { value: ['checkout', 'cart', 'api'], allSelected: false },
});
expect(
screen.getAllByRole('listitem').map((item) => item.textContent),
).toStrictEqual(['checkout', 'cart', 'api']);
});
it('keeps a lone value unbulleted', () => {
renderTooltip(['env'], {
env: { value: 'production', allSelected: false },
});
expect(screen.queryByRole('list')).not.toBeInTheDocument();
expect(screen.getByText('production')).toBeInTheDocument();
});
it('labels all-selected and unset variables', () => {
renderTooltip(['env', 'host'], {
env: { value: null, allSelected: true },
});
expect(screen.getByText('ALL')).toBeInTheDocument();
expect(screen.getByText('—')).toBeInTheDocument();
});
it('lists every hidden variable, however many there are', () => {
const names = Array.from({ length: 12 }, (_, i) => `var${i}`);
const tooltip = renderTooltip(names, {});
expect(tooltip).toHaveTextContent('$var0');
expect(tooltip).toHaveTextContent('$var11');
});
it('bullets every value it is given, without truncating', () => {
const values = Array.from({ length: 14 }, (_, i) => `v${i}`);
renderTooltip(['service'], {
service: { value: values, allSelected: false },
});
expect(screen.getAllByRole('listitem')).toHaveLength(14);
});
});

View File

@@ -1,90 +0,0 @@
import { act, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TooltipProvider } from '@signozhq/ui/tooltip';
import type { VariableSelection } from '../selectionTypes';
import ValueSelector from '../components/selectors/ValueSelector';
jest.mock('api/common/logEvent', () => ({
__esModule: true,
default: jest.fn(),
}));
const VALUES = ['checkout-service-prod', 'payments-service-prod'];
// A strict subset of the options — selecting every option renders as ALL instead.
const OPTIONS = [...VALUES, 'cart-service-prod'];
function renderSelector(
selection: VariableSelection,
options: string[],
multiSelect = true,
): void {
render(
<TooltipProvider>
<ValueSelector
options={options}
variableType="dynamic"
multiSelect={multiSelect}
showAllOption
selection={selection}
onChange={jest.fn()}
emptyFallback={{ value: [], allSelected: false }}
testId="variable-select-env"
/>
</TooltipProvider>,
);
}
/** Hovers an element and lets the tooltip's open delay elapse. */
async function hover(element: HTMLElement): Promise<void> {
const user = userEvent.setup({ advanceTimers: jest.advanceTimersByTime });
await user.hover(element);
act(() => {
jest.advanceTimersByTime(500);
});
}
describe('ValueSelector', () => {
beforeEach(() => {
jest.useFakeTimers();
});
afterEach(() => {
jest.useRealTimers();
});
it("reveals a tag's full value on hovering that tag", async () => {
renderSelector({ value: VALUES, allSelected: false }, OPTIONS);
// maxTagCount={1} + maxTagTextLength={10} → the one visible tag is cut short.
await hover(screen.getByText('checkout-s...'));
expect(screen.getByRole('tooltip')).toHaveTextContent(
'checkout-service-prod',
);
});
it('reveals the hidden values on hovering the +N overflow', async () => {
renderSelector({ value: VALUES, allSelected: false }, OPTIONS);
await hover(screen.getByText('+1'));
expect(screen.getByRole('tooltip')).toHaveTextContent(
'payments-service-prod',
);
});
it('does not reveal anything from the rest of the control', async () => {
renderSelector({ value: VALUES, allSelected: false }, OPTIONS);
await hover(screen.getByTestId('variable-select-env'));
expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
});
it('renders ALL for an all-selected variable', () => {
renderSelector({ value: null, allSelected: true }, ['a', 'b']);
expect(screen.getByText('ALL')).toBeInTheDocument();
});
});

View File

@@ -1,39 +0,0 @@
import { describeSelection } from '../utils/selectionDisplay';
describe('describeSelection', () => {
it('reports an all-selected variable as ALL', () => {
expect(describeSelection({ value: null, allSelected: true })).toStrictEqual({
kind: 'all',
});
});
it('lists a multi-select selection', () => {
expect(
describeSelection({ value: ['a', 'b'], allSelected: false }),
).toStrictEqual({ kind: 'values', values: ['a', 'b'] });
});
it('keeps every value, however many there are', () => {
const values = Array.from({ length: 30 }, (_, i) => `v${i}`);
expect(
describeSelection({ value: values, allSelected: false }),
).toStrictEqual({ kind: 'values', values });
});
it('lists a single value on its own', () => {
expect(
describeSelection({ value: 'production', allSelected: false }),
).toStrictEqual({ kind: 'values', values: ['production'] });
});
it('reports a missing or empty selection as empty', () => {
expect(describeSelection(undefined)).toStrictEqual({ kind: 'empty' });
expect(describeSelection({ value: '', allSelected: false })).toStrictEqual({
kind: 'empty',
});
expect(describeSelection({ value: [], allSelected: false })).toStrictEqual({
kind: 'empty',
});
});
});

View File

@@ -1,117 +0,0 @@
// eslint-disable-next-line no-restricted-imports
import { useSelector } from 'react-redux';
import { QueryClient, QueryClientProvider } from 'react-query';
import { act, renderHook, waitFor } from '@testing-library/react';
import { getFieldValues } from 'api/dynamicVariables/getFieldValues';
import {
emptyVariableFormModel,
type VariableFormModel,
} from '../../DashboardSettings/Variables/variableFormModel';
import { VariableFetchState } from '../../store/slices/variableFetchSlice';
import { useDashboardStore } from '../../store/useDashboardStore';
import { useFetchedVariableOptions } from '../hooks/useFetchedVariableOptions';
jest.mock('react-redux', () => ({ useSelector: jest.fn() }));
jest.mock('api/dynamicVariables/getFieldValues', () => ({
getFieldValues: jest.fn(),
}));
const mockUseSelector = useSelector as unknown as jest.Mock;
const mockGetFieldValues = getFieldValues as unknown as jest.Mock;
function fieldValues(values: string[]): unknown {
return { data: { normalizedValues: values, complete: true } };
}
/** A promise resolved by the test, so the in-flight window is deterministic. */
function deferred(): {
promise: Promise<unknown>;
resolve: (value: unknown) => void;
} {
let settle: (value: unknown) => void = () => {};
const promise = new Promise<unknown>((resolve) => {
settle = resolve;
});
return { promise, resolve: settle };
}
function dynamicVariable(name: string): VariableFormModel {
return {
...emptyVariableFormModel(),
name,
type: 'DYNAMIC',
dynamicAttribute: 'service.name',
};
}
function wrapper({ children }: { children: React.ReactNode }): JSX.Element {
const client = new QueryClient({
defaultOptions: { queries: { retry: false } },
});
return <QueryClientProvider client={client}>{children}</QueryClientProvider>;
}
describe('useFetchedVariableOptions', () => {
beforeEach(() => {
mockUseSelector.mockImplementation((selector: (state: unknown) => unknown) =>
selector({
globalTime: {
minTime: 1_000,
maxTime: 2_000,
isAutoRefreshDisabled: true,
},
}),
);
});
afterEach(() => {
mockGetFieldValues.mockReset();
useDashboardStore.setState({
variableFetchStates: {},
variableLastUpdated: {},
variableCycleIds: {},
variableResolvedEmpty: {},
});
});
it('keeps the previous options while a new fetch cycle is in flight', async () => {
const refetch = deferred();
mockGetFieldValues
.mockResolvedValueOnce(fieldValues(['prod', 'staging']))
.mockReturnValueOnce(refetch.promise);
useDashboardStore.setState({
variableFetchStates: { env: VariableFetchState.Loading },
variableCycleIds: { env: 1 },
});
const variable = dynamicVariable('env');
const { result } = renderHook(
() => useFetchedVariableOptions(variable, [variable], {}),
{ wrapper },
);
await waitFor(() =>
expect(result.current.options).toStrictEqual(['prod', 'staging']),
);
// What a sibling dynamic's selection change does: bump the cycle id, which keys
// a fresh request. The options must not blink empty in the meantime, or an ALL
// selection (rendered from them) falls back to the placeholder.
act(() => {
useDashboardStore.setState({ variableCycleIds: { env: 2 } });
});
await waitFor(() => expect(result.current.loading).toBe(true));
expect(result.current.options).toStrictEqual(['prod', 'staging']);
await act(async () => {
refetch.resolve(fieldValues(['prod']));
await refetch.promise;
});
await waitFor(() => expect(result.current.options).toStrictEqual(['prod']));
});
});

View File

@@ -1,39 +0,0 @@
.tooltip {
display: flex;
max-width: 360px;
flex-direction: column;
gap: 8px;
}
.row {
display: flex;
flex-direction: column;
gap: 2px;
min-width: 0;
}
.name {
--typography-text-display: block;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
// A lone value, ALL, or the unset dash.
.value {
--typography-text-display: block;
font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
}
// One bullet per value when a variable holds several.
.values {
margin: 0;
padding-left: 14px;
list-style: disc outside;
}
.valueItem {
font-weight: var(--font-weight-medium);
overflow-wrap: anywhere;
}

View File

@@ -1,42 +0,0 @@
import TooltipScrollArea from 'components/TooltipScrollArea/TooltipScrollArea';
import { Typography } from '@signozhq/ui/typography';
import type { VariableFormModel } from '../../../DashboardSettings/Variables/variableFormModel';
import type { VariableSelectionMap } from '../../selectionTypes';
import SelectionValue from './SelectionValue';
import styles from './HiddenVariablesTooltip.module.scss';
interface HiddenVariablesTooltipProps {
/** The variables the collapsed bar isn't showing, in bar order. */
variables: VariableFormModel[];
selections: VariableSelectionMap;
}
/**
* Body of the collapsed bar's `+N` tooltip: what each hidden variable is set to.
* Name and value sit on their own lines — `$name` muted above its value, which
* bullets out when there are several — so the two read apart at a glance instead of
* running together as `name: value`.
* Every hidden variable is listed; the box scrolls rather than truncating.
*/
function HiddenVariablesTooltip({
variables,
selections,
}: HiddenVariablesTooltipProps): JSX.Element {
return (
<TooltipScrollArea>
<div className={styles.tooltip} data-testid="hidden-variables-tooltip">
{variables.map((variable) => (
<div className={styles.row} key={variable.name}>
<Typography.Text size="xs" color="muted" className={styles.name}>
${variable.name}
</Typography.Text>
<SelectionValue selection={selections[variable.name]} />
</div>
))}
</div>
</TooltipScrollArea>
);
}
export default HiddenVariablesTooltip;

View File

@@ -1,46 +0,0 @@
import { Typography } from '@signozhq/ui/typography';
import type { VariableSelection } from '../../selectionTypes';
import { describeSelection } from '../../utils/selectionDisplay';
import styles from './HiddenVariablesTooltip.module.scss';
interface SelectionValueProps {
selection?: VariableSelection;
}
/**
* A variable's current value as tooltip content: `ALL`, a dash when unset, the lone
* value on its own, or — when it holds several — one bullet per value so the list
* doesn't read as one run-on string.
*/
function SelectionValue({ selection }: SelectionValueProps): JSX.Element {
const display = describeSelection(selection);
if (display.kind !== 'values') {
return (
<Typography.Text size="sm" className={styles.value}>
{display.kind === 'all' ? 'ALL' : '—'}
</Typography.Text>
);
}
if (display.values.length === 1) {
return (
<Typography.Text size="sm" className={styles.value}>
{display.values[0]}
</Typography.Text>
);
}
return (
<ul className={styles.values}>
{display.values.map((value) => (
<Typography.Text asChild size="sm" className={styles.valueItem} key={value}>
<li>{value}</li>
</Typography.Text>
))}
</ul>
);
}
export default SelectionValue;

View File

@@ -1,43 +0,0 @@
import { TooltipSimple } from '@signozhq/ui/tooltip';
import TooltipScrollArea, {
TOOLTIP_SCROLL_CONTENT_CLASS,
} from 'components/TooltipScrollArea/TooltipScrollArea';
import styles from '../../VariablesBar.module.scss';
interface OverflowValuesTooltipProps {
/** The selected values the pill hides behind this `+N`. */
values: string[];
}
/**
* The multi-select's `+N` overflow item, revealing on hover the values it stands
* for — one bullet each, all of them, scrolling rather than truncating. The
* scrollbar stays put instead of auto-hiding, so a capped list reads as scrollable.
*/
function OverflowValuesTooltip({
values,
}: OverflowValuesTooltipProps): JSX.Element {
return (
<TooltipSimple
side="top"
delayDuration={300}
tooltipContentProps={{ className: TOOLTIP_SCROLL_CONTENT_CLASS }}
title={
<TooltipScrollArea>
<ul className={styles.overflowValues}>
{values.map((value) => (
<li key={value}>{value}</li>
))}
</ul>
</TooltipScrollArea>
}
>
{/* rc-select copies this node into the overflow wrapper's `title`; an empty
one keeps the browser's own "[object Object]" tooltip out of the way. */}
<span title="">+{values.length}</span>
</TooltipSimple>
);
}
export default OverflowValuesTooltip;

View File

@@ -6,7 +6,6 @@ import { DashboardDetailEvents } from 'pages/DashboardPageV2/constants/events';
import type { VariableSelection } from '../../selectionTypes';
import { areSelectionsEqual } from '../../utils/resolveVariableSelection';
import OverflowValuesTooltip from './OverflowValuesTooltip';
import styles from '../../VariablesBar.module.scss';
interface ValueSelectorProps {
@@ -98,13 +97,7 @@ function ValueSelector({
placeholder="Select value"
maxTagCount={1}
maxTagTextLength={10}
maxTagPlaceholder={(omitted): JSX.Element => (
<OverflowValuesTooltip
values={omitted.map((item) =>
typeof item.label === 'string' ? item.label : String(item.value ?? ''),
)}
/>
)}
maxTagPlaceholder={(omitted): string => `+${omitted.length}`}
// Offer ALL only once options load, else a concrete value reads as "all".
enableAllSelection={showAllOption && options.length > 0}
onDropdownVisibleChange={(open): void => {

View File

@@ -89,7 +89,6 @@ export function useFetchedVariableOptions(
enabled: variable.type === 'QUERY' && canFetch,
refetchOnWindowFocus: false,
cacheTime,
keepPreviousData: true,
onSettled: (_, error) =>
error
? onVariableFetchFailure(variable.name)
@@ -125,7 +124,6 @@ export function useFetchedVariableOptions(
variable.type === 'DYNAMIC' && !!variable.dynamicAttribute && canFetch,
refetchOnWindowFocus: false,
cacheTime,
keepPreviousData: true,
onSettled: (_, error) =>
error
? onVariableFetchFailure(variable.name)

View File

@@ -1,29 +0,0 @@
import type { VariableSelection } from '../selectionTypes';
/**
* What a selection reads as in a tooltip: the ALL label, nothing at all, or the
* concrete values. Never truncated — the tooltip scrolls instead.
*/
export type SelectionDisplay =
| { kind: 'all' }
| { kind: 'empty' }
| { kind: 'values'; values: string[] };
/** Describes a selection for display. */
export function describeSelection(
selection: VariableSelection | undefined,
): SelectionDisplay {
if (!selection) {
return { kind: 'empty' };
}
if (selection.allSelected) {
return { kind: 'all' };
}
const { value } = selection;
const values = (Array.isArray(value) ? value : [value])
.filter((entry) => entry !== '' && entry !== null && entry !== undefined)
.map(String);
return values.length === 0 ? { kind: 'empty' } : { kind: 'values', values };
}

View File

@@ -387,23 +387,15 @@ describe('usePanelQuery', () => {
expect(result.current.pagination?.canNext).toBe(false);
});
it('drives canNext from the cursor OR a full page (offset fallback for non-timestamp sorts)', () => {
// Full page, no cursor → the backend's offset path (a non-timestamp sort skips the
// window/cursor path), so a full page is the has-more signal.
it('drives canNext from the response cursor, not the row count', () => {
// Full page but no cursor → backend says these are the last rows.
withResponse(rawResponse(25));
const fullPage = renderHook(() =>
const noCursor = renderHook(() =>
usePanelQuery({ panel: listPanel({}), panelId: 'p1' }),
);
expect(fullPage.result.current.pagination?.canNext).toBe(true);
expect(noCursor.result.current.pagination?.canNext).toBe(false);
// Partial page, no cursor → the last page.
withResponse(rawResponse(3));
const partialPage = renderHook(() =>
usePanelQuery({ panel: listPanel({}), panelId: 'p1' }),
);
expect(partialPage.result.current.pagination?.canNext).toBe(false);
// Cursor present (even on a partial page) → more rows (timestamp window path).
// Cursor present (even on a partial page) → more rows.
withResponse(rawResponse(3, 'cursor-1'));
const withCursor = renderHook(() =>
usePanelQuery({ panel: listPanel({}), panelId: 'p1' }),

View File

@@ -283,10 +283,8 @@ export function usePanelQuery({
[pageSize],
);
// Paging handles for raw/list panels. The backend only emits `nextCursor` on the
// timestamp-ordered window path (isWindowList); a non-timestamp sort falls back to plain
// offset paging with no cursor. So treat a full page as a has-more signal too — matching the
// offset heuristic the logs/traces explorers use (there's no total count on the wire).
// Paging handles for raw/list panels. The backend sets `nextCursor` iff the page filled,
// so it's the authoritative has-more signal (there's no total count on the wire).
const pagination = useMemo<PanelPagination | undefined>(() => {
if (!isPaginated) {
return undefined;
@@ -302,7 +300,7 @@ export function usePanelQuery({
return {
pageIndex: Math.floor(safeOffset / safePageSize),
canPrev: safeOffset > 0,
canNext: !!result?.nextCursor || (result?.rows?.length ?? 0) >= safePageSize,
canNext: !!result?.nextCursor,
goPrev,
goNext,
pageSize: safePageSize,

View File

@@ -7,7 +7,7 @@
// small ones as data URIs — they ship in the bundle and render with no network
// call. Logos are a large, JSON-only catalogue, so `?url` keeps them as emitted
// files fetched (and cached) on demand rather than bloating the bundle.
const iconModules = import.meta.glob('../../../assets/Icons/**/*.{svg,png}', {
const iconModules = import.meta.glob('../../../assets/Icons/**/*.svg', {
eager: true,
import: 'default',
});

View File

@@ -2,82 +2,329 @@ package contextlinks
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"time"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
tracesV3 "github.com/SigNoz/signoz/pkg/query-service/app/traces/v3"
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
"github.com/SigNoz/signoz/pkg/query-service/utils"
)
// PrepareParamsForTracesV5 returns the traces explorer query params for the
// given range and filter; the traces explorer writes its time params in
// nanoseconds.
func PrepareParamsForTracesV5(start, end time.Time, whereClause string) url.Values {
return prepareExplorerParams("traces", start.UnixNano(), end.UnixNano(), whereClause)
}
func PrepareLinksToTraces(start, end time.Time, filterItems []v3.FilterItem) string {
// PrepareParamsForLogsV5 returns the logs explorer query params for the given
// range and filter; the logs explorer writes its time params in milliseconds.
func PrepareParamsForLogsV5(start, end time.Time, whereClause string) url.Values {
return prepareExplorerParams("logs", start.UnixMilli(), end.UnixMilli(), whereClause)
}
// Traces list view expects time in nanoseconds
tr := URLShareableTimeRange{
Start: start.UnixNano(),
End: end.UnixNano(),
PageSize: 100,
}
options := URLShareableOptions{
MaxLines: 2,
Format: "list",
SelectColumns: tracesV3.TracesListViewDefaultSelectedColumns,
}
period, _ := json.Marshal(tr)
urlEncodedTimeRange := url.QueryEscape(string(period))
builderQuery := v3.BuilderQuery{
DataSource: v3.DataSourceTraces,
QueryName: "A",
AggregateOperator: v3.AggregateOperatorNoOp,
AggregateAttribute: v3.AttributeKey{},
Filters: &v3.FilterSet{
Items: filterItems,
Operator: "AND",
},
Expression: "A",
Disabled: false,
Having: []v3.Having{},
StepInterval: 60,
OrderBy: []v3.OrderBy{
{
ColumnName: "timestamp",
Order: "desc",
},
},
}
// The end link is double encoded because otherwise a filter expression with `%` somewhere in it breaks.
func prepareExplorerParams(dataSource string, start, end int64, whereClause string) url.Values {
urlData := URLShareableCompositeQuery{
QueryType: "builder",
QueryType: string(v3.QueryTypeBuilder),
Builder: URLShareableBuilderQuery{
QueryData: []LinkQuery{{
DataSource: dataSource,
Filter: &FilterExpression{Expression: whereClause},
}},
QueryData: []LinkQuery{
{BuilderQuery: builderQuery},
},
QueryFormulas: make([]string, 0),
},
}
data, _ := json.Marshal(urlData)
compositeQuery := url.QueryEscape(url.QueryEscape(string(data)))
optionsData, _ := json.Marshal(options)
urlEncodedOptions := url.QueryEscape(string(optionsData))
return fmt.Sprintf("compositeQuery=%s&timeRange=%s&startTime=%d&endTime=%d&options=%s", compositeQuery, urlEncodedTimeRange, tr.Start, tr.End, urlEncodedOptions)
}
func PrepareLinksToLogs(start, end time.Time, filterItems []v3.FilterItem) string {
// Logs list view expects time in milliseconds
tr := URLShareableTimeRange{
Start: start.UnixMilli(),
End: end.UnixMilli(),
PageSize: 100,
}
options := URLShareableOptions{
MaxLines: 2,
Format: "list",
SelectColumns: []v3.AttributeKey{},
}
period, _ := json.Marshal(tr)
urlEncodedTimeRange := url.QueryEscape(string(period))
builderQuery := v3.BuilderQuery{
DataSource: v3.DataSourceLogs,
QueryName: "A",
AggregateOperator: v3.AggregateOperatorNoOp,
AggregateAttribute: v3.AttributeKey{},
Filters: &v3.FilterSet{
Items: filterItems,
Operator: "AND",
},
Expression: "A",
Disabled: false,
Having: []v3.Having{},
StepInterval: 60,
OrderBy: []v3.OrderBy{
{
ColumnName: "timestamp",
Order: "desc",
},
},
}
urlData := URLShareableCompositeQuery{
QueryType: string(v3.QueryTypeBuilder),
Builder: URLShareableBuilderQuery{
QueryData: []LinkQuery{
{BuilderQuery: builderQuery},
},
QueryFormulas: make([]string, 0),
},
}
data, _ := json.Marshal(urlData)
compositeQuery := url.QueryEscape(url.QueryEscape(string(data)))
optionsData, _ := json.Marshal(options)
urlEncodedOptions := url.QueryEscape(string(optionsData))
return fmt.Sprintf("compositeQuery=%s&timeRange=%s&startTime=%d&endTime=%d&options=%s", compositeQuery, urlEncodedTimeRange, tr.Start, tr.End, urlEncodedOptions)
}
// The following function is used to prepare the where clause for the query
// `lbls` contains the key value pairs of the labels from the result of the query
// We iterate over the where clause and replace the labels with the actual values
// There are two cases:
// 1. The label is present in the where clause
// 2. The label is not present in the where clause
//
// Example for case 2:
// Latency by serviceName without any filter
// In this case, for each service with latency > threshold we send a notification
// The expectation will be that clicking on the related traces for service A, will
// take us to the traces page with the filter serviceName=A
// So for all the missing labels in the where clause, we add them as key = value
//
// Example for case 1:
// Severity text IN (WARN, ERROR)
// In this case, the Severity text will appear in the `lbls` if it were part of the group
// by clause, in which case we replace it with the actual value for the notification
// i.e Severity text = WARN
// If the Severity text is not part of the group by clause, then we add it as it is.
func PrepareFilters(labels map[string]string, whereClauseItems []v3.FilterItem, groupByItems []v3.AttributeKey, keys map[string]v3.AttributeKey) []v3.FilterItem {
filterItems := make([]v3.FilterItem, 0)
//delete predefined alert labels
for _, label := range PredefinedAlertLabels {
delete(labels, label)
}
added := make(map[string]struct{})
for _, item := range whereClauseItems {
exists := false
for key, value := range labels {
if item.Key.Key == key {
// if the label is present in the where clause, replace it with key = value
filterItems = append(filterItems, v3.FilterItem{
Key: item.Key,
Operator: v3.FilterOperatorEqual,
Value: value,
})
exists = true
added[key] = struct{}{}
break
}
}
if !exists {
// if there is no label for the filter item, add it as it is
filterItems = append(filterItems, item)
}
}
// if there are labels which are not part of the where clause, but
// exist in the result, then they could be part of the group by clause
for key, value := range labels {
if _, ok := added[key]; !ok {
// start by taking the attribute key from the keys map, if not present, create a new one
var attributeKey v3.AttributeKey
var attrFound bool
// as of now this logic will only apply for logs
for _, tKey := range utils.GenerateEnrichmentKeys(v3.AttributeKey{Key: key}) {
if val, ok := keys[tKey]; ok {
attributeKey = val
attrFound = true
break
}
}
// check if the attribute key is directly present, as of now this will always be false for logs
// as for logs it will be satisfied in the condition above
if !attrFound {
attributeKey, attrFound = keys[key]
}
// if the attribute key is not present, create a new one
if !attrFound {
attributeKey = v3.AttributeKey{Key: key}
}
// if there is a group by item with the same key, use that instead
for _, groupByItem := range groupByItems {
if groupByItem.Key == key {
attributeKey = groupByItem
break
}
}
filterItems = append(filterItems, v3.FilterItem{
Key: attributeKey,
Operator: v3.FilterOperatorEqual,
Value: value,
})
}
}
return filterItems
}
func PrepareParamsForTracesV5(start, end time.Time, whereClause string) url.Values {
// Traces list view expects time in nanoseconds
tr := URLShareableTimeRange{
Start: start.UnixNano(),
End: end.UnixNano(),
PageSize: 100,
}
options := URLShareableOptions{}
period, _ := json.Marshal(tr)
linkQuery := LinkQuery{
BuilderQuery: v3.BuilderQuery{
DataSource: v3.DataSourceTraces,
QueryName: "A",
AggregateOperator: v3.AggregateOperatorNoOp,
AggregateAttribute: v3.AttributeKey{},
Expression: "A",
Disabled: false,
Having: []v3.Having{},
StepInterval: 60,
},
Filter: &FilterExpression{Expression: whereClause},
}
urlData := URLShareableCompositeQuery{
QueryType: string(v3.QueryTypeBuilder),
Builder: URLShareableBuilderQuery{
QueryData: []LinkQuery{
linkQuery,
},
QueryFormulas: make([]string, 0),
},
}
data, _ := json.Marshal(urlData)
compositeQuery := url.QueryEscape(string(data))
optionsData, _ := json.Marshal(options)
params := url.Values{}
params.Set("compositeQuery", url.QueryEscape(string(data)))
params.Set("startTime", strconv.FormatInt(start, 10))
params.Set("endTime", strconv.FormatInt(end, 10))
params.Set("compositeQuery", compositeQuery)
params.Set("timeRange", string(period))
params.Set("startTime", strconv.FormatInt(tr.Start, 10))
params.Set("endTime", strconv.FormatInt(tr.End, 10))
params.Set("options", string(optionsData))
return params
}
// BuilderQueryForSignal returns the filter expression and group-by keys of the
// builder query for the given signal, or found=false when the composite query
// has no builder query for it (e.g. PromQL or ClickHouse SQL alerts).
// TODO(srikanthccv): re-visit this and support multiple queries.
func BuilderQueryForSignal(queries []qbtypes.QueryEnvelope, signal telemetrytypes.Signal) (string, []qbtypes.GroupByKey, bool) {
switch signal {
case telemetrytypes.SignalLogs:
return builderQueryForSignal[qbtypes.LogAggregation](queries, signal)
case telemetrytypes.SignalTraces:
return builderQueryForSignal[qbtypes.TraceAggregation](queries, signal)
}
return "", nil, false
}
func PrepareParamsForLogsV5(start, end time.Time, whereClause string) url.Values {
func builderQueryForSignal[T any](queries []qbtypes.QueryEnvelope, signal telemetrytypes.Signal) (string, []qbtypes.GroupByKey, bool) {
var q qbtypes.QueryBuilderQuery[T]
found := false
for _, query := range queries {
if query.Type != qbtypes.QueryTypeBuilder {
continue
}
if spec, ok := query.Spec.(qbtypes.QueryBuilderQuery[T]); ok {
q = spec
found = true
}
}
if !found || q.Signal != signal {
return "", nil, false
// Logs list view expects time in milliseconds
tr := URLShareableTimeRange{
Start: start.UnixMilli(),
End: end.UnixMilli(),
PageSize: 100,
}
filterExpr := ""
if q.Filter != nil {
filterExpr = q.Filter.Expression
options := URLShareableOptions{}
period, _ := json.Marshal(tr)
linkQuery := LinkQuery{
BuilderQuery: v3.BuilderQuery{
DataSource: v3.DataSourceLogs,
QueryName: "A",
AggregateOperator: v3.AggregateOperatorNoOp,
AggregateAttribute: v3.AttributeKey{},
Expression: "A",
Disabled: false,
Having: []v3.Having{},
StepInterval: 60,
},
Filter: &FilterExpression{Expression: whereClause},
}
return filterExpr, q.GroupBy, true
urlData := URLShareableCompositeQuery{
QueryType: string(v3.QueryTypeBuilder),
Builder: URLShareableBuilderQuery{
QueryData: []LinkQuery{
linkQuery,
},
QueryFormulas: make([]string, 0),
},
}
data, _ := json.Marshal(urlData)
compositeQuery := url.QueryEscape(string(data))
optionsData, _ := json.Marshal(options)
params := url.Values{}
params.Set("compositeQuery", compositeQuery)
params.Set("timeRange", string(period))
params.Set("startTime", strconv.FormatInt(tr.Start, 10))
params.Set("endTime", strconv.FormatInt(tr.End, 10))
params.Set("options", string(optionsData))
return params
}

View File

@@ -1,63 +0,0 @@
package contextlinks
import (
"testing"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestBuilderQueryForSignal(t *testing.T) {
logQuery := qbtypes.QueryEnvelope{
Type: qbtypes.QueryTypeBuilder,
Spec: qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]{
Name: "A",
Signal: telemetrytypes.SignalLogs,
Filter: &qbtypes.Filter{Expression: "severity_text = 'ERROR'"},
GroupBy: []qbtypes.GroupByKey{{TelemetryFieldKey: telemetrytypes.TelemetryFieldKey{Name: "service.name"}}},
},
}
traceQuery := qbtypes.QueryEnvelope{
Type: qbtypes.QueryTypeBuilder,
Spec: qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]{
Name: "B",
Signal: telemetrytypes.SignalTraces,
},
}
promQuery := qbtypes.QueryEnvelope{
Type: qbtypes.QueryTypePromQL,
Spec: qbtypes.PromQuery{Name: "C"},
}
t.Run("logs query among mixed queries", func(t *testing.T) {
filterExpr, groupBy, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{promQuery, logQuery, traceQuery}, telemetrytypes.SignalLogs)
require.True(t, found)
assert.Equal(t, "severity_text = 'ERROR'", filterExpr)
require.Len(t, groupBy, 1)
assert.Equal(t, "service.name", groupBy[0].Name)
})
t.Run("traces query without filter", func(t *testing.T) {
filterExpr, groupBy, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{logQuery, traceQuery}, telemetrytypes.SignalTraces)
require.True(t, found)
assert.Empty(t, filterExpr)
assert.Empty(t, groupBy)
})
t.Run("no builder query for signal", func(t *testing.T) {
_, _, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{traceQuery}, telemetrytypes.SignalLogs)
assert.False(t, found)
})
t.Run("no builder queries at all", func(t *testing.T) {
_, _, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{promQuery}, telemetrytypes.SignalLogs)
assert.False(t, found)
})
t.Run("unsupported signal", func(t *testing.T) {
_, _, found := BuilderQueryForSignal([]qbtypes.QueryEnvelope{logQuery}, telemetrytypes.SignalMetrics)
assert.False(t, found)
})
}

View File

@@ -1,20 +1,29 @@
package contextlinks
import (
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
)
// TODO(srikanthccv): Fix the URL management.
type URLShareableTimeRange struct {
Start int64 `json:"start"`
End int64 `json:"end"`
PageSize int64 `json:"pageSize"`
}
type FilterExpression struct {
Expression string `json:"expression,omitempty"`
}
// LinkQuery carries the only fields the explorer pages read from a shared
// link; the frontend fills in the rest of the query shape with defaults.
type Aggregation struct {
Expression string `json:"expression,omitempty"`
}
type LinkQuery struct {
DataSource string `json:"dataSource"`
Filter *FilterExpression `json:"filter,omitempty"`
v3.BuilderQuery
Filter *FilterExpression `json:"filter,omitempty"`
Aggregations []*Aggregation `json:"aggregations,omitempty"`
}
type URLShareableBuilderQuery struct {
@@ -27,4 +36,10 @@ type URLShareableCompositeQuery struct {
Builder URLShareableBuilderQuery `json:"builder"`
}
type URLShareableOptions struct {
MaxLines int `json:"maxLines"`
Format string `json:"format"`
SelectColumns []v3.AttributeKey `json:"selectColumns"`
}
var PredefinedAlertLabels = []string{ruletypes.LabelThresholdName, ruletypes.LabelSeverityName, ruletypes.LabelLastSeen}

View File

@@ -113,8 +113,6 @@ func (h *handler) GetRuleHistoryTimeline(w http.ResponseWriter, r *http.Request)
Labels: item.Labels.ToQBLabels(),
Fingerprint: item.Fingerprint,
Value: item.Value,
RelatedTracesLink: item.RelatedTracesLink,
RelatedLogsLink: item.RelatedLogsLink,
})
}
resp.Total = timelineTotal

View File

@@ -1,104 +0,0 @@
package implrulestatehistory
import (
"context"
"encoding/json"
"time"
"github.com/SigNoz/signoz/pkg/contextlinks"
qbtypes "github.com/SigNoz/signoz/pkg/types/querybuildertypes/querybuildertypesv5"
"github.com/SigNoz/signoz/pkg/types/rulestatehistorytypes"
"github.com/SigNoz/signoz/pkg/types/ruletypes"
"github.com/SigNoz/signoz/pkg/types/telemetrytypes"
"github.com/SigNoz/signoz/pkg/valuer"
)
// relatedLinkBuilder builds logs/traces explorer links that carry the rule's
// filter and the entry's labels, so a history entry can be opened in the
// explorer with the context that produced it.
type relatedLinkBuilder struct {
alertType ruletypes.AlertType
evaluation ruletypes.Evaluation
filterExpr string
groupBy []qbtypes.GroupByKey
}
// relatedLinkBuilderForRule returns nil when the rule cannot be loaded or is
// not a logs/traces rule; callers then leave the links empty.
func (m *module) relatedLinkBuilderForRule(ctx context.Context, orgID valuer.UUID, ruleID string) *relatedLinkBuilder {
id, err := valuer.NewUUID(ruleID)
if err != nil {
return nil
}
storableRule, err := m.ruleStore.GetStoredRule(ctx, orgID, id)
if err != nil {
return nil
}
rule := ruletypes.PostableRule{}
if err := json.Unmarshal([]byte(storableRule.Data), &rule); err != nil {
return nil
}
if rule.AlertType != ruletypes.AlertTypeLogs && rule.AlertType != ruletypes.AlertTypeTraces {
return nil
}
if rule.RuleCondition == nil || rule.RuleCondition.CompositeQuery == nil {
return nil
}
builder := &relatedLinkBuilder{alertType: rule.AlertType}
if rule.Evaluation != nil {
if evaluation, err := rule.Evaluation.GetEvaluation(); err == nil {
builder.evaluation = evaluation
}
}
if builder.evaluation == nil {
evalWindow := rule.EvalWindow
if evalWindow.IsZero() {
evalWindow = valuer.MustParseTextDuration("5m")
}
builder.evaluation = ruletypes.RollingWindow{EvalWindow: evalWindow}
}
signal := telemetrytypes.SignalLogs
if rule.AlertType == ruletypes.AlertTypeTraces {
signal = telemetrytypes.SignalTraces
}
// links are still built from the labels alone when the rule has no builder
// query for the signal (e.g. ClickHouse SQL alerts)
builder.filterExpr, builder.groupBy, _ = contextlinks.BuilderQueryForSignal(rule.RuleCondition.CompositeQuery.Queries, signal)
return builder
}
// queryWindow returns the range the rule evaluated when it recorded a state
// change at unixMilli.
// why are we subtracting 3 minutes?
// the query range is calculated based on the rule's evaluation window and
// evalDelay; alerts have 2 minutes delay built in, so we need to subtract
// that from the start time to get the correct query range.
func (b *relatedLinkBuilder) queryWindow(unixMilli int64) (time.Time, time.Time) {
start, end := b.evaluation.NextWindowFor(time.Unix(unixMilli/1000, 0))
return start.Add(-3 * time.Minute), end
}
// links returns the encoded logs and traces explorer query params for the
// given entry labels and time range; at most one of the two is non-empty.
func (b *relatedLinkBuilder) links(labels rulestatehistorytypes.LabelsString, start, end time.Time) (string, string) {
lbls := map[string]string{}
if err := json.Unmarshal([]byte(labels), &lbls); err != nil {
return "", ""
}
whereClause := contextlinks.PrepareFilterExpression(lbls, b.filterExpr, b.groupBy)
switch b.alertType {
case ruletypes.AlertTypeLogs:
return contextlinks.PrepareParamsForLogsV5(start, end, whereClause).Encode(), ""
case ruletypes.AlertTypeTraces:
return "", contextlinks.PrepareParamsForTracesV5(start, end, whereClause).Encode()
}
return "", ""
}

View File

@@ -13,12 +13,11 @@ import (
)
type module struct {
store rulestatehistorytypes.Store
ruleStore ruletypes.RuleStore
store rulestatehistorytypes.Store
}
func NewModule(store rulestatehistorytypes.Store, ruleStore ruletypes.RuleStore) rulestatehistory.Module {
return &module{store: store, ruleStore: ruleStore}
func NewModule(store rulestatehistorytypes.Store) rulestatehistory.Module {
return &module{store: store}
}
func (m *module) GetLastSavedRuleStateHistory(ctx context.Context, ruleID string) ([]rulestatehistorytypes.RuleStateHistory, error) {
@@ -26,19 +25,7 @@ func (m *module) GetLastSavedRuleStateHistory(ctx context.Context, ruleID string
}
func (m *module) GetHistoryTimeline(ctx context.Context, orgID valuer.UUID, ruleID string, query rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistory, uint64, error) {
items, total, err := m.store.ReadRuleStateHistoryByRuleID(ctx, orgID, ruleID, &query)
if err != nil {
return nil, 0, err
}
if builder := m.relatedLinkBuilderForRule(ctx, orgID, ruleID); builder != nil {
for idx := range items {
start, end := builder.queryWindow(items[idx].UnixMilli)
items[idx].RelatedLogsLink, items[idx].RelatedTracesLink = builder.links(items[idx].Labels, start, end)
}
}
return items, total, nil
return m.store.ReadRuleStateHistoryByRuleID(ctx, orgID, ruleID, &query)
}
func (m *module) GetHistoryFilterKeys(ctx context.Context, orgID valuer.UUID, ruleID string, query rulestatehistorytypes.Query, search string, limit int64) (*telemetrytypes.GettableFieldKeys, error) {
@@ -50,21 +37,7 @@ func (m *module) GetHistoryFilterValues(ctx context.Context, orgID valuer.UUID,
}
func (m *module) GetHistoryContributors(ctx context.Context, orgID valuer.UUID, ruleID string, query rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistoryContributor, error) {
contributors, err := m.store.ReadRuleStateHistoryTopContributorsByRuleID(ctx, orgID, ruleID, &query)
if err != nil {
return nil, err
}
if builder := m.relatedLinkBuilderForRule(ctx, orgID, ruleID); builder != nil {
// contributor counts aggregate the whole selected range, so the links
// span it too instead of a single evaluation window
start, end := time.UnixMilli(query.Start), time.UnixMilli(query.End)
for idx := range contributors {
contributors[idx].RelatedLogsLink, contributors[idx].RelatedTracesLink = builder.links(contributors[idx].Labels, start, end)
}
}
return contributors, nil
return m.store.ReadRuleStateHistoryTopContributorsByRuleID(ctx, orgID, ruleID, &query)
}
func (m *module) GetHistoryOverallStatus(ctx context.Context, ruleID string, query rulestatehistorytypes.Query) ([]rulestatehistorytypes.GettableRuleStateWindow, error) {

View File

@@ -23,8 +23,7 @@ type Module interface {
GetHistoryStats(context.Context, string, rulestatehistorytypes.Query) (rulestatehistorytypes.GettableRuleStateHistoryStats, error)
// GetHistoryTimeline returns a time-ordered list of rule state history entries and a total count
// for the given query, suitable for paginated timeline views. For logs/traces rules, each entry
// carries a related logs/traces explorer link scoped to the entry's labels and evaluation window.
// for the given query, suitable for paginated timeline views.
GetHistoryTimeline(context.Context, valuer.UUID, string, rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistory, uint64, error)
// GetHistoryFilterKeys returns the available filter keys for rule state history queries.
@@ -34,8 +33,6 @@ type Module interface {
GetHistoryFilterValues(context.Context, valuer.UUID, string, string, rulestatehistorytypes.Query, string, int64) (*telemetrytypes.GettableFieldValues, error)
// GetHistoryContributors returns the top contributors to trigger alert, for the given query.
// For logs/traces rules, each contributor carries a related logs/traces explorer link scoped
// to the contributor's labels and the queried range.
GetHistoryContributors(context.Context, valuer.UUID, string, rulestatehistorytypes.Query) ([]rulestatehistorytypes.RuleStateHistoryContributor, error)
// GetHistoryOverallStatus returns the overall status windows for rule state history,

View File

@@ -100,12 +100,27 @@ func (r *ThresholdRule) prepareParamsForLogs(ctx context.Context, ts time.Time,
return nil
}
filterExpr, groupBy, found := contextlinks.BuilderQueryForSignal(r.ruleCondition.CompositeQuery.Queries, telemetrytypes.SignalLogs)
if !found {
var q qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]
for _, query := range r.ruleCondition.CompositeQuery.Queries {
if query.Type == qbtypes.QueryTypeBuilder {
switch spec := query.Spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.LogAggregation]:
q = spec
}
}
}
if q.Signal != telemetrytypes.SignalLogs {
return nil
}
whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, groupBy)
filterExpr := ""
if q.Filter != nil && q.Filter.Expression != "" {
filterExpr = q.Filter.Expression
}
whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, q.GroupBy)
return contextlinks.PrepareParamsForLogsV5(start, end, whereClause)
}
@@ -125,12 +140,27 @@ func (r *ThresholdRule) prepareParamsForTraces(ctx context.Context, ts time.Time
return nil
}
filterExpr, groupBy, found := contextlinks.BuilderQueryForSignal(r.ruleCondition.CompositeQuery.Queries, telemetrytypes.SignalTraces)
if !found {
var q qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]
for _, query := range r.ruleCondition.CompositeQuery.Queries {
if query.Type == qbtypes.QueryTypeBuilder {
switch spec := query.Spec.(type) {
case qbtypes.QueryBuilderQuery[qbtypes.TraceAggregation]:
q = spec
}
}
}
if q.Signal != telemetrytypes.SignalTraces {
return nil
}
whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, groupBy)
filterExpr := ""
if q.Filter != nil && q.Filter.Expression != "" {
filterExpr = q.Filter.Expression
}
whereClause := contextlinks.PrepareFilterExpression(lbls.Map(), filterExpr, q.GroupBy)
return contextlinks.PrepareParamsForTracesV5(start, end, whereClause)
}

View File

@@ -4,7 +4,6 @@ import (
"context"
"fmt"
"math"
"net/url"
"strings"
"testing"
"time"
@@ -196,16 +195,10 @@ func TestPrepareParamsForLogs(t *testing.T) {
ts := time.UnixMilli(1705469040000)
params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{})
assert.Equal(t, "1705468620000", params.Get("startTime"))
assert.Equal(t, "1705468920000", params.Get("endTime"))
// the frontend decodes compositeQuery twice, so it must be escaped once
// before being encoded into the params
assert.Contains(t, params.Encode(), "compositeQuery=%257B")
compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))
assert.NoError(t, err)
assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"logs","filter":{}}],"queryFormulas":[]}}`, compositeQuery)
params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{}).Encode()
assert.Contains(t, params, "&timeRange=%7B%22start%22%3A1705468620000%2C%22end%22%3A1705468920000%2C%22pageSize%22%3A100%7D")
assert.Contains(t, params, "&startTime=1705468620000")
assert.Contains(t, params, "&endTime=1705468920000")
}
func TestPrepareParamsForLogsFilterExpression(t *testing.T) {
@@ -264,13 +257,8 @@ func TestPrepareParamsForLogsFilterExpression(t *testing.T) {
ts := time.UnixMilli(1753527163000)
params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{})
assert.Equal(t, "1753526700000", params.Get("startTime"))
assert.Equal(t, "1753527000000", params.Get("endTime"))
compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))
assert.NoError(t, err)
assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"logs","filter":{"expression":"service.name EXISTS"}}],"queryFormulas":[]}}`, compositeQuery)
params := rule.prepareParamsForLogs(context.Background(), ts, ruletypes.Labels{}).Encode()
assert.Contains(t, params, "compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522queryName%2522%253A%2522A%2522%252C%2522stepInterval%2522%253A60%252C%2522dataSource%2522%253A%2522logs%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522key%2522%253A%2522%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522type%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522isJSON%2522%253Afalse%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522limit%2522%253A0%252C%2522offset%2522%253A0%252C%2522pageSize%2522%253A0%252C%2522ShiftBy%2522%253A0%252C%2522IsAnomaly%2522%253Afalse%252C%2522QueriesUsedInFormula%2522%253Anull%252C%2522filter%2522%253A%257B%2522expression%2522%253A%2522service.name%2BEXISTS%2522%257D%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%257D&endTime=1753527000000&options=%7B%22maxLines%22%3A0%2C%22format%22%3A%22%22%2C%22selectColumns%22%3Anull%7D&startTime=1753526700000&timeRange=%7B%22start%22%3A1753526700000%2C%22end%22%3A1753527000000%2C%22pageSize%22%3A100%7D")
}
func TestPrepareParamsForTracesFilterExpression(t *testing.T) {
@@ -329,13 +317,8 @@ func TestPrepareParamsForTracesFilterExpression(t *testing.T) {
ts := time.UnixMilli(1753527163000)
params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{})
assert.Equal(t, "1753526700000000000", params.Get("startTime"))
assert.Equal(t, "1753527000000000000", params.Get("endTime"))
compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))
assert.NoError(t, err)
assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"traces","filter":{"expression":"service.name EXISTS"}}],"queryFormulas":[]}}`, compositeQuery)
params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{}).Encode()
assert.Contains(t, params, "compositeQuery=%257B%2522queryType%2522%253A%2522builder%2522%252C%2522builder%2522%253A%257B%2522queryData%2522%253A%255B%257B%2522queryName%2522%253A%2522A%2522%252C%2522stepInterval%2522%253A60%252C%2522dataSource%2522%253A%2522traces%2522%252C%2522aggregateOperator%2522%253A%2522noop%2522%252C%2522aggregateAttribute%2522%253A%257B%2522key%2522%253A%2522%2522%252C%2522dataType%2522%253A%2522%2522%252C%2522type%2522%253A%2522%2522%252C%2522isColumn%2522%253Afalse%252C%2522isJSON%2522%253Afalse%257D%252C%2522expression%2522%253A%2522A%2522%252C%2522disabled%2522%253Afalse%252C%2522limit%2522%253A0%252C%2522offset%2522%253A0%252C%2522pageSize%2522%253A0%252C%2522ShiftBy%2522%253A0%252C%2522IsAnomaly%2522%253Afalse%252C%2522QueriesUsedInFormula%2522%253Anull%252C%2522filter%2522%253A%257B%2522expression%2522%253A%2522service.name%2BEXISTS%2522%257D%257D%255D%252C%2522queryFormulas%2522%253A%255B%255D%257D%257D&endTime=1753527000000000000&options=%7B%22maxLines%22%3A0%2C%22format%22%3A%22%22%2C%22selectColumns%22%3Anull%7D&startTime=1753526700000000000&timeRange=%7B%22start%22%3A1753526700000000000%2C%22end%22%3A1753527000000000000%2C%22pageSize%22%3A100%7D")
}
func TestPrepareParamsForTraces(t *testing.T) {
@@ -392,16 +375,10 @@ func TestPrepareParamsForTraces(t *testing.T) {
ts := time.UnixMilli(1705469040000)
params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{})
assert.Equal(t, "1705468620000000000", params.Get("startTime"))
assert.Equal(t, "1705468920000000000", params.Get("endTime"))
// the frontend decodes compositeQuery twice, so it must be escaped once
// before being encoded into the params
assert.Contains(t, params.Encode(), "compositeQuery=%257B")
compositeQuery, err := url.QueryUnescape(params.Get("compositeQuery"))
assert.NoError(t, err)
assert.JSONEq(t, `{"queryType":"builder","builder":{"queryData":[{"dataSource":"traces","filter":{}}],"queryFormulas":[]}}`, compositeQuery)
params := rule.prepareParamsForTraces(context.Background(), ts, ruletypes.Labels{}).Encode()
assert.Contains(t, params, "&timeRange=%7B%22start%22%3A1705468620000000000%2C%22end%22%3A1705468920000000000%2C%22pageSize%22%3A100%7D")
assert.Contains(t, params, "&startTime=1705468620000000000")
assert.Contains(t, params, "&endTime=1705468920000000000")
}
func TestThresholdRuleLabelNormalization(t *testing.T) {

View File

@@ -159,7 +159,7 @@ func NewModules(
ServiceAccount: serviceAccount,
ServiceAccountGetter: serviceAccountGetter,
LogsPipeline: impllogspipeline.NewModule(sqlstore),
RuleStateHistory: implrulestatehistory.NewModule(implrulestatehistory.NewStore(telemetryStore, telemetryMetadataStore, providerSettings.Logger), ruleStore),
RuleStateHistory: implrulestatehistory.NewModule(implrulestatehistory.NewStore(telemetryStore, telemetryMetadataStore, providerSettings.Logger)),
CloudIntegration: cloudIntegrationModule,
TraceDetail: impltracedetail.NewModule(impltracedetail.NewTraceStore(telemetryStore), providerSettings, config.TraceDetail),
SpanMapper: implspanmapper.NewModule(implspanmapper.NewStore(sqlstore), fl),

View File

@@ -140,49 +140,6 @@ type seriesLookup struct {
// maps a variable to its series keys, letting evaluation iterate a single
// variable's series directly.
variableToSeriesKeys map[string][]string
// seriesKey -> label set encoded as id pairs, used as the "subset" side of isSubset
// during dedup and evaluation so label comparison is an integer compare.
encodedLabels map[string][]encodedLabel
}
// encodedLabel is a label's key name and value replaced with stable integer ids by an
// encodedLabelsBuilder, so comparing two encodedLabels is an integer compare rather than
// a per-byte string compare (runtime.efaceeq/strequal/memeqbody).
type encodedLabel struct {
keyID uint32
valueID uint32
}
// encodedLabelsBuilder stores a stable uint32 id for each distinct label key name and label
// value (dictionary encoding). Populated single-threaded in buildSeriesLookup and
// read-only thereafter, so the parallel evaluation phase never writes to it.
type encodedLabelsBuilder struct {
encodedKeyIDs map[string]uint32
encodedValueIDs map[any]uint32
}
func newEncodedLabelsBuilder() *encodedLabelsBuilder {
return &encodedLabelsBuilder{encodedKeyIDs: map[string]uint32{}, encodedValueIDs: map[any]uint32{}}
}
func (b *encodedLabelsBuilder) encode(labels []*Label) []encodedLabel {
out := make([]encodedLabel, len(labels))
for i, label := range labels {
encodedKey, ok := b.encodedKeyIDs[label.Key.Name]
if !ok {
encodedKey = uint32(len(b.encodedKeyIDs)) // acts as a sequential counter.
b.encodedKeyIDs[label.Key.Name] = encodedKey
}
encodedValue, ok := b.encodedValueIDs[label.Value]
if !ok {
encodedValue = uint32(len(b.encodedValueIDs)) // acts as a sequential counter.
b.encodedValueIDs[label.Value] = encodedValue
}
out[i] = encodedLabel{keyID: encodedKey, valueID: encodedValue}
}
return out
}
// FormulaEvaluator handles formula evaluation b/w time series from different aggregations
@@ -342,7 +299,7 @@ func (fe *FormulaEvaluator) EvaluateFormula(timeSeriesData map[string]*TimeSerie
// Work per label-set is cheap enough that spawning a goroutine per item
// costs more in scheduler signaling than it saves in parallelism.
const numWorkers = 4
workCh := make(chan labelSetCandidate, len(uniqueLabelSets))
workCh := make(chan []*Label, len(uniqueLabelSets))
resultChan := make(chan *TimeSeries, len(uniqueLabelSets))
var wg sync.WaitGroup
@@ -391,12 +348,8 @@ func (fe *FormulaEvaluator) buildSeriesLookup(timeSeriesData map[string]*TimeSer
seriesMetadata: make(map[string]*TimeSeries),
variableToSeriesKeys: make(map[string][]string),
encodedLabels: make(map[string][]encodedLabel),
}
encodedLabelsBuilder := newEncodedLabelsBuilder()
for variable, aggRef := range fe.aggRefs {
// We are only interested in the time series data for the queries that are
// involved in the formula expression.
@@ -446,7 +399,6 @@ func (fe *FormulaEvaluator) buildSeriesLookup(timeSeriesData map[string]*TimeSer
if _, exists := lookup.data[seriesKey]; !exists {
lookup.data[seriesKey] = make(map[int64]float64, len(series.Values))
lookup.seriesMetadata[seriesKey] = series
lookup.encodedLabels[seriesKey] = encodedLabelsBuilder.encode(series.Labels)
lookup.variableToSeriesKeys[variable] = append(lookup.variableToSeriesKeys[variable], seriesKey)
}
@@ -509,74 +461,58 @@ func (fe *FormulaEvaluator) buildSeriesKey(variable string, seriesIndex int, lab
// The result of any expression that uses the series with `{"service": "frontend", "operation": "GET /api"}`
// and `{"service": "frontend"}` would be the series with `{"service": "frontend", "operation": "GET /api"}`
// So, we create a set of labels sets that can be termed as candidates for the final result.
func (fe *FormulaEvaluator) findUniqueLabelSets(lookup *seriesLookup) []labelSetCandidate {
// original labels (for the result series) paired with their encoded form (for the
// subset comparison).
type labelSet struct {
labels []*Label
encoded []encodedLabel
}
allLabelSets := make([]labelSet, 0, len(lookup.seriesMetadata))
for key, series := range lookup.seriesMetadata {
allLabelSets = append(allLabelSets, labelSet{labels: series.Labels, encoded: lookup.encodedLabels[key]})
func (fe *FormulaEvaluator) findUniqueLabelSets(lookup *seriesLookup) [][]*Label {
var allLabelSets [][]*Label
// Collect all label sets from series metadata
for _, series := range lookup.seriesMetadata {
allLabelSets = append(allLabelSets, series.Labels)
}
// sort the label sets by the number of labels in descending order.
slices.SortFunc(allLabelSets, func(i, j labelSet) int {
if len(i.labels) > len(j.labels) {
// sort the label sets by the number of labels in descending order
slices.SortFunc(allLabelSets, func(i, j []*Label) int {
if len(i) > len(j) {
return -1
}
if len(i.labels) < len(j.labels) {
if len(i) < len(j) {
return 1
}
return 0
})
// Find unique label sets using integer-id label comparison.
var uniqueSets []labelSetCandidate
// Find unique label sets using proper label comparison
var uniqueSets [][]*Label
var uniqueMaps []map[string]any
for _, labelSet := range allLabelSets {
isUnique := true
for _, uniqueSet := range uniqueSets {
if isSubset(uniqueSet.encodedKeyToEncodedValueMap, labelSet.encoded) {
for _, uniqueMap := range uniqueMaps {
if isSubset(uniqueMap, labelSet) {
isUnique = false
break
}
}
if isUnique {
uniqueSets = append(uniqueSets, labelSetCandidate{
labels: labelSet.labels,
encodedKeyToEncodedValueMap: encodedLabelsToMap(labelSet.encoded),
})
uniqueSets = append(uniqueSets, labelSet)
uniqueMaps = append(uniqueMaps, labelsToMap(labelSet))
}
}
return uniqueSets
}
// labelSetCandidate is a maximal label set kept by findUniqueLabelSets: the original
// labels (preserved for the result series) plus a keyID->valueID map used as the
// "superset" when matching series during evaluation.
type labelSetCandidate struct {
labels []*Label
encodedKeyToEncodedValueMap map[uint32]uint32
}
func encodedLabelsToMap(labels []encodedLabel) map[uint32]uint32 {
m := make(map[uint32]uint32, len(labels))
func labelsToMap(labels []*Label) map[string]any {
m := make(map[string]any, len(labels))
for _, label := range labels {
m[label.keyID] = label.valueID
m[label.Key.Name] = label.Value
}
return m
}
// isSubset reports whether every label in subset is present with the same value in
// supersetMap (i.e. subset ⊆ superset).
func isSubset(supersetMap map[uint32]uint32, subset []encodedLabel) bool {
func isSubset(supersetMap map[string]any, subset []*Label) bool {
for _, label := range subset {
// each key and value of string/any type in the overall label set in the whole result
// has a corresponding unique uint32 assigned to it by buildSeriesLookup, which helps us
// do a simple integer comparison in place of a much more expensive str/any comparison.
if valID, ok := supersetMap[label.keyID]; !ok || valID != label.valueID {
if val, ok := supersetMap[label.Key.Name]; !ok || val != label.Value {
return false
}
}
@@ -584,7 +520,7 @@ func isSubset(supersetMap map[uint32]uint32, subset []encodedLabel) bool {
}
// evaluateForLabelSet performs formula evaluation for a specific label set.
func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels labelSetCandidate, lookup *seriesLookup) *TimeSeries {
func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels []*Label, lookup *seriesLookup) *TimeSeries {
// Find matching series for each variable
variableData := make(map[string]map[int64]float64)
// not every series would have a value for every timestamp
@@ -592,14 +528,14 @@ func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels labelSetCandidate,
// for the variable
var allTimestamps = make(map[int64]struct{})
// target.encodedKeyToEncodedValueMap is the superset map, precomputed once in
// findUniqueLabelSets and reused across every series comparison below.
targetMap := targetLabels.encodedKeyToEncodedValueMap
// targetLabels is fixed for this call, so build its lookup once and reuse it
// across every series comparison below.
targetMap := labelsToMap(targetLabels)
for variable := range fe.aggRefs {
// only this variable's series.
for _, seriesKey := range lookup.variableToSeriesKeys[variable] {
if isSubset(targetMap, lookup.encodedLabels[seriesKey]) {
if isSubset(targetMap, lookup.seriesMetadata[seriesKey].Labels) {
if timestampData, exists := lookup.data[seriesKey]; exists {
variableData[variable] = timestampData
// Collect all timestamps
@@ -687,8 +623,8 @@ func (fe *FormulaEvaluator) evaluateForLabelSet(targetLabels labelSetCandidate,
}
// Preserve original label structure and metadata
resultLabels := make([]*Label, len(targetLabels.labels))
copy(resultLabels, targetLabels.labels)
resultLabels := make([]*Label, len(targetLabels))
copy(resultLabels, targetLabels)
return &TimeSeries{
Labels: resultLabels,

View File

@@ -22,8 +22,6 @@ type GettableRuleStateHistory struct {
Labels []*qbtypes.Label `json:"labels" required:"true"`
Fingerprint uint64 `json:"fingerprint" required:"true"`
Value float64 `json:"value" required:"true"`
RelatedTracesLink string `json:"relatedTracesLink,omitempty"`
RelatedLogsLink string `json:"relatedLogsLink,omitempty"`
}
type GettableRuleStateHistoryContributor struct {

View File

@@ -76,9 +76,6 @@ type RuleStateHistory struct {
Labels LabelsString `ch:"labels"`
Fingerprint uint64 `ch:"fingerprint"`
Value float64 `ch:"value"`
RelatedTracesLink string
RelatedLogsLink string
}
type RuleStateHistoryContributor struct {

View File

@@ -14,11 +14,6 @@ dotenv.config({ path: path.resolve(__dirname, '.env.local'), override: true });
export default defineConfig({
testDir: './tests',
// Temporarily excluded: the V1 -> V2 dashboard migration changes the
// behaviour the dashboards specs assert against, so they fail as written.
// Remove this once they are updated for the V2 dashboard.
testIgnore: ['**/tests/dashboards/**'],
// All Playwright output lands under artifacts/. One subdir per reporter
// plus results/ for per-test artifacts (traces/screenshots/videos).
// CI can archive the whole dir with `tar czf artifacts.tgz tests/e2e/artifacts`.

View File

@@ -1,8 +1,6 @@
import base64
import json
import time
import urllib.parse
import uuid
from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from http import HTTPStatus
@@ -60,97 +58,6 @@ def create_alert_rule(signoz: types.SigNoz, get_token: Callable[[str, str], str]
logger.error("Error deleting rule: %s", {"rule_id": rule_id, "error": e})
@pytest.fixture(name="create_alert_rule_with_channel", scope="function")
def create_alert_rule_with_channel(
notification_channel: types.TestContainerDocker,
create_webhook_notification_channel: Callable[[str, str, dict, bool], str],
create_alert_rule: Callable[[dict], str],
) -> Callable[[str], str]:
"""Creates the rule from the given testdata path with a throwaway webhook channel."""
def _create_alert_rule_with_channel(rule_path: str) -> str:
channel_name = str(uuid.uuid4())
create_webhook_notification_channel(
channel_name=channel_name,
webhook_url=notification_channel.container_configs["8080"].get(f"/alert/{channel_name}"),
http_config={},
send_resolved=False,
)
with open(get_testdata_file_path(rule_path), encoding="utf-8") as f:
rule_data = json.loads(f.read())
update_rule_channel_name(rule_data, channel_name)
return create_alert_rule(rule_data)
return _create_alert_rule_with_channel
def labels_to_map(labels: list[dict]) -> dict[str, str]:
"""Converts the label list shape of the v2 rule history APIs to a plain map."""
return {label["key"]["name"]: label["value"] for label in labels or []}
def parse_related_link(link: str) -> dict:
"""Parses the query params of a related logs/traces explorer link."""
params = urllib.parse.parse_qs(link)
for key in ("compositeQuery", "startTime", "endTime"):
assert key in params, f"related link is missing param {key}, link: {link}"
return {
"start": int(params["startTime"][0]),
"end": int(params["endTime"][0]),
# the compositeQuery value is query-escaped before being encoded into
# the params, so it needs one more unquote than the other params
"composite_query": json.loads(urllib.parse.unquote_plus(params["compositeQuery"][0])),
}
def assert_related_link_query(link: dict, data_source: str, expression_pieces: list[str]) -> None:
query_data = link["composite_query"]["builder"]["queryData"]
assert len(query_data) == 1
assert query_data[0]["dataSource"] == data_source
expression = query_data[0]["filter"]["expression"]
for piece in expression_pieces:
assert piece in expression, f"expected {piece} in link filter expression: {expression}"
def wait_for_firing_timeline_entry(signoz: types.SigNoz, token: str, rule_id: str, start_ms: int, wait_seconds: int = 60) -> tuple[dict, int]:
"""Polls the v2 timeline API until the rule records a firing entry.
Rules in the alert scenarios evaluate every 15s and their data is set up to
fire on the first evaluation, so the default wait leaves plenty of slack.
Returns the firing entry and the end of the queried range.
"""
deadline = time.time() + wait_seconds
items = []
while time.time() < deadline:
end_ms = int(datetime.now(tz=UTC).timestamp() * 1000) + 60_000
response = requests.get(
signoz.self.host_configs["8080"].get(f"/api/v2/rules/{rule_id}/history/timeline"),
params={"start": start_ms, "end": end_ms, "limit": 50, "order": "desc"},
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.OK, f"Failed to get rule history timeline, api returned {response.status_code} with response: {response.text}"
items = response.json()["data"]["items"] or []
firing = [item for item in items if item["state"] == "firing"]
if len(firing) > 0:
return (firing[0], end_ms)
time.sleep(2)
raise AssertionError(f"No firing entry recorded in rule state history within {wait_seconds}s, items: {items}")
def get_rule_history_top_contributors(signoz: types.SigNoz, token: str, rule_id: str, start_ms: int, end_ms: int) -> list[dict]:
response = requests.get(
signoz.self.host_configs["8080"].get(f"/api/v2/rules/{rule_id}/history/top_contributors"),
params={"start": start_ms, "end": end_ms},
headers={"Authorization": f"Bearer {token}"},
timeout=5,
)
assert response.status_code == HTTPStatus.OK, f"Failed to get rule history top contributors, api returned {response.status_code} with response: {response.text}"
return response.json()["data"] or []
@pytest.fixture(name="insert_alert_data", scope="function")
def insert_alert_data(
insert_metrics: Callable[[list[Metrics]], None],

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 30,
"matchType": "at_least_once",
"op": "above",
"matchType": "1",
"op": "1",
"channels": [
"test channel"
]
@@ -18,8 +18,8 @@
{
"name": "warning",
"target": 20,
"matchType": "at_least_once",
"op": "above",
"matchType": "1",
"op": "1",
"channels": [
"test channel"
]
@@ -27,8 +27,8 @@
{
"name": "info",
"target": 10,
"matchType": "at_least_once",
"op": "above",
"matchType": "1",
"op": "1",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "at_least_once",
"op": "above",
"matchType": "1",
"op": "1",
"channels": [
"test channel"
]

View File

@@ -1,8 +0,0 @@
{ "timestamp": "2026-01-29T10:00:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:00:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:01:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:02:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:02:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:03:00.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }
{ "timestamp": "2026-01-29T10:03:30.000000Z", "resources": { "service.name": "payment-service" }, "attributes": { "code.file": "payment_handler.py" }, "body": "payment success", "severity_text": "INFO" }

View File

@@ -1,73 +0,0 @@
{
"alert": "rule_state_history_logs",
"ruleType": "threshold_rule",
"alertType": "LOGS_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 0,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "graph",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "logs",
"filter": {
"expression": "body CONTAINS 'payment success'"
},
"groupBy": [
{
"name": "service.name",
"fieldContext": "resource",
"fieldDataType": "string"
}
],
"aggregations": [
{
"expression": "count()"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"version": "v5",
"schemaVersion": "v2alpha1"
}

View File

@@ -1,8 +0,0 @@
{ "timestamp": "2026-01-29T10:00:00.000000Z", "duration": "PT0.8S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a1", "span_id": "b1b2c3d4e5f6a7b8", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }
{ "timestamp": "2026-01-29T10:00:30.000000Z", "duration": "PT0.9S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a2", "span_id": "b2b3c4d5e6f7a8b9", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }
{ "timestamp": "2026-01-29T10:01:00.000000Z", "duration": "PT1.1S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a3", "span_id": "b3b4c5d6e7f8a9b0", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }
{ "timestamp": "2026-01-29T10:01:30.000000Z", "duration": "PT0.7S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a4", "span_id": "b4b5c6d7e8f9a0b1", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }
{ "timestamp": "2026-01-29T10:02:00.000000Z", "duration": "PT1.3S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a5", "span_id": "b5b6c7d8e9f0a1b2", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }
{ "timestamp": "2026-01-29T10:02:30.000000Z", "duration": "PT0.6S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a6", "span_id": "b6b7c8d9e0f1a2b3", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }
{ "timestamp": "2026-01-29T10:03:00.000000Z", "duration": "PT1.0S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a7", "span_id": "b7b8c9d0e1f2a3b4", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }
{ "timestamp": "2026-01-29T10:03:30.000000Z", "duration": "PT0.8S", "trace_id": "591f6d3d6b0a1f9e8a71b2c3d4e5f6a8", "span_id": "b8b9c0d1e2f3a4b5", "parent_span_id": "", "name": "POST /order", "kind": 2, "status_code": 1, "status_message": "", "resources": { "deployment.environment": "production", "service.name": "order-service", "os.type": "linux", "host.name": "linux-000" }, "attributes": { "net.transport": "IP.TCP", "http.scheme": "http", "http.user_agent": "Integration Test", "http.request.method": "POST", "http.response.status_code": "200", "http.request.path": "/order" } }

View File

@@ -1,73 +0,0 @@
{
"alert": "rule_state_history_traces",
"ruleType": "threshold_rule",
"alertType": "TRACES_BASED_ALERT",
"condition": {
"thresholds": {
"kind": "basic",
"spec": [
{
"name": "critical",
"target": 0,
"matchType": "at_least_once",
"op": "above",
"channels": [
"test channel"
]
}
]
},
"compositeQuery": {
"queryType": "builder",
"panelType": "graph",
"queries": [
{
"type": "builder_query",
"spec": {
"name": "A",
"signal": "traces",
"filter": {
"expression": "http.request.path = '/order'"
},
"groupBy": [
{
"name": "service.name",
"fieldContext": "resource",
"fieldDataType": "string"
}
],
"aggregations": [
{
"expression": "count()"
}
]
}
}
]
},
"selectedQueryName": "A"
},
"evaluation": {
"kind": "rolling",
"spec": {
"evalWindow": "5m0s",
"frequency": "15s"
}
},
"labels": {},
"annotations": {
"description": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})",
"summary": "This alert is fired when the defined metric (current value: {{$value}}) crosses the threshold ({{$threshold}})"
},
"notificationSettings": {
"groupBy": [],
"usePolicy": false,
"renotify": {
"enabled": false,
"interval": "30m",
"alertStates": []
}
},
"version": "v5",
"schemaVersion": "v2alpha1"
}

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "all_the_times",
"op": "above",
"matchType": "2",
"op": "1",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "at_least_once",
"op": "above",
"matchType": "1",
"op": "1",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 1,
"matchType": "on_average",
"op": "above",
"matchType": "3",
"op": "1",
"channels": [
"test channel"
],

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 5,
"matchType": "in_total",
"op": "above",
"matchType": "4",
"op": "1",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "last",
"op": "above",
"matchType": "5",
"op": "1",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "all_the_times",
"op": "below",
"matchType": "2",
"op": "2",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "at_least_once",
"op": "below",
"matchType": "1",
"op": "2",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "on_average",
"op": "below",
"matchType": "3",
"op": "2",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "in_total",
"op": "below",
"matchType": "4",
"op": "2",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "last",
"op": "below",
"matchType": "5",
"op": "2",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "all_the_times",
"op": "equal",
"matchType": "2",
"op": "3",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "at_least_once",
"op": "equal",
"matchType": "1",
"op": "3",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "on_average",
"op": "equal",
"matchType": "3",
"op": "3",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "in_total",
"op": "equal",
"matchType": "4",
"op": "3",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "last",
"op": "equal",
"matchType": "5",
"op": "3",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "all_the_times",
"op": "not_equal",
"matchType": "2",
"op": "4",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 5,
"matchType": "at_least_once",
"op": "not_equal",
"matchType": "1",
"op": "4",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "on_average",
"op": "not_equal",
"matchType": "3",
"op": "4",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "in_total",
"op": "not_equal",
"matchType": "4",
"op": "4",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 10,
"matchType": "last",
"op": "not_equal",
"matchType": "5",
"op": "4",
"channels": [
"test channel"
]

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 1.5,
"matchType": "at_least_once",
"op": "above",
"matchType": "1",
"op": "1",
"channels": [
"test channel"
],

View File

@@ -9,8 +9,8 @@
{
"name": "critical",
"target": 3,
"matchType": "at_least_once",
"op": "above",
"matchType": "1",
"op": "1",
"channels": [
"test channel"
],

Some files were not shown because too many files have changed in this diff Show More