diff --git a/.changeset/source-variable-text-alerts.md b/.changeset/source-variable-text-alerts.md new file mode 100644 index 000000000..18435c935 --- /dev/null +++ b/.changeset/source-variable-text-alerts.md @@ -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 diff --git a/packages/api/src/controllers/alerts.ts b/packages/api/src/controllers/alerts.ts index ef7c43dc3..ce290783f 100644 --- a/packages/api/src/controllers/alerts.ts +++ b/packages/api/src/controllers/alerts.ts @@ -1,4 +1,5 @@ import { + configDependsOnReferenceVariable, displayTypeSupportsBuilderAlerts, displayTypeSupportsRawSqlAlerts, isFormulaSourceKind, @@ -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'; @@ -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', ); diff --git a/packages/api/src/controllers/dashboard.ts b/packages/api/src/controllers/dashboard.ts index 1eb0e249d..1a020d2d3 100644 --- a/packages/api/src/controllers/dashboard.ts +++ b/packages/api/src/controllers/dashboard.ts @@ -1,5 +1,6 @@ import { savedChartConfigSupportsAlerts } from '@hyperdx/common-utils/dist/core/utils'; import { + DashboardFilter, DashboardWithoutIdSchema, resolveChartPaletteToken, SavedChartConfig, @@ -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; } @@ -92,7 +99,7 @@ function extractTileAlertData(tiles: TileForAlertSync[]): { } async function syncDashboardAlerts( - dashboard: Pick, + dashboard: Pick, teamId: ObjectId, oldTiles: TileForAlertSync[], newTiles: Tile[], @@ -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, @@ -224,7 +231,7 @@ export async function createDashboard( await createOrUpdateDashboardAlerts( newDashboard, teamId, - pickAlertsByTile(dashboard.tiles), + pickAlertsByTile(dashboard.tiles, newDashboard.filters), userId, ); @@ -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); diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index 119ca9f72..634cec479 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -263,6 +263,7 @@ export function registerPatchDashboard({ teamId, internalTiles: patchedTileInDb, existingTileIds, + filters: updatedDashboard.filters, }); } diff --git a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts index 05cfc0e2f..5aeed3978 100644 --- a/packages/api/src/mcp/tools/dashboards/saveDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/saveDashboard.ts @@ -444,6 +444,7 @@ async function updateDashboard({ teamId, internalTiles, existingTileIds, + filters: updatedDashboard.filters, }); recordDashboardOnboardingIfHasTiles(userId, updatedDashboard.tiles); diff --git a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts index 9b4fbb1dc..cf442e019 100644 --- a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts +++ b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts @@ -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 diff --git a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts index dcfb11383..4c8b529e2 100644 --- a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts @@ -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', () => { diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index c70f14f29..e427141ba 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -4115,6 +4115,7 @@ router.put( teamId, internalTiles, existingTileIds, + filters: updatedDashboard.filters, }); recordDashboardOnboardingIfHasTiles( diff --git a/packages/api/src/routers/external-api/v2/utils/dashboards.ts b/packages/api/src/routers/external-api/v2/utils/dashboards.ts index 826262963..6716d73ce 100644 --- a/packages/api/src/routers/external-api/v2/utils/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/utils/dashboards.ts @@ -2054,17 +2054,20 @@ export async function cleanupDashboardAlerts({ teamId, internalTiles, existingTileIds, + filters, }: { dashboardId: string; teamId: string | mongoose.Types.ObjectId; internalTiles: DashboardDocument['tiles']; existingTileIds: Set; + /** 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)), diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 7837d0258..3ad99caad 100644 --- a/packages/api/src/tasks/checkAlerts/index.ts +++ b/packages/api/src/tasks/checkAlerts/index.ts @@ -29,13 +29,13 @@ import { isTimeSeriesDisplayType, } from '@hyperdx/common-utils/dist/core/utils'; import { timeBucketByGranularity } from '@hyperdx/common-utils/dist/core/utils'; -import { getDashboardVariableDeclarations } from '@hyperdx/common-utils/dist/filters'; import { isBuilderChartConfig, isPromqlSavedChartConfig, isRawSqlChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { getEmptyDashboardVariables } from '@hyperdx/common-utils/dist/referenceVariables'; import { ALERT_NOTIFICATION_TARGETS_LIMIT, AlertErrorType, @@ -889,12 +889,7 @@ const getChartConfigFromAlert = ( }); } else if (details.taskType === AlertTaskType.TILE) { // Substitute empty selections for each variable the dashboard defines - const variables = getDashboardVariableDeclarations( - details.dashboard.filters, - ).map(declaration => ({ - ...declaration, - values: [], - })); + const variables = getEmptyDashboardVariables(details.dashboard.filters); const config = buildAlertChartConfigFromSavedConfig({ alertId: alert.id, diff --git a/packages/app/src/DBDashboardPage.tsx b/packages/app/src/DBDashboardPage.tsx index a532c598b..5c104e126 100644 --- a/packages/app/src/DBDashboardPage.tsx +++ b/packages/app/src/DBDashboardPage.tsx @@ -1000,9 +1000,12 @@ const Tile = ({ return url && addTimeZone(url); }, [dateRange, queriedConfig, source, addTimeZone]); - // An alert must query one fixed source and connection + // An alert must query one fixed source and connection, and runs with every + // variable unselected, so text referencing one would render as nothing. const supportsAlerts = - !usesReferenceVariable && savedChartConfigSupportsAlerts(chart.config); + !usesReferenceVariable && + savedChartConfigSupportsAlerts(chart.config) && + !tileVariables?.some(variable => variable.reference != null); const hoverToolbar = useMemo(() => { if (readOnly) return null; diff --git a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx index 7dff69c16..f3532d9a4 100644 --- a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx @@ -60,6 +60,7 @@ export default function RawSqlChartEditor({ alert, additionalWarnings, alertsEnabled, + alertsDisabledReason, isAlertRequired, dashboardId, variables, @@ -74,6 +75,8 @@ export default function RawSqlChartEditor({ additionalWarnings?: string[]; /** Whether this editor offers an alert (see EditTimeChartForm.enableAlerts). */ alertsEnabled?: boolean; + /** Why an alert can't be added; shows the alert button disabled. */ + alertsDisabledReason?: string; /** Hides the alert editor's remove control. */ isAlertRequired?: boolean; dashboardId?: string; @@ -191,7 +194,7 @@ export default function RawSqlChartEditor({ const showAlertButton = alert != null || (displayTypeSupportsRawSqlAlerts(displayType) && - alertsEnabled && + (alertsEnabled || alertsDisabledReason != null) && !IS_LOCAL_MODE); return ( @@ -246,6 +249,7 @@ export default function RawSqlChartEditor({ {showAlertButton && ( diff --git a/packages/app/src/components/ChartEditor/utils.ts b/packages/app/src/components/ChartEditor/utils.ts index e6f2dba3e..accda1ae8 100644 --- a/packages/app/src/components/ChartEditor/utils.ts +++ b/packages/app/src/components/ChartEditor/utils.ts @@ -44,6 +44,7 @@ import { SourceKind, TSource, } from '@hyperdx/common-utils/dist/types'; +import { configReferencesReferenceVariable } from '@hyperdx/common-utils/dist/variables'; import { getStoredLanguage } from '@/components/SearchInput'; import { type SQLCompletion } from '@/components/SQLEditor/utils'; @@ -222,6 +223,21 @@ export function getFormReferenceVariables( }); } +/** + * Whether a chart form's text (SQL, expressions, markdown) references a data + * source or connection variable. Alerts run with every variable unselected, + * so such a reference would render as nothing. + */ +export function formTextUsesReferenceVariable( + form: ChartEditorFormState, + source: TSource | undefined, + variables: ChartVariable[] | undefined, +): boolean { + if (!variables?.some(variable => variable.reference != null)) return false; + const config = convertFormStateToSavedChartConfig(form, source); + return config != null && configReferencesReferenceVariable(config, variables); +} + const isCustomOrderByDisplayType = ( displayType: DisplayType | undefined, ): displayType is DisplayType.Table | DisplayType.Bar | DisplayType.Pie => diff --git a/packages/app/src/components/DBEditTimeChartForm/AlertPanelButton.tsx b/packages/app/src/components/DBEditTimeChartForm/AlertPanelButton.tsx index a2c1d3774..301e5565e 100644 --- a/packages/app/src/components/DBEditTimeChartForm/AlertPanelButton.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/AlertPanelButton.tsx @@ -12,9 +12,12 @@ export function AlertPanelButton({ onAddAlert, error, warning, + disabledReason, }: { hasAlert: boolean; onAddAlert: () => void; + /** Why the chart can't have an alert; disables the button and explains it. */ + disabledReason?: string; /** * The alert's error and warning. Their badges render in the panel, which an * existing alert opens closed, so the button carries them while it is. @@ -26,11 +29,13 @@ export function AlertPanelButton({ const isConfirmed = hasAlert && !alertPanel?.isDraft; const issue = hasAlert && !alertPanel?.opened ? (error ?? warning) : undefined; + const isDisabled = disabledReason != null; + const tooltip = disabledReason ?? issue; return ( { + if (isDisabled) return; if (hasAlert) { // Only opens: closing from here would cancel the panel's changes // without the user asking to. diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx index 7c5d577cd..64f11c288 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx @@ -74,6 +74,8 @@ type ChartEditorControlsProps = { additionalWarnings?: string[]; /** Whether this editor offers an alert (see EditTimeChartForm.enableAlerts). */ alertsEnabled?: boolean; + /** Why an alert can't be added; shows the alert button disabled. */ + alertsDisabledReason?: string; /** Hides the alert editor's remove control. */ isAlertRequired?: boolean; isRawSqlInput: boolean; @@ -110,6 +112,7 @@ export function ChartEditorControls({ alert, additionalWarnings, alertsEnabled, + alertsDisabledReason, isAlertRequired, isRawSqlInput, dashboardId, @@ -189,7 +192,7 @@ export function ChartEditorControls({ const showAlertButton = (alert != null && !isRawSqlInput) || (displayTypeSupportsBuilderAlerts(displayType) && - alertsEnabled && + (alertsEnabled || alertsDisabledReason != null) && !IS_LOCAL_MODE); const alertWarning = useMemo( @@ -512,6 +515,7 @@ export function ChartEditorControls({ {showAlertButton && ( setValue('alert', { diff --git a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx index 50640e07f..d3245eb57 100644 --- a/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/EditTimeChartForm.tsx @@ -39,7 +39,10 @@ import { TILE_DESCRIPTION_MAX_LENGTH, TSource, } from '@hyperdx/common-utils/dist/types'; -import { getAlertVariableWarning } from '@hyperdx/common-utils/dist/variables'; +import { + configReferencesReferenceVariable, + getAlertVariableWarning, +} from '@hyperdx/common-utils/dist/variables'; import { Alert, Box, @@ -79,6 +82,7 @@ import { convertFormStateToChartConfig, convertFormStateToSavedChartConfig, convertSavedChartConfigToFormState, + formTextUsesReferenceVariable, getAllowedSourceKinds, getFormReferenceVariables, getInterchangeableSourceKind, @@ -180,25 +184,12 @@ type EditTimeChartFormProps = { const zodChartFormResolver = zodResolver(zSavedChartConfig); -// A tile on a variable can't keep an alert. The form holds on to it, so that -// switching back to a fixed source restores it, but validates and submits -// without it. -const chartFormResolver: Resolver = ( - values, - context, - options, -) => - zodChartFormResolver( - getFormReferenceVariables(values).length > 0 - ? { ...values, alert: undefined } - : values, - context, - options, - ); - const ALERT_IGNORES_DASHBOARD_FILTERS = 'Dashboard-level filter and variable selections cannot be applied when an alert is configured.'; +const ALERTS_BLOCKED_BY_VARIABLE = + 'Alerts need a fixed source and connection, so they are not available on tiles that use a data source or connection variable.'; + /** * Populate form state with the standard series for a heatmap mode. * Distribution heatmaps bucket the trace duration (or `fallbackValueExpression` @@ -282,6 +273,31 @@ export default function EditTimeChartForm({ [chartConfig], ); + // Read at validation time, but only known after the form exists + const variablesRef = useRef(variables); + const tableSourceRef = useRef(undefined); + + // A tile on a variable can't keep an alert. The form holds on to it, so that + // switching back to a fixed source restores it, but validates and submits + // without it. Checked against the live values, not the debounced ones the + // UI uses, so a reference typed just before saving still counts. + const chartFormResolver = useCallback>( + (values, context, options) => + zodChartFormResolver( + getFormReferenceVariables(values).length > 0 || + formTextUsesReferenceVariable( + values, + tableSourceRef.current, + variablesRef.current, + ) + ? { ...values, alert: undefined } + : values, + context, + options, + ), + [], + ); + const { control, setValue, @@ -399,13 +415,6 @@ export default function EditTimeChartForm({ ); const usesReferenceVariable = referenceVariableNames.length > 0; - // An alert must query one fixed source and connection, not the viewer's - // current selection. - const alertsEnabled = - (enableAlerts ?? dashboardId != null) && !usesReferenceVariable; - // The alert as it will save - const activeAlert = usesReferenceVariable ? undefined : alert; - // A source selection that current mode can't query counts as no source, // so that nothing downstream builds a query from it. const { data: tableSource } = useSource({ @@ -413,6 +422,38 @@ export default function EditTimeChartForm({ kinds: allowedSourceKinds, }); + useEffect(() => { + variablesRef.current = variables; + tableSourceRef.current = tableSource; + }, [variables, tableSource]); + + const debouncedForm = useDebouncedFormValues(watch, getValues, 300); + + const debouncedConfig = useMemo( + () => convertFormStateToSavedChartConfig(debouncedForm, tableSource), + [debouncedForm, tableSource], + ); + + const textUsesReferenceVariable = useMemo( + () => + debouncedConfig != null && + configReferencesReferenceVariable(debouncedConfig, variables), + [debouncedConfig, variables], + ); + + // An alert must query one fixed source and connection, not the viewer's + // current selection. + const alertsBlockedByVariable = + usesReferenceVariable || textUsesReferenceVariable; + const offersAlerts = enableAlerts ?? dashboardId != null; + const alertsEnabled = offersAlerts && !alertsBlockedByVariable; + const alertsDisabledReason = + offersAlerts && alertsBlockedByVariable + ? ALERTS_BLOCKED_BY_VARIABLE + : undefined; + // The alert as it will save + const activeAlert = alertsBlockedByVariable ? undefined : alert; + // Saving reads only the source's kind. With no source selected, a variable // whose kinds charts all treat alike still determines it. const sourceVariable = sourceVariableDeclarations.find( @@ -670,8 +711,6 @@ export default function EditTimeChartForm({ }; }, [queriedConfig, previewDashboardFilters]); - const debouncedForm = useDebouncedFormValues(watch, getValues, 300); - // With no selection for a variable it references the tile has nothing to // query, so there may be no queried config to compute the block from. const previewBlockingFilters = useMemo(() => { @@ -681,7 +720,7 @@ export default function EditTimeChartForm({ ) return undefined; return getPreviewBlockingFilters({ - config: convertFormStateToSavedChartConfig(debouncedForm, tableSource), + config: debouncedConfig, sourceId: undefined, variables, unsatisfiedRequiredFilters, @@ -692,8 +731,7 @@ export default function EditTimeChartForm({ previewDashboardFilters, referenceVariableNames, referenceVariableValues, - debouncedForm, - tableSource, + debouncedConfig, variables, unsatisfiedRequiredFilters, resolvedApplyFilters, @@ -706,15 +744,11 @@ export default function EditTimeChartForm({ const additionalAlertWarnings = useMemo(() => { if (activeAlert == null) return []; - const config = convertFormStateToSavedChartConfig( - debouncedForm, - tableSource, - ); - const variableWarning = config - ? getAlertVariableWarning(config, variables) + const variableWarning = debouncedConfig + ? getAlertVariableWarning(debouncedConfig, variables) : undefined; return variableWarning ? [variableWarning] : []; - }, [activeAlert, debouncedForm, tableSource, variables]); + }, [activeAlert, debouncedConfig, variables]); const [saveToDashboardModalOpen, setSaveToDashboardModalOpen] = useState(false); @@ -1497,6 +1531,7 @@ export default function EditTimeChartForm({ alert={activeAlert} additionalWarnings={additionalAlertWarnings} alertsEnabled={alertsEnabled} + alertsDisabledReason={alertsDisabledReason} isAlertRequired={isAlertRequired} dashboardId={dashboardId} variables={variables} @@ -1526,6 +1561,7 @@ export default function EditTimeChartForm({ alert={activeAlert} additionalWarnings={additionalAlertWarnings} alertsEnabled={alertsEnabled} + alertsDisabledReason={alertsDisabledReason} isAlertRequired={isAlertRequired} isRawSqlInput={isRawSqlInput} dashboardId={dashboardId} @@ -1537,7 +1573,7 @@ export default function EditTimeChartForm({ onHeatmapModeChange={onHeatmapModeChange} /> )} - {alert != null && usesReferenceVariable && ( + {alert != null && alertsBlockedByVariable && ( } diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx index 8b35f1ada..2d9b1e662 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx @@ -1,6 +1,7 @@ import React from 'react'; // The `mock` prefix is required for a jest.mock factory to close over it. import { useController as mockUseController } from 'react-hook-form'; +import { buildReferenceChartVariables } from '@hyperdx/common-utils/dist/referenceVariables'; import { AlertThresholdType, DashboardFilter, @@ -1782,9 +1783,15 @@ describe('DBEditTimeChartForm - Alerts on data source variables', () => { await userEvent.selectOptions(sourceSelector, '$metrics'); expect(screen.getByText(removalNotice)).toBeInTheDocument(); - expect(screen.queryByTestId('alert-button')).not.toBeInTheDocument(); + expect(screen.getByTestId('alert-button')).toHaveAttribute( + 'aria-disabled', + 'true', + ); await userEvent.selectOptions(sourceSelector, 'metric-source'); + expect(screen.getByTestId('alert-button')).not.toHaveAttribute( + 'aria-disabled', + ); expect(screen.queryByText(removalNotice)).not.toBeInTheDocument(); await userEvent.click(screen.getByTestId('chart-save-button')); @@ -1808,4 +1815,39 @@ describe('DBEditTimeChartForm - Alerts on data source variables', () => { expect(saved.source).toBe('$metrics'); expect(saved.alert).toBeUndefined(); }); + + it('saves a raw SQL tile without its alert while its text references a variable, even an invalid one', async () => { + const onSave = jest.fn(); + renderWithMantine( + + + + + , + ); + + expect(await screen.findByText(removalNotice)).toBeInTheDocument(); + await userEvent.click(screen.getByTestId('chart-save-button')); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave.mock.calls[0][0].alert).toBeUndefined(); + }); }); diff --git a/packages/app/src/components/alerts/AlertDetailChart.tsx b/packages/app/src/components/alerts/AlertDetailChart.tsx index 60608d154..213cf4023 100644 --- a/packages/app/src/components/alerts/AlertDetailChart.tsx +++ b/packages/app/src/components/alerts/AlertDetailChart.tsx @@ -5,11 +5,11 @@ import { Granularity, isTimeSeriesDisplayType, } from '@hyperdx/common-utils/dist/core/utils'; -import { getDashboardVariableDeclarations } from '@hyperdx/common-utils/dist/filters'; import { isPromqlSavedChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { getEmptyDashboardVariables } from '@hyperdx/common-utils/dist/referenceVariables'; import { AlertSource, ChartConfigWithDateRange, @@ -298,9 +298,7 @@ function TileAlertChart({ source, // The alert (and its preview) runs with every dashboard variable in // its empty state. - variables: getDashboardVariableDeclarations(dashboard?.filters).map( - declaration => ({ ...declaration, values: [] }), - ), + variables: getEmptyDashboardVariables(dashboard?.filters), dateRange, granularity, }), diff --git a/packages/app/tests/e2e/features/dashboard-source-variables.spec.ts b/packages/app/tests/e2e/features/dashboard-source-variables.spec.ts index 71c7e8733..22b713a39 100644 --- a/packages/app/tests/e2e/features/dashboard-source-variables.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-source-variables.spec.ts @@ -84,7 +84,10 @@ test.describe( await expect(editor.alertButton).toBeVisible(); await editor.setChartName('Variable tile'); await editor.selectSource('$logs'); - await expect(editor.alertButton).toHaveCount(0); + await expect(editor.alertButton).toHaveAttribute( + 'aria-disabled', + 'true', + ); await editor.save(); await expect(dashboardPage.getTiles()).toHaveCount(1); await expect( @@ -112,7 +115,10 @@ test.describe( await test.step('The editor keeps the reference', async () => { await dashboardPage.editTile(0); await expect(editor.source).toHaveValue('$logs'); - await expect(editor.alertButton).toHaveCount(0); + await expect(editor.alertButton).toHaveAttribute( + 'aria-disabled', + 'true', + ); await editor.save(); }); @@ -228,7 +234,10 @@ test.describe( await expect(editor.alertButton).toBeVisible(); await editor.selectConnection('$cluster'); await editor.selectSource('$logs'); - await expect(editor.alertButton).toHaveCount(0); + await expect(editor.alertButton).toHaveAttribute( + 'aria-disabled', + 'true', + ); await editor.typeSqlQuery('SELECT count() FROM $__sourceTable'); await editor.save(); await expect( diff --git a/packages/common-utils/src/__tests__/referenceVariables.test.ts b/packages/common-utils/src/__tests__/referenceVariables.test.ts index 93faff5a9..1c072b586 100644 --- a/packages/common-utils/src/__tests__/referenceVariables.test.ts +++ b/packages/common-utils/src/__tests__/referenceVariables.test.ts @@ -383,6 +383,42 @@ describe('alerts', () => { expect(savedChartConfigSupportsAlerts(lineConfig('$logs'))).toBe(false); expect(savedChartConfigSupportsAlerts(lineConfig('abc'))).toBe(true); }); + + it('are not supported on tiles whose text references a reference variable', () => { + const filters = [dataSourceFilter(), connectionFilter()]; + const sqlLine = (sqlTemplate: string) => + rawSqlConfig({ displayType: DisplayType.Line, sqlTemplate }); + expect( + savedChartConfigSupportsAlerts( + sqlLine('SELECT count() FROM $logs'), + filters, + ), + ).toBe(false); + expect( + savedChartConfigSupportsAlerts( + sqlLine('SELECT ${conn.name}, count() FROM t'), + filters, + ), + ).toBe(false); + expect( + savedChartConfigSupportsAlerts( + { ...lineConfig('abc'), where: 'Table = ${logs.table:sqlstring}' }, + filters, + ), + ).toBe(false); + }); + + it('are supported on tiles whose text references only value variables', () => { + expect( + savedChartConfigSupportsAlerts( + rawSqlConfig({ + displayType: DisplayType.Line, + sqlTemplate: 'SELECT count() FROM t WHERE s = $svc', + }), + [dataSourceFilter()], + ), + ).toBe(true); + }); }); describe('getBlockingRequiredFilterNames (connections)', () => { diff --git a/packages/common-utils/src/core/utils.ts b/packages/common-utils/src/core/utils.ts index d9b985546..c611a20ae 100644 --- a/packages/common-utils/src/core/utils.ts +++ b/packages/common-utils/src/core/utils.ts @@ -31,9 +31,11 @@ import { } from '@/macros'; import { QUERY_PARAMS, RawSqlQueryParam } from '@/rawSqlParams'; import { + buildReferenceChartVariables, configUsesReferenceVariable, getObjectName, getReferenceVariableFilters, + ReferenceVariableFilter, } from '@/referenceVariables'; import { BuilderChartConfig, @@ -57,7 +59,10 @@ import { TileTemplateSchema, TSource, } from '@/types'; -import { validateVariableReferencesInTemplate } from '@/variables'; +import { + configReferencesReferenceVariable, + validateVariableReferencesInTemplate, +} from '@/variables'; import { SkipIndexMetadata, TableMetadata } from './metadata'; @@ -1823,15 +1828,36 @@ export function displayTypeSupportsPromQLAlerts( return displayType ? false : false; } +/** + * Whether a config depends on a data source or connection variable: in its + * source or connection, or in text (SQL, expressions, markdown) referencing + * one that `filters` declare. Alerts run with every variable unselected, so + * such a config can't carry one. + */ +export function configDependsOnReferenceVariable( + config: SavedChartConfig, + filters: ReferenceVariableFilter[] | undefined, +): boolean { + return ( + configUsesReferenceVariable(config) || + configReferencesReferenceVariable( + config, + buildReferenceChartVariables(filters), + ) + ); +} + /** * Whether the alert checker can evaluate an alert on a tile with this config. * Shared by every save path so alerts are never stored where they cannot run. */ export function savedChartConfigSupportsAlerts( config: SavedChartConfig, + /** The dashboard's filters, so text references to its variables count. */ + filters?: ReferenceVariableFilter[], ): boolean { // An alert must query one fixed source, not the viewer's current selection. - if (configUsesReferenceVariable(config)) return false; + if (configDependsOnReferenceVariable(config, filters)) return false; if (isPromqlSavedChartConfig(config)) { return displayTypeSupportsPromQLAlerts(config.displayType); }