Skip to content
Merged
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
7 changes: 7 additions & 0 deletions .changeset/source-variable-text-alerts.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/common-utils': minor
'@hyperdx/app': minor
'@hyperdx/api': minor
---

feat: Block alerts on tiles whose text references a data source or connection variable
9 changes: 6 additions & 3 deletions packages/api/src/controllers/alerts.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
configDependsOnReferenceVariable,
displayTypeSupportsBuilderAlerts,
displayTypeSupportsRawSqlAlerts,
isFormulaSourceKind,
Expand All @@ -9,7 +10,6 @@ import {
isPromqlSavedChartConfig,
isRawSqlSavedChartConfig,
} from '@hyperdx/common-utils/dist/guards';
import { configUsesReferenceVariable } from '@hyperdx/common-utils/dist/referenceVariables';
import { isRangeThresholdType } from '@hyperdx/common-utils/dist/types';
import { groupBy } from 'lodash';
import { type FilterQuery, Types } from 'mongoose';
Expand Down Expand Up @@ -97,8 +97,11 @@ export const validateAlertInput = async (
}

// The alert checker cannot evaluate these tiles, so the alert would never run.
if (tile.config != null && !savedChartConfigSupportsAlerts(tile.config)) {
if (configUsesReferenceVariable(tile.config)) {
if (
tile.config != null &&
!savedChartConfigSupportsAlerts(tile.config, dashboard.filters)
) {
if (configDependsOnReferenceVariable(tile.config, dashboard.filters)) {
throw new Api400Error(
'Alerts are not supported on tiles that use a data source or connection variable',
);
Expand Down
39 changes: 31 additions & 8 deletions packages/api/src/controllers/dashboard.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { savedChartConfigSupportsAlerts } from '@hyperdx/common-utils/dist/core/utils';
import {
DashboardFilter,
DashboardWithoutIdSchema,
resolveChartPaletteToken,
SavedChartConfig,
Expand All @@ -23,15 +24,21 @@ import { resolveAlertDisplayFields } from '@/utils/alerts';

// Drop alerts on tiles the alert checker cannot evaluate (e.g. PromQL), so
// they are never stored and any existing ones are deleted on save.
function getSupportedTileAlert(tile: Tile) {
return savedChartConfigSupportsAlerts(tile.config)
function getSupportedTileAlert(
tile: Tile,
filters: DashboardFilter[] | undefined,
) {
return savedChartConfigSupportsAlerts(tile.config, filters)
? tile.config.alert
: undefined;
}

function pickAlertsByTile(tiles: Tile[]) {
function pickAlertsByTile(
tiles: Tile[],
filters: DashboardFilter[] | undefined,
) {
return tiles.reduce((acc, tile) => {
const alert = getSupportedTileAlert(tile);
const alert = getSupportedTileAlert(tile, filters);
if (alert) {
acc[tile.id] = alert;
}
Expand Down Expand Up @@ -92,7 +99,7 @@ function extractTileAlertData(tiles: TileForAlertSync[]): {
}

async function syncDashboardAlerts(
dashboard: Pick<IDashboard, '_id' | 'name' | 'tags' | 'tiles'>,
dashboard: Pick<IDashboard, '_id' | 'name' | 'tags' | 'tiles' | 'filters'>,
teamId: ObjectId,
oldTiles: TileForAlertSync[],
newTiles: Tile[],
Expand All @@ -104,13 +111,13 @@ async function syncDashboardAlerts(

const newTilesForAlertSync: TileForAlertSync[] = newTiles.map(t => ({
id: t.id,
config: { alert: getSupportedTileAlert(t) },
config: { alert: getSupportedTileAlert(t, dashboard.filters) },
}));
const { tileIds: newTileIds, tileIdsWithAlerts: newTileIdsWithAlerts } =
extractTileAlertData(newTilesForAlertSync);

// 1. Create/update alerts for tiles that have alerts
const alertsByTile = pickAlertsByTile(newTiles);
const alertsByTile = pickAlertsByTile(newTiles, dashboard.filters);
if (Object.keys(alertsByTile).length > 0) {
await createOrUpdateDashboardAlerts(
dashboard,
Expand Down Expand Up @@ -224,7 +231,7 @@ export async function createDashboard(
await createOrUpdateDashboardAlerts(
newDashboard,
teamId,
pickAlertsByTile(dashboard.tiles),
pickAlertsByTile(dashboard.tiles, newDashboard.filters),
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
userId,
);

Expand Down Expand Up @@ -292,6 +299,22 @@ export async function updateDashboard(
updates.tiles,
userId,
);
} else if (updates.filters) {
// Whether a tile can alert depends on the filters, so a filters-only save
// can leave an alert on a tile that now references a data source variable.
// Stored tiles don't carry their alerts, so this can only delete.
const unsupportedTileIds = updatedDashboard.tiles
.filter(
tile =>
!savedChartConfigSupportsAlerts(
tile.config,
updatedDashboard.filters,
),
)
.map(tile => tile.id);
if (unsupportedTileIds.length > 0) {
await deleteDashboardAlerts(dashboardId, teamId, unsupportedTileIds);
}
}

recordDashboardOnboardingIfHasTiles(userId, updatedDashboard.tiles);
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/mcp/tools/dashboards/patchDashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,7 @@ export function registerPatchDashboard({
teamId,
internalTiles: patchedTileInDb,
existingTileIds,
filters: updatedDashboard.filters,
});
}

Expand Down
1 change: 1 addition & 0 deletions packages/api/src/mcp/tools/dashboards/saveDashboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,7 @@ async function updateDashboard({
teamId,
internalTiles,
existingTileIds,
filters: updatedDashboard.filters,
});

recordDashboardOnboardingIfHasTiles(userId, updatedDashboard.tiles);
Expand Down
109 changes: 109 additions & 0 deletions packages/api/src/routers/api/__tests__/dashboard.int.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -541,6 +541,115 @@ describe('dashboard router', () => {
expect(await Alert.countDocuments({ team: team._id })).toBe(0);
});

describe('tiles whose text references a data source variable', () => {
const logsVariableFilter = {
id: 'logs-filter',
type: 'DATA_SOURCE' as const,
name: 'Logs',
variableName: 'logs',
allowedSourceKinds: [SourceKind.Log],
minSelections: 1,
maxSelections: 1,
isBroadcastEnabled: false,
isVariableEnabled: true,
};
const where = 'SourceName:"${logs.name}"';

it('does not create the tile alert', async () => {
await agent
.post('/dashboards')
.send({
name: 'Test Dashboard',
tiles: [
makeTile({ alert: makeMockAlert(webhook._id.toString()), where }),
],
filters: [logsVariableFilter],
tags: [],
})
.expect(200);

expect(await Alert.countDocuments({ team: team._id })).toBe(0);
});

it('rejects a standalone alert', async () => {
const tile = makeTile({ where });
const dashboard = await agent
.post('/dashboards')
.send({
name: 'Test Dashboard',
tiles: [tile],
filters: [logsVariableFilter],
tags: [],
})
.expect(200);

const response = await agent
.post('/alerts')
.send(
makeAlertInput({
dashboardId: dashboard.body.id,
tileId: tile.id,
webhookId: webhook._id.toString(),
}),
)
.expect(400);
expect(JSON.stringify(response.body)).toContain(
'Alerts are not supported on tiles that use a data source or connection variable',
);
});

it('deletes the alert when a PATCH makes the tile text reference the variable', async () => {
const dashboard = await agent
.post('/dashboards')
.send({
name: 'Test Dashboard',
tiles: [makeTile({ alert: makeMockAlert(webhook._id.toString()) })],
filters: [logsVariableFilter],
tags: [],
})
.expect(200);
expect(await Alert.countDocuments({ team: team._id })).toBe(1);

const [tile] = dashboard.body.tiles;
await agent
.patch(`/dashboards/${dashboard.body.id}`)
.send({
...dashboard.body,
tiles: [{ ...tile, config: { ...tile.config, where } }],
})
.expect(200);

expect(await Alert.countDocuments({ team: team._id })).toBe(0);
});

it('deletes only that alert when a filters-only PATCH declares the variable', async () => {
const referencingTile = makeTile({
alert: makeMockAlert(webhook._id.toString()),
where,
});
const otherTile = makeTile({
alert: makeMockAlert(webhook._id.toString()),
});
const dashboard = await agent
.post('/dashboards')
.send({
name: 'Test Dashboard',
tiles: [referencingTile, otherTile],
tags: [],
})
.expect(200);
expect(await Alert.countDocuments({ team: team._id })).toBe(2);

await agent
.patch(`/dashboards/${dashboard.body.id}`)
.send({ filters: [logsVariableFilter] })
.expect(200);

const alerts = await Alert.find({ team: team._id });
expect(alerts.map(alert => alert.tileId)).toEqual([otherTile.id]);
});
});

it('deletes the alert when a tile is switched to PromQL', async () => {
const mockAlert = makeMockAlert(webhook._id.toString());
const dashboard = await agent
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9361,6 +9361,84 @@ describe('External API v2 Dashboards - new format', () => {

expect(await Alert.findById(alert._id)).toBeNull();
});

describe('tiles whose text references the variable', () => {
const where = 'SpanName:"${traces.name}"';
const createTileAlert = async (dashboardId: string, tileId: string) => {
const webhook = await Webhook.create({
name: `Webhook ${tileId}`,
service: WebhookService.Slack,
url: 'https://hooks.slack.com/test',
team: team._id,
});
return Alert.create({
team: team._id,
dashboard: dashboardId,
tileId,
source: AlertSource.TILE,
threshold: 100,
interval: '1h',
thresholdType: AlertThresholdType.ABOVE,
channel: { type: 'webhook', webhookId: webhook._id.toString() },
});
};
const withWhere = (tile: ExternalDashboardTile) => ({
...tile,
config: {
...tile.config,
select: [{ aggFn: 'count', where, whereLanguage: 'lucene' }],
},
});

it('deletes the alert of a tile whose text starts referencing the variable', async () => {
const created = await authRequest('post', BASE_URL)
.send({
name: 'Variable Dashboard',
tiles: [makeExternalTile({ sourceId: traceSource._id.toString() })],
tags: [],
filters: [connectionFilter, dataSourceFilter],
})
.expect(200);
const { id: dashboardId, tiles } = created.body.data;
const alert = await createTileAlert(dashboardId, tiles[0].id);

await authRequest('put', `${BASE_URL}/${dashboardId}`)
.send({ ...created.body.data, tiles: [withWhere(tiles[0])] })
.expect(200);

expect(await Alert.findById(alert._id)).toBeNull();
});

it('deletes only that alert when a filter edit declares the variable', async () => {
const tile = makeExternalTile({ sourceId: traceSource._id.toString() });
const created = await authRequest('post', BASE_URL)
.send({
name: 'Variable Dashboard',
tiles: [withWhere(tile), tile],
tags: [],
})
.expect(200);
const { id: dashboardId, tiles } = created.body.data;
const referencingAlert = await createTileAlert(
dashboardId,
tiles[0].id,
);
const otherAlert = await createTileAlert(dashboardId, tiles[1].id);

await authRequest('put', `${BASE_URL}/${dashboardId}`)
.send({
...created.body.data,
filters: [connectionFilter, dataSourceFilter].map(filter => ({
...filter,
id: new ObjectId().toString(),
})),
})
.expect(200);

expect(await Alert.findById(referencingAlert._id)).toBeNull();
expect(await Alert.findById(otherAlert._id)).not.toBeNull();
});
});
});

describe('ad hoc filters', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/routers/external-api/v2/dashboards.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4115,6 +4115,7 @@ router.put(
teamId,
internalTiles,
existingTileIds,
filters: updatedDashboard.filters,
});

recordDashboardOnboardingIfHasTiles(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2054,17 +2054,20 @@ export async function cleanupDashboardAlerts({
teamId,
internalTiles,
existingTileIds,
filters,
}: {
dashboardId: string;
teamId: string | mongoose.Types.ObjectId;
internalTiles: DashboardDocument['tiles'];
existingTileIds: Set<string>;
/** The saved dashboard's filters, so text references to its variables count. */
filters: DashboardDocument['filters'];
}) {
const newTileIdSet = new Set(internalTiles.map(t => t.id));
const tileIdsToDeleteAlerts = [
// Tiles whose config no longer supports alerts (e.g. switched to PromQL).
...internalTiles
.filter(tile => !savedChartConfigSupportsAlerts(tile.config))
.filter(tile => !savedChartConfigSupportsAlerts(tile.config, filters))
.map(tile => tile.id),
// Tiles that were completely removed.
...[...existingTileIds].filter(id => !newTileIdSet.has(id)),
Expand Down
Loading
Loading