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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5917,11 +5917,14 @@ describe('External API v2 Dashboards - new format', () => {
...overrides,
});

const sendFilters = async (filters: Record<string, unknown>[]) => {
const payload = createMockDashboardWithIds(
traceSource._id.toString(),
{},
);
const sendFilters = async (
filters: Record<string, unknown>[],
savedFilterValues: Record<string, unknown>[] = [],
) => {
const payload = {
...createMockDashboardWithIds(traceSource._id.toString(), {}),
savedFilterValues,
};
if (method === 'post') {
// A create body may not choose filter ids, so the shared fixtures shed
// theirs on this path.
Expand Down Expand Up @@ -6154,6 +6157,37 @@ describe('External API v2 Dashboards - new format', () => {
});
});

// Held back until the dashboard UI offers "All".
describe('"All" option', () => {
it.each([
['STATIC_LIST', () => staticFilterInput({ allowAll: true })],
[
'SQL_QUERY',
() => ({
id: new ObjectId().toString(),
type: 'SQL_QUERY' as const,
name: 'Environment',
connectionId: connection._id.toString(),
sqlTemplate: 'SELECT DISTINCT env FROM envs',
allowAll: true,
}),
],
] as const)(
'rejects allowAll on a %s filter',
async (_type, makeFilter) => {
await expectFilters([makeFilter()], 400);
},
);

it('rejects a saved "all" value', async () => {
const response = await sendFilters(
[staticFilterInput()],
[{ type: 'variable', name: 'env', values: [], all: true }],
);
expect(response.status).toBe(400);
});
});

describe('required filters', () => {
// Named factories rather than a keyed map, so the label `it.each` prints
// does not have to come from a lookup evaluated at collection time
Expand Down
13 changes: 9 additions & 4 deletions packages/api/src/utils/zod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,8 +200,11 @@ const externalQueryExpressionFilterShape =
});

// A static filter's mode flags each accept exactly one value, so callers may
// omit them and get that value.
const externalStaticListFilterShape = StaticListDashboardFilterSchema.extend({
// omit them and get that value. `allowAll` is held back until the dashboard UI
// offers "All".
const externalStaticListFilterShape = StaticListDashboardFilterSchema.omit({
allowAll: true,
}).extend({
isBroadcastEnabled: z.literal(false).default(false),
isVariableEnabled: z.literal(true).default(true),
});
Expand All @@ -215,10 +218,11 @@ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({
});

// `connectionId`/`sourceId` rather than `connection`/`source`, matching raw SQL
// tiles.
// tiles. `allowAll` is held back until the dashboard UI offers "All".
const externalSqlQueryFilterShape = SqlQueryDashboardFilterSchema.omit({
connection: true,
source: true,
allowAll: true,
}).extend({
connectionId: objectIdOrVariableReferenceSchema,
sourceId: objectIdOrVariableReferenceSchema.optional(),
Expand Down Expand Up @@ -300,8 +304,9 @@ export const externalSqlSavedFilterValueSchema = z.object({
condition: z.string().max(10000),
});

// `all` is held back until the dashboard UI offers "All".
export const externalVariableSavedFilterValueSchema =
VariableFilterValueSchema.strict();
VariableFilterValueSchema.omit({ all: true }).strict();

export const externalAdhocSavedFilterValueSchema =
AdhocFilterValueSchema.strict();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,16 @@ describe('dashboardFilterValues', () => {
]);
});

it('keeps an "all" selection even though it carries no values', () => {
expect(
serializeDashboardFilterValues({
byVariable: new Map<string, VariableEntryValue>([
['env', { type: 'variable', values: ['ignored'], all: true }],
]),
}),
).toEqual([{ type: 'variable', name: 'env', values: [], all: true }]);
});

it('emits legacy entries byte-identically to filtersToQuery', () => {
const byExpression: FilterState = {
ServiceName: {
Expand Down Expand Up @@ -445,6 +455,18 @@ describe('dashboardFilterValues', () => {
);
});

it('resolves an "all" entry to an empty selection', () => {
// The included/excluded shape can't hold "all", and the entry's values
// are ignored, so neither may leak into it.
const parsed = parseDashboardFilterValues([
{ type: 'variable', name: 'env', values: ['prod'], all: true },
]);

expect(resolveFilterSelection(staticFilter(), parsed)).toEqual(
included(),
);
});

it('treats an explicitly empty variable entry as a selection', () => {
const parsed = parseDashboardFilterValues([
{ type: 'sql', condition: "ServiceName IN ('legacy')" },
Expand Down
74 changes: 74 additions & 0 deletions packages/common-utils/src/__tests__/dashboardValidation.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { z } from 'zod/v3';

import {
collectRefinementIssues,
validateChartConfigFormulas,
validateDashboardFilterFieldGating,
validateDashboardFilterModes,
validateDashboardFilterOptionUniqueness,
validateDashboardFilterVariableNames,
validateDashboardSavedFilterValues,
} from '@/dashboardValidation';

type TestFilter = {
Expand Down Expand Up @@ -288,6 +290,8 @@ type GatingFilter = ModeFilter & {
sourceType?: string;
where?: string;
whereLanguage?: string;
allowAll?: boolean;
maxSelections?: number;
};

const collectGatingIssues = (
Expand Down Expand Up @@ -444,6 +448,76 @@ describe('validateDashboardFilterFieldGating', () => {

expect(issues[0].path).toEqual(['body', 'filters', 0, 'variableName']);
});

it('rejects allowAll on a single-select filter only', () => {
const issues = collectGatingIssues([
{ name: 'Multi', isVariableEnabled: true, allowAll: true },
{
name: 'Single',
isVariableEnabled: true,
allowAll: true,
maxSelections: 1,
},
{
name: 'Off',
isVariableEnabled: true,
allowAll: false,
maxSelections: 1,
},
]);

expect(issues).toHaveLength(1);
expect(issues[0].path).toEqual(['filters', 1, 'allowAll']);
expect(issues[0].message).toBe(
'Filter "Single" sets allowAll but is single-select; drop allowAll or maxSelections',
);
});
});

describe('validateDashboardSavedFilterValues', () => {
const filters = [
{
type: 'STATIC_LIST' as const,
name: 'Environment',
variableName: 'env',
allowAll: true,
},
{ type: 'STATIC_LIST' as const, name: 'Region', variableName: 'region' },
];

const collect = (
savedFilterValues: Parameters<typeof validateDashboardSavedFilterValues>[1],
) =>
collectRefinementIssues(ctx =>
validateDashboardSavedFilterValues(filters, savedFilterValues, ctx),
);

it('accepts "all" on a filter that offers it', () => {
expect(collect([{ type: 'variable', name: 'env', all: true }])).toEqual([]);
});

it('rejects "all" on a filter that does not offer it', () => {
const issues = collect([
{ type: 'variable', name: 'env', all: true },
{ type: 'variable', name: 'region', all: true },
]);

expect(issues).toHaveLength(1);
expect(issues[0].path).toEqual(['savedFilterValues', 1, 'all']);
expect(issues[0].message).toBe(
'Saved filter value for "region" sets all: true, but its filter does not offer "All"; set allowAll on the filter or select specific values',
);
});

it('ignores explicit values and names no filter declares', () => {
expect(
collect([
{ type: 'variable', name: 'region' },
{ type: 'variable', name: 'unknown', all: true },
{ type: 'sql', all: true },
]),
).toEqual([]);
});
});

type OptionsFilter = Parameters<
Expand Down
35 changes: 35 additions & 0 deletions packages/common-utils/src/__tests__/filters.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
FilterState,
filterStateToPredicate,
filtersToQuery,
filterSupportsAllValue,
getAdhocFilterAppliesToSourceIds,
getDashboardVariableDeclarations,
getDashboardVariableFilters,
Expand Down Expand Up @@ -2050,6 +2051,40 @@ describe('filters', () => {
});
});

describe('filterSupportsAllValue', () => {
it('holds for multi-select static list and SQL query filters that opt in', () => {
expect(
filterSupportsAllValue({ type: 'STATIC_LIST', allowAll: true }),
).toBe(true);
expect(
filterSupportsAllValue({ type: 'SQL_QUERY', allowAll: true }),
).toBe(true);
});

it('does not hold without the opt-in', () => {
expect(filterSupportsAllValue({ type: 'STATIC_LIST' })).toBe(false);
expect(
filterSupportsAllValue({ type: 'SQL_QUERY', allowAll: false }),
).toBe(false);
});

it('does not hold for a single-select filter', () => {
expect(
filterSupportsAllValue({
type: 'STATIC_LIST',
allowAll: true,
maxSelections: 1,
}),
).toBe(false);
});

it('does not hold for other filter types', () => {
expect(
filterSupportsAllValue({ type: 'QUERY_EXPRESSION', allowAll: true }),
).toBe(false);
});
});

describe('isFilterGlobalRequirement', () => {
it('treats a missing flag as covering only the tiles that read the filter', () => {
expect(isFilterGlobalRequirement({})).toBe(false);
Expand Down
20 changes: 20 additions & 0 deletions packages/common-utils/src/__tests__/types.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -588,6 +588,11 @@ describe('DashboardFilterSchema static-list variant', () => {
]);
});

it('keeps allowAll', () => {
const withAll = { ...staticFilter, allowAll: true };
expect(DashboardFilterSchema.parse(withAll)).toEqual(withAll);
});

it('rejects an unknown filter type at the discriminator', () => {
const result = DashboardFilterSchema.safeParse({
...staticFilter,
Expand Down Expand Up @@ -694,6 +699,11 @@ describe('DashboardFilterSchema SQL query variant', () => {
expect(DashboardFilterSchema.parse(sqlFilter)).toEqual(sqlFilter);
});

it('keeps allowAll', () => {
const withAll = { ...sqlFilter, allowAll: true };
expect(DashboardFilterSchema.parse(withAll)).toEqual(withAll);
});

it.each(['connection', 'sqlTemplate'] as const)(
'requires a non-empty %s',
field => {
Expand Down Expand Up @@ -867,6 +877,16 @@ describe('DashboardFilterValueSchema', () => {
).toBe(true);
});

it('accepts an "all" entry and rejects any other value for the flag', () => {
const entry = { type: 'variable', name: 'svc', values: [] };
expect(
DashboardFilterValueSchema.safeParse({ ...entry, all: true }).success,
).toBe(true);
expect(
DashboardFilterValueSchema.safeParse({ ...entry, all: false }).success,
).toBe(false);
});

it('requires a non-empty name and a values array', () => {
for (const entry of [
{ type: 'variable', values: ['a'] },
Expand Down
58 changes: 58 additions & 0 deletions packages/common-utils/src/__tests__/variableSelection.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { ChartVariable } from '@/types';
import {
ALL_SELECTION,
expandAllSelections,
isAllSelection,
selectionHasValue,
} from '@/variableSelection';

describe('isAllSelection', () => {
it('holds only for the "all" marker', () => {
expect(isAllSelection(ALL_SELECTION)).toBe(true);
expect(isAllSelection(['a'])).toBe(false);
expect(isAllSelection([])).toBe(false);
expect(isAllSelection(undefined)).toBe(false);
});
});

describe('selectionHasValue', () => {
it('holds for "all" and for a non-empty list', () => {
expect(selectionHasValue(ALL_SELECTION)).toBe(true);
expect(selectionHasValue(['a'])).toBe(true);
});

it('treats an empty list like no selection', () => {
expect(selectionHasValue([])).toBe(false);
expect(selectionHasValue(undefined)).toBe(false);
});
});

describe('expandAllSelections', () => {
const env: ChartVariable = { name: 'env', values: [], all: true };
const region: ChartVariable = { name: 'region', values: ['eu'] };

it('fills an "all" variable with its sorted options', () => {
expect(
expandAllSelections(
[env, region],
new Map([
['env', ['staging', 'prod']],
['region', ['us', 'eu']],
]),
),
).toEqual([
{ name: 'env', values: ['prod', 'staging'], all: true },
region,
]);
});

it('leaves an "all" variable empty until its options are known', () => {
expect(expandAllSelections([env], new Map())).toEqual([env]);
});

it('does not mutate the options it was given', () => {
const options = ['staging', 'prod'];
expandAllSelections([env], new Map([['env', options]]));
expect(options).toEqual(['staging', 'prod']);
});
});
Loading
Loading