feat(alerting): server-side state+severity filters, ButtonGroup filter UI
Backend: `GET /environments/{envSlug}/alerts` now accepts optional multi-value
`state=…` and `severity=…` query params. Filters are pushed down to
PostgresAlertInstanceRepository, which appends `AND state::text = ANY(?)` /
`AND severity::text = ANY(?)` to the inbox query (null/empty = no filter).
`AlertInstanceRepository.listForInbox` gained a 7-arg overload; the old 5-arg
form is preserved as a default delegate so existing callers (evaluator,
AlertingFullLifecycleIT, PostgresAlertInstanceRepositoryIT) compile unchanged.
`InAppInboxQuery.listInbox` also has a new filtered overload.
UI: InboxPage severity filter migrated from `SegmentedTabs` (single-select,
no color cues) to `ButtonGroup` (multi-select with severity-coloured dots),
matching the topnavbar status-filter pattern. `useAlerts` forwards the
filters as query params and cache-keys on the filter tuple so each combo
is independently cached.
Unit + hook tests updated to the new contract (5 UI tests + 8 Java unit
tests passing). OpenAPI types regenerated from the fresh local backend.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -22,16 +22,32 @@ describe('useAlerts', () => {
|
||||
useEnvironmentStore.setState({ environment: 'dev' });
|
||||
});
|
||||
|
||||
it('fetches up to 200 alerts for selected env (no server-side filter params)', async () => {
|
||||
// Backend AlertController.list accepts only `limit`; state/severity are
|
||||
// dropped server-side. We therefore fetch once per env and filter
|
||||
// client-side via react-query `select`.
|
||||
it('forwards state + severity filters to the server as query params', async () => {
|
||||
(apiClient.GET as any).mockResolvedValue({ data: [], error: null });
|
||||
const { result } = renderHook(
|
||||
() => useAlerts({ state: 'FIRING', severity: ['CRITICAL', 'WARNING'] }),
|
||||
{ wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(apiClient.GET).toHaveBeenCalledWith(
|
||||
'/environments/{envSlug}/alerts',
|
||||
expect.objectContaining({
|
||||
params: expect.objectContaining({
|
||||
path: { envSlug: 'dev' },
|
||||
query: {
|
||||
limit: 200,
|
||||
state: ['FIRING'],
|
||||
severity: ['CRITICAL', 'WARNING'],
|
||||
},
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('omits state + severity when no filter is set', async () => {
|
||||
(apiClient.GET as any).mockResolvedValue({ data: [], error: null });
|
||||
const { result } = renderHook(() => useAlerts(), { wrapper });
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
expect(apiClient.GET).toHaveBeenCalledWith(
|
||||
'/environments/{envSlug}/alerts',
|
||||
expect.objectContaining({
|
||||
@@ -43,21 +59,19 @@ describe('useAlerts', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('applies state + severity filters client-side via select', async () => {
|
||||
it('still applies ruleId client-side via select', async () => {
|
||||
const dataset = [
|
||||
{ id: '1', state: 'FIRING', severity: 'CRITICAL', title: 'a' },
|
||||
{ id: '2', state: 'FIRING', severity: 'WARNING', title: 'b' },
|
||||
{ id: '3', state: 'ACKNOWLEDGED', severity: 'CRITICAL', title: 'c' },
|
||||
{ id: '4', state: 'RESOLVED', severity: 'INFO', title: 'd' },
|
||||
{ id: '1', ruleId: 'R1', state: 'FIRING', severity: 'WARNING', title: 'a' },
|
||||
{ id: '2', ruleId: 'R2', state: 'FIRING', severity: 'WARNING', title: 'b' },
|
||||
];
|
||||
(apiClient.GET as any).mockResolvedValue({ data: dataset, error: null });
|
||||
const { result } = renderHook(
|
||||
() => useAlerts({ state: ['FIRING'], severity: ['CRITICAL', 'WARNING'] }),
|
||||
() => useAlerts({ ruleId: 'R2' }),
|
||||
{ wrapper },
|
||||
);
|
||||
await waitFor(() => expect(result.current.isSuccess).toBe(true));
|
||||
const ids = (result.current.data ?? []).map((a: any) => a.id);
|
||||
expect(ids).toEqual(['1', '2']);
|
||||
expect(ids).toEqual(['2']);
|
||||
});
|
||||
|
||||
it('does not fetch when no env is selected', () => {
|
||||
|
||||
@@ -30,51 +30,45 @@ function toArray<T>(v: T | T[] | undefined): T[] | undefined {
|
||||
|
||||
/** List alert instances in the current env. Polls every 30s (pauses in background).
|
||||
*
|
||||
* The backend's `AlertController.list` accepts only `limit` — `state` /
|
||||
* `severity` query params are dropped. We fetch up to 200 alerts once per
|
||||
* env (cached under a stable key) and apply filters client-side via
|
||||
* react-query's `select` so filter switches on the All / History / Inbox
|
||||
* pages are instant and don't each fire their own request. True server-side
|
||||
* filtering needs a backend change (follow-up).
|
||||
* State + severity filters are server-side (`state=FIRING&state=ACKNOWLEDGED&severity=CRITICAL`).
|
||||
* `ruleId` is not a backend param and is still applied via react-query `select`.
|
||||
* Each unique (state, severity) combo gets its own cache entry so the server
|
||||
* honors the filter and stays as the source of truth.
|
||||
*/
|
||||
export function useAlerts(filter: AlertsFilter = {}) {
|
||||
const env = useSelectedEnv();
|
||||
const fetchLimit = 200;
|
||||
const stateSet = filter.state === undefined
|
||||
? undefined
|
||||
: new Set(toArray(filter.state));
|
||||
const severitySet = filter.severity === undefined
|
||||
? undefined
|
||||
: new Set(toArray(filter.severity));
|
||||
const applyLimit = filter.limit;
|
||||
const fetchLimit = Math.min(filter.limit ?? 200, 200);
|
||||
const stateArr = toArray(filter.state);
|
||||
const severityArr = toArray(filter.severity);
|
||||
const ruleIdFilter = filter.ruleId;
|
||||
|
||||
// Stable, serialisable key — arrays must be sorted so order doesn't create cache misses.
|
||||
const stateKey = stateArr ? [...stateArr].sort() : null;
|
||||
const severityKey = severityArr ? [...severityArr].sort() : null;
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['alerts', env, 'list', fetchLimit],
|
||||
queryKey: ['alerts', env, 'list', fetchLimit, stateKey, severityKey],
|
||||
enabled: !!env,
|
||||
refetchInterval: 30_000,
|
||||
refetchIntervalInBackground: false,
|
||||
queryFn: async () => {
|
||||
if (!env) throw new Error('no env');
|
||||
const query: Record<string, unknown> = { limit: fetchLimit };
|
||||
if (stateArr && stateArr.length > 0) query.state = stateArr;
|
||||
if (severityArr && severityArr.length > 0) query.severity = severityArr;
|
||||
const { data, error } = await apiClient.GET(
|
||||
'/environments/{envSlug}/alerts',
|
||||
{
|
||||
params: {
|
||||
path: { envSlug: env },
|
||||
query: { limit: fetchLimit },
|
||||
query,
|
||||
},
|
||||
} as any,
|
||||
);
|
||||
if (error) throw error;
|
||||
return data as AlertDto[];
|
||||
},
|
||||
select: (all) => {
|
||||
let out = all;
|
||||
if (stateSet) out = out.filter((a) => a.state && stateSet.has(a.state));
|
||||
if (severitySet) out = out.filter((a) => a.severity && severitySet.has(a.severity));
|
||||
if (ruleIdFilter) out = out.filter((a) => a.ruleId === ruleIdFilter);
|
||||
if (applyLimit !== undefined) out = out.slice(0, applyLimit);
|
||||
return out;
|
||||
},
|
||||
select: (all) => ruleIdFilter ? all.filter((a) => a.ruleId === ruleIdFilter) : all,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
2
ui/src/api/schema.d.ts
vendored
2
ui/src/api/schema.d.ts
vendored
@@ -7213,6 +7213,8 @@ export interface operations {
|
||||
query: {
|
||||
env: components["schemas"]["Environment"];
|
||||
limit?: number;
|
||||
state?: ("PENDING" | "FIRING" | "ACKNOWLEDGED" | "RESOLVED")[];
|
||||
severity?: ("CRITICAL" | "WARNING" | "INFO")[];
|
||||
};
|
||||
header?: never;
|
||||
path?: never;
|
||||
|
||||
@@ -2,9 +2,9 @@ import { useMemo, useState } from 'react';
|
||||
import { Link } from 'react-router';
|
||||
import { Inbox } from 'lucide-react';
|
||||
import {
|
||||
Button, DataTable, EmptyState, SegmentedTabs, useToast,
|
||||
Button, ButtonGroup, DataTable, EmptyState, useToast,
|
||||
} from '@cameleer/design-system';
|
||||
import type { Column } from '@cameleer/design-system';
|
||||
import type { ButtonGroupItem, Column } from '@cameleer/design-system';
|
||||
import { PageLoader } from '../../components/PageLoader';
|
||||
import { SeverityBadge } from '../../components/SeverityBadge';
|
||||
import { AlertStateChip } from '../../components/AlertStateChip';
|
||||
@@ -20,20 +20,21 @@ import tableStyles from '../../styles/table-section.module.css';
|
||||
|
||||
type Severity = NonNullable<AlertDto['severity']>;
|
||||
|
||||
const SEVERITY_FILTERS: Record<string, { label: string; values: Severity[] | undefined }> = {
|
||||
all: { label: 'All severities', values: undefined },
|
||||
critical: { label: 'Critical', values: ['CRITICAL'] },
|
||||
warning: { label: 'Warning', values: ['WARNING'] },
|
||||
info: { label: 'Info', values: ['INFO'] },
|
||||
};
|
||||
const SEVERITY_ITEMS: ButtonGroupItem[] = [
|
||||
{ value: 'CRITICAL', label: 'Critical', color: 'var(--error)' },
|
||||
{ value: 'WARNING', label: 'Warning', color: 'var(--warning)' },
|
||||
{ value: 'INFO', label: 'Info', color: 'var(--text-muted)' },
|
||||
];
|
||||
|
||||
export default function InboxPage() {
|
||||
const [severityKey, setSeverityKey] = useState<string>('all');
|
||||
const severityFilter = SEVERITY_FILTERS[severityKey];
|
||||
const [severitySel, setSeveritySel] = useState<Set<string>>(new Set());
|
||||
const severityValues: Severity[] | undefined = severitySel.size === 0
|
||||
? undefined
|
||||
: [...severitySel] as Severity[];
|
||||
|
||||
const { data, isLoading, error } = useAlerts({
|
||||
state: ['FIRING', 'ACKNOWLEDGED'],
|
||||
severity: severityFilter.values,
|
||||
severity: severityValues,
|
||||
limit: 200,
|
||||
});
|
||||
const bulkRead = useBulkReadAlerts();
|
||||
@@ -179,10 +180,10 @@ export default function InboxPage() {
|
||||
<span className={css.pageSubtitle}>{subtitle}</span>
|
||||
</div>
|
||||
<div className={css.pageActions}>
|
||||
<SegmentedTabs
|
||||
tabs={Object.entries(SEVERITY_FILTERS).map(([value, f]) => ({ value, label: f.label }))}
|
||||
active={severityKey}
|
||||
onChange={setSeverityKey}
|
||||
<ButtonGroup
|
||||
items={SEVERITY_ITEMS}
|
||||
value={severitySel}
|
||||
onChange={setSeveritySel}
|
||||
/>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
Reference in New Issue
Block a user