From 5035e69f34a70b811b96233513974c56848aba61 Mon Sep 17 00:00:00 2001 From: Drew Davis Date: Tue, 1 Dec 2026 16:08:14 -0500 Subject: [PATCH] feat: Allow referencing source and connection variables in text --- .changeset/source-variable-text-references.md | 7 + .../dashboards/queryTilesHandler.test.ts | 2 +- .../__tests__/dashboards/variables.test.ts | 186 +++++-- .../api/src/mcp/prompts/dashboards/content.ts | 14 + .../api/src/mcp/tools/dashboards/queryTile.ts | 6 +- .../src/mcp/tools/dashboards/queryTiles.ts | 6 +- .../src/mcp/tools/dashboards/validation.ts | 9 +- .../api/src/mcp/tools/dashboards/variables.ts | 149 +++++- packages/api/src/tasks/checkAlerts/index.ts | 9 +- packages/app/src/HDXMarkdownChart.tsx | 11 +- .../src/__tests__/HDXMarkdownChart.test.tsx | 49 ++ .../AdhocDashboardFilter.tsx | 11 +- .../__tests__/variableCompletions.test.ts | 55 +- .../SQLEditor/variableCompletions.tsx | 68 ++- .../components/alerts/AlertDetailChart.tsx | 6 +- .../__tests__/useDashboardFilters.test.tsx | 41 +- .../app/src/hooks/useDashboardFilters.tsx | 18 +- .../dashboard-source-variables.spec.ts | 52 ++ .../app/tests/e2e/features/dashboard.spec.ts | 3 +- .../__tests__/dashboardFilterValues.test.ts | 53 ++ .../src/__tests__/filters.test.ts | 34 ++ .../__tests__/variableReferenceFields.test.ts | 484 ++++++++++++++++++ .../src/__tests__/variables.test.ts | 2 +- .../common-utils/src/dashboardFilterValues.ts | 39 +- packages/common-utils/src/filters.ts | 15 +- packages/common-utils/src/macroErrors.ts | 14 + .../common-utils/src/referenceVariables.ts | 149 +++++- packages/common-utils/src/types.ts | 43 +- packages/common-utils/src/variables.ts | 265 +++++++++- 29 files changed, 1642 insertions(+), 158 deletions(-) create mode 100644 .changeset/source-variable-text-references.md create mode 100644 packages/common-utils/src/__tests__/variableReferenceFields.test.ts diff --git a/.changeset/source-variable-text-references.md b/.changeset/source-variable-text-references.md new file mode 100644 index 0000000000..a6bb0f1449 --- /dev/null +++ b/.changeset/source-variable-text-references.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': minor +'@hyperdx/app': minor +'@hyperdx/api': minor +--- + +feat: Reference DATA_SOURCE and CONNECTION dashboard variables in text diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts index 9bcf9dec8e..f5058963ea 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts @@ -22,7 +22,7 @@ jest.mock('@/mcp/tools/dashboards/variables', () => { return { ...actual, getReferenceTargets: () => - Promise.resolve({ sources: [], connectionIds: new Set() }), + Promise.resolve({ sources: [], connections: [] }), }; }); diff --git a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts index d50a56e33d..62c1f9b481 100644 --- a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts @@ -1,13 +1,16 @@ import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { substituteVariables } from '@hyperdx/common-utils/dist/variables'; import { fromAny } from '@total-typescript/shoehorn'; import mongoose from 'mongoose'; import { + type McpVariableValues, type ReferenceTargets, resolveDashboardVariables, resolveTileVariableReferences, withResolvedFilterVariableNames, } from '@/mcp/tools/dashboards/variables'; +import type { ExternalDashboard } from '@/routers/external-api/v2/utils/dashboards'; import type { ExternalDashboardFilterWithId, ExternalDashboardTileWithId, @@ -15,6 +18,8 @@ import type { const sourceId = new mongoose.Types.ObjectId().toString(); +const NO_TARGETS: ReferenceTargets = { sources: [], connections: [] }; + function filter( overrides: Partial = {}, ): ExternalDashboardFilterWithId { @@ -58,22 +63,32 @@ describe('resolveDashboardVariables', () => { // $__conditionalAll as macros, so a tile using one against a dashboard // that declares nothing fails with a message about the variable rather // than leaking macro text into ClickHouse. - expect(resolveDashboardVariables(undefined, undefined)).toEqual({ + expect(resolveDashboardVariables({}, undefined, NO_TARGETS)).toEqual({ variables: [], }); - expect(resolveDashboardVariables([], undefined)).toEqual({ + expect( + resolveDashboardVariables({ filters: [] }, undefined, NO_TARGETS), + ).toEqual({ variables: [], }); }); it('declares nothing for a broadcast-only filter', () => { - expect(resolveDashboardVariables([filter()], undefined)).toEqual({ + expect( + resolveDashboardVariables({ filters: [filter()] }, undefined, NO_TARGETS), + ).toEqual({ variables: [], }); }); it('defaults every declared variable to an empty selection', () => { - expect(resolveDashboardVariables([variableFilter], undefined)).toEqual({ + expect( + resolveDashboardVariables( + { filters: [variableFilter] }, + undefined, + NO_TARGETS, + ), + ).toEqual({ variables: [{ name: 'service', expression: 'ServiceName', values: [] }], }); }); @@ -81,8 +96,9 @@ describe('resolveDashboardVariables', () => { it('applies a supplied selection', () => { expect( resolveDashboardVariables( - [variableFilter], + { filters: [variableFilter] }, [{ name: 'service', values: ['checkout'] }], + NO_TARGETS, ), ).toEqual({ variables: [ @@ -101,8 +117,9 @@ describe('resolveDashboardVariables', () => { }); const resolved = resolveDashboardVariables( - [variableFilter, env], + { filters: [variableFilter, env] }, [{ name: 'service', values: ['checkout'] }], + NO_TARGETS, ); expect(resolved).toEqual({ @@ -115,8 +132,9 @@ describe('resolveDashboardVariables', () => { it('rejects a name the dashboard does not declare', () => { const resolved = resolveDashboardVariables( - [variableFilter], + { filters: [variableFilter] }, [{ name: 'tenant', values: ['acme'] }], + NO_TARGETS, ); expect(resolved).toHaveProperty('error'); @@ -127,8 +145,9 @@ describe('resolveDashboardVariables', () => { it('lists (none) when the dashboard declares no variables at all', () => { const resolved = resolveDashboardVariables( - [filter()], + { filters: [filter()] }, [{ name: 'service', values: ['checkout'] }], + NO_TARGETS, ); if (!('error' in resolved)) throw new Error('expected an error'); @@ -137,8 +156,9 @@ describe('resolveDashboardVariables', () => { it('rejects several values for a single-select variable', () => { const resolved = resolveDashboardVariables( - [staticFilter({ maxSelections: 1 })], + { filters: [staticFilter({ maxSelections: 1 })] }, [{ name: 'env', values: ['prod', 'staging'] }], + NO_TARGETS, ); if (!('error' in resolved)) throw new Error('expected an error'); @@ -149,8 +169,9 @@ describe('resolveDashboardVariables', () => { it('applies one value to a single-select variable', () => { expect( resolveDashboardVariables( - [staticFilter({ maxSelections: 1 })], + { filters: [staticFilter({ maxSelections: 1 })] }, [{ name: 'env', values: ['prod'] }], + NO_TARGETS, ), ).toEqual({ variables: [ @@ -165,7 +186,13 @@ describe('resolveDashboardVariables', () => { }); it('declares a variable for a static filter', () => { - expect(resolveDashboardVariables([staticFilter()], undefined)).toEqual({ + expect( + resolveDashboardVariables( + { filters: [staticFilter()] }, + undefined, + NO_TARGETS, + ), + ).toEqual({ variables: [{ name: 'env', expression: undefined, values: [] }], }); }); @@ -173,8 +200,9 @@ describe('resolveDashboardVariables', () => { it('applies a selection within a static filter options', () => { expect( resolveDashboardVariables( - [staticFilter()], + { filters: [staticFilter()] }, [{ name: 'env', values: ['prod', 'dev'] }], + NO_TARGETS, ), ).toEqual({ variables: [ @@ -186,8 +214,9 @@ describe('resolveDashboardVariables', () => { it('accepts an empty selection for a static filter', () => { expect( resolveDashboardVariables( - [staticFilter()], + { filters: [staticFilter()] }, [{ name: 'env', values: [] }], + NO_TARGETS, ), ).toEqual({ variables: [{ name: 'env', expression: undefined, values: [] }], @@ -196,8 +225,9 @@ describe('resolveDashboardVariables', () => { it('rejects a value outside a static filter options', () => { const resolved = resolveDashboardVariables( - [staticFilter()], + { filters: [staticFilter()] }, [{ name: 'env', values: ['prod', 'prod-2'] }], + NO_TARGETS, ); if (!('error' in resolved)) throw new Error('expected an error'); @@ -215,11 +245,12 @@ describe('resolveDashboardVariables', () => { }); const resolved = resolveDashboardVariables( - [staticFilter(), tier], + { filters: [staticFilter(), tier] }, [ { name: 'env', values: ['nope'] }, { name: 'tier', values: ['enterprise'] }, ], + NO_TARGETS, ); if (!('error' in resolved)) throw new Error('expected an error'); @@ -230,8 +261,9 @@ describe('resolveDashboardVariables', () => { it('leaves query-expression variables unconstrained', () => { expect( resolveDashboardVariables( - [variableFilter], + { filters: [variableFilter] }, [{ name: 'service', values: ['anything-at-all'] }], + NO_TARGETS, ), ).toEqual({ variables: [ @@ -247,8 +279,9 @@ describe('resolveDashboardVariables', () => { it('truncates the options preview in the error', () => { const options = Array.from({ length: 25 }, (_, i) => `opt${i}`); const resolved = resolveDashboardVariables( - [staticFilter({ options })], + { filters: [staticFilter({ options })] }, [{ name: 'env', values: ['nope'] }], + NO_TARGETS, ); if (!('error' in resolved)) throw new Error('expected an error'); @@ -260,8 +293,9 @@ describe('resolveDashboardVariables', () => { const shadowed = staticFilter({ variableName: 'service' }); expect( resolveDashboardVariables( - [variableFilter, shadowed], + { filters: [variableFilter, shadowed] }, [{ name: 'service', values: ['not-an-option'] }], + NO_TARGETS, ), ).toEqual({ variables: [ @@ -276,11 +310,12 @@ describe('resolveDashboardVariables', () => { it('lets the last entry win on a repeated name', () => { const resolved = resolveDashboardVariables( - [variableFilter], + { filters: [variableFilter] }, [ { name: 'service', values: ['a'] }, { name: 'service', values: ['b'] }, ], + NO_TARGETS, ); expect(resolved).toEqual({ @@ -330,6 +365,14 @@ describe('withResolvedFilterVariableNames', () => { }); }); +const target = (id: string, kind: SourceKind, connection: string) => ({ + id, + kind, + connection, + name: `${kind} source`, + from: { databaseName: 'default', tableName: `${kind}_table` }, +}); + describe('resolveTileVariableReferences', () => { const objectId = () => new mongoose.Types.ObjectId().toString(); const connectionId = objectId(); @@ -341,17 +384,16 @@ describe('resolveTileVariableReferences', () => { const otherConnectionLogSourceId = objectId(); const targets: ReferenceTargets = { sources: [ - { id: traceSourceId, kind: SourceKind.Trace, connection: connectionId }, - { id: logSourceId, kind: SourceKind.Log, connection: connectionId }, - { id: metricSourceId, kind: SourceKind.Metric, connection: connectionId }, - { id: promqlSourceId, kind: SourceKind.Promql, connection: connectionId }, - { - id: otherConnectionLogSourceId, - kind: SourceKind.Log, - connection: otherConnectionId, - }, + target(traceSourceId, SourceKind.Trace, connectionId), + target(logSourceId, SourceKind.Log, connectionId), + target(metricSourceId, SourceKind.Metric, connectionId), + target(promqlSourceId, SourceKind.Promql, connectionId), + target(otherConnectionLogSourceId, SourceKind.Log, otherConnectionId), + ], + connections: [ + { id: connectionId, name: 'Main' }, + { id: otherConnectionId, name: 'Other' }, ], - connectionIds: new Set([connectionId, otherConnectionId]), }; const referenceVariableFields = { @@ -608,3 +650,89 @@ describe('resolveTileVariableReferences', () => { }); }); }); + +describe('resolveDashboardVariables with data source and connection variables', () => { + const objectId = () => new mongoose.Types.ObjectId().toString(); + const connectionId = objectId(); + const logSourceId = objectId(); + const traceSourceId = objectId(); + const targets: ReferenceTargets = { + sources: [ + target(logSourceId, SourceKind.Log, connectionId), + target(traceSourceId, SourceKind.Trace, connectionId), + ], + connections: [{ id: connectionId, name: 'Main' }], + }; + const filters: ExternalDashboardFilterWithId[] = [ + { + id: objectId(), + type: 'DATA_SOURCE', + name: 'Source', + variableName: 'src', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + { + id: objectId(), + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ]; + + const expand = ( + variableValues: McpVariableValues | undefined, + savedFilterValues: ExternalDashboard['savedFilterValues'] = undefined, + ) => { + const resolved = resolveDashboardVariables( + { filters, savedFilterValues }, + variableValues, + targets, + ); + if ('error' in resolved) throw new Error(resolved.error); + return substituteVariables('SELECT ${conn.name} FROM $src', { + variables: resolved.variables, + inputLanguage: 'sql', + }); + }; + + it('expands text references to the selected source and connection', () => { + expect( + expand([ + { name: 'src', values: [logSourceId] }, + { name: 'conn', values: [connectionId] }, + ]), + ).toBe("SELECT 'Main' FROM `default`.`log_table`"); + }); + + it('falls back to the saved selection', () => { + expect( + expand(undefined, [ + { type: 'variable', name: 'src', values: [logSourceId] }, + ]), + ).toBe('SELECT FROM `default`.`log_table`'); + }); + + it('expands a selection the variable would not offer to nothing', () => { + expect(expand([{ name: 'src', values: [traceSourceId] }])).toBe( + 'SELECT FROM ', + ); + }); + + it('still rejects an unknown variable name', () => { + expect( + resolveDashboardVariables( + { filters, savedFilterValues: undefined }, + [{ name: 'nope', values: ['x'] }], + targets, + ), + ).toEqual({ error: expect.stringContaining('nope') }); + }); +}); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index 273fb97e7f..121be08f64 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -1297,6 +1297,20 @@ Only add one when the default is wrong. \${service:sqlstring} is redundant in a promql a or (a|b) "" or .* the default in PromQL; a single-select variable (maxSelections: 1) renders its raw value for {label="$var"}, a multi-select one an escaped regex for {label=~"$var"} csv a,b use INSIDE a string literal markdown a, b the default in markdown tiles; markdown syntax in values is escaped + sqlidentifier \`a\`, \`b c\` backtick-quotes each value, for a table, database, or column name + +DATA_SOURCE AND CONNECTION VARIABLES IN TEXT + +Besides sourceId / connectionId, a DATA_SOURCE or CONNECTION variable can be referenced in any text input. Use the braced form to read a field. + $src / \${src} the source's database.table (a connection's name) + \${src.table} the table name + \${src.database} the database name + \${src.name} the source's (or connection's) display name + \${src.id} the source's (or connection's) ID + \${src.table.} a metric source's gauge, sum, histogram, summary, or exponential_histogram table. Always required for a metric source. +In SQL, table and database references default to the sqlidentifier format (FROM $src renders FROM \`default\`.\`otel_logs\`) and names to sqlstring. In markdown, every field defaults to markdown. Formats combine with fields, as in \${src.name:csv}. On the dashboard, a tile that references an unselected variable waits for a selection, like one with sourceId: "$src"; a markdown tile renders the reference as nothing. $__filter and $__conditionalAll do not accept these variables. + sqlTemplate: "SELECT count() FROM $src WHERE $__timeFilter(Timestamp)" + markdown: "Showing \${src.name}" BUILDER TILES diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index 6d07d8e299..d3a2079fe5 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -91,9 +91,11 @@ export function registerQueryTile({ ); } + const referenceTargets = await getReferenceTargets(context); const resolvedVariables = resolveDashboardVariables( - externalDashboard.filters, + externalDashboard, variableValues, + referenceTargets, ); if ('error' in resolvedVariables) { return mcpUserError(resolvedVariables.error); @@ -104,7 +106,7 @@ export function registerQueryTile({ externalDashboard.filters, variableValues, externalDashboard.savedFilterValues, - await getReferenceTargets(context), + referenceTargets, ); if ('error' in resolvedTile) { return mcpUserError(resolvedTile.error); diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index b87293cc68..c9c95b345c 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -215,9 +215,11 @@ export function registerQueryTiles({ }); const allTiles = externalDashboard.tiles; + const referenceTargets = await getReferenceTargets(context); const resolved = resolveDashboardVariables( - externalDashboard.filters, + externalDashboard, variableValues, + referenceTargets, ); if ('error' in resolved) { return mcpUserError(resolved.error); @@ -258,8 +260,6 @@ export function registerQueryTiles({ .slice(MAX_TILES_PER_CALL) .map(t => t.id); - const referenceTargets = await getReferenceTargets(context); - // Fix one shared deadline for the whole batch that every tile races. const deadlineAt = Date.now() + BATCH_DEADLINE_MS; diff --git a/packages/api/src/mcp/tools/dashboards/validation.ts b/packages/api/src/mcp/tools/dashboards/validation.ts index 65eb0b204e..37efeb58e5 100644 --- a/packages/api/src/mcp/tools/dashboards/validation.ts +++ b/packages/api/src/mcp/tools/dashboards/validation.ts @@ -21,6 +21,7 @@ import { INTERVAL_MACROS, TIME_RANGE_MACROS, } from '@hyperdx/common-utils/dist/macros'; +import { getEmptyDashboardVariables } from '@hyperdx/common-utils/dist/referenceVariables'; import { AdhocFilterSourceType, AdhocFilterValue, @@ -190,9 +191,7 @@ export function getFilterVariableWarnings( ): string[] { if (!filters?.length) return []; - const variables = getDashboardVariableDeclarations(filters).map( - declaration => ({ ...declaration, values: [] }), - ); + const variables = getEmptyDashboardVariables(filters); const declaredNames = new Set(variables.map(variable => variable.name)); // A map from variable name to to the name of the filter that collects it but is not variable-enabled. @@ -363,9 +362,7 @@ export function getTileVariableWarnings( tiles: ExternalDashboardTileWithId[], filters: FilterForVariableDeclaration[] | undefined, ): string[] { - const variables = getDashboardVariableDeclarations(filters).map( - declaration => ({ ...declaration, values: [] }), - ); + const variables = getEmptyDashboardVariables(filters); const warnings: string[] = []; tiles.forEach((tile, index) => { diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index a20432df58..774b1f5cae 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -8,14 +8,17 @@ import { } from '@hyperdx/common-utils/dist/filters'; import { getSavedConfigAllowedSourceKinds } from '@hyperdx/common-utils/dist/guards'; import { + buildReferenceChartVariables, getReferenceVariableFilters, getStringField, isSourceOfferedByVariable, parseVariableReference, + type ReferenceVariableConnection, + type ReferenceVariableSource, } from '@hyperdx/common-utils/dist/referenceVariables'; -import type { - ChartVariable, - SavedChartConfig, +import { + type ChartVariable, + type SavedChartConfig, SourceKind, } from '@hyperdx/common-utils/dist/types'; import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables'; @@ -75,7 +78,7 @@ export const mcpVariableValuesParam = z export type McpVariableValues = z.infer; /** - * Build the variable context a dashboard tile runs with. + * The value variables a dashboard tile runs with. * * The declarations come from the dashboard's variable-enabled filters, with * every selection empty by default. @@ -84,7 +87,7 @@ export type McpVariableValues = z.infer; * it is the agent's own input, and a typo would otherwise run the query with * the variable still empty and look like a data problem. */ -export function resolveDashboardVariables( +function resolveValueVariables( filters: | (ExternalDashboardFilter | ExternalDashboardFilterWithId)[] | undefined, @@ -165,13 +168,12 @@ export function resolveDashboardVariables( /** The team's sources and connections that a reference variable may select. */ export type ReferenceTargets = { - sources: { - id: string; + sources: (ReferenceVariableSource & { kind: SourceKind; connection: string; disabled?: boolean; - }[]; - connectionIds: ReadonlySet; + })[]; + connections: ReferenceVariableConnection[]; }; export async function getReferenceTargets( @@ -184,32 +186,29 @@ export async function getReferenceTargets( return { sources: sources.map(source => ({ id: source._id.toString(), + name: source.name, + from: source.from, + metricTables: + source.kind === SourceKind.Metric ? source.metricTables : undefined, kind: source.kind, connection: source.connection.toString(), disabled: source.disabled, })), - connectionIds: new Set(connections.map(c => c._id.toString())), + connections: connections.map(c => ({ + id: c._id.toString(), + name: c.name, + })), }; } /** - * Replace a tile's `$name` sourceId / connectionId with the source or - * connection its data source or connection variable selects: the caller's - * variableValues first, then the dashboard's saved selection. A tile with no - * selection cannot run, as on the dashboard, so that is an error naming the - * variable. So is a selection the dashboard's picker would not offer, such as - * a source of another kind or on another connection. + * Each variable's selection for a tile run: the caller's variableValues + * first, then the dashboard's saved selection. */ -export function resolveTileVariableReferences< - T extends ExternalDashboardTileWithId, ->( - tile: T, - filters: ExternalFilters, +function getVariableSelections( variableValues: McpVariableValues | undefined, savedFilterValues: ExternalDashboard['savedFilterValues'] | undefined, - targets: ReferenceTargets, -): { tile: T } | { error: string } { - if (!('config' in tile) || tile.config == null) return { tile }; +): Map { const selections = new Map(); for (const value of savedFilterValues ?? []) { if (value.type === 'variable') selections.set(value.name, value.values); @@ -218,6 +217,15 @@ export function resolveTileVariableReferences< for (const { name, values } of variableValues ?? []) { selections.set(name, values); } + return selections; +} + +/** The data source variables a dashboard declares, and which sources each offers. */ +function getSourceVariableOffers( + filters: ExternalFilters, + selections: ReadonlyMap, + targets: ReferenceTargets, +) { const sourceVariables = new Map( getReferenceVariableFilters(filters).flatMap(({ filter, name }) => isDataSourceFilter(filter) ? [[name, filter] as const] : [], @@ -240,6 +248,97 @@ export function resolveTileVariableReferences< }); }; + return { sourceVariables, isSourceOffered }; +} + +/** + * The data source and connection variables a dashboard declares, as text + * references (`$src`, `${src.table}`) expand against. Selected the same way + * `resolveTileVariableReferences` selects them; a selection the dashboard + * wouldn't offer is treated as no selection, which expands to nothing. + */ +function getReferenceChartVariables( + filters: ExternalFilters, + variableValues: McpVariableValues | undefined, + savedFilterValues: ExternalDashboard['savedFilterValues'] | undefined, + targets: ReferenceTargets, +): ChartVariable[] { + const selections = getVariableSelections(variableValues, savedFilterValues); + const { isSourceOffered } = getSourceVariableOffers( + filters, + selections, + targets, + ); + const selectedIds = new Map( + getReferenceVariableFilters(filters).flatMap(({ filter, name }) => { + const values = selections.get(name) ?? []; + if (values.length !== 1) return []; + const [id] = values; + const isOffered = isDataSourceFilter(filter) + ? isSourceOffered(name, id) + : targets.connections.some(connection => connection.id === id); + return isOffered ? [[name, id] as const] : []; + }), + ); + return buildReferenceChartVariables(filters, { + values: selectedIds, + sources: targets.sources, + connections: targets.connections, + }); +} + +/** + * Build the variable context a dashboard tile runs with: its value variables, + * plus the data source and connection variables its text can reference. + */ +export function resolveDashboardVariables( + dashboard: { + filters?: ExternalFilters; + savedFilterValues?: ExternalDashboard['savedFilterValues']; + }, + variableValues: McpVariableValues | undefined, + targets: ReferenceTargets, +): { variables: ChartVariable[] } | { error: string } { + const resolved = resolveValueVariables(dashboard.filters, variableValues); + if ('error' in resolved) return resolved; + return { + variables: [ + ...resolved.variables, + ...getReferenceChartVariables( + dashboard.filters, + variableValues, + dashboard.savedFilterValues, + targets, + ), + ], + }; +} + +/** + * Replace a tile's `$name` sourceId / connectionId with the source or + * connection its data source or connection variable selects: the caller's + * variableValues first, then the dashboard's saved selection. A tile with no + * selection cannot run, as on the dashboard, so that is an error naming the + * variable. So is a selection the dashboard's picker would not offer, such as + * a source of another kind or on another connection. + */ +export function resolveTileVariableReferences< + T extends ExternalDashboardTileWithId, +>( + tile: T, + filters: ExternalFilters, + variableValues: McpVariableValues | undefined, + savedFilterValues: ExternalDashboard['savedFilterValues'] | undefined, + targets: ReferenceTargets, +): { tile: T } | { error: string } { + if (!('config' in tile) || tile.config == null) return { tile }; + const selections = getVariableSelections(variableValues, savedFilterValues); + const { sourceVariables, isSourceOffered } = getSourceVariableOffers( + filters, + selections, + targets, + ); + const describeOffer = (name: string) => { const variable = sourceVariables.get(name); if (variable == null) return 'no sources'; @@ -270,7 +369,7 @@ export function resolveTileVariableReferences< const [id] = values; const isOffered = field === 'connectionId' - ? targets.connectionIds.has(id) + ? targets.connections.some(connection => connection.id === id) : isSourceOffered(name, id); if (!isOffered) { const offer = diff --git a/packages/api/src/tasks/checkAlerts/index.ts b/packages/api/src/tasks/checkAlerts/index.ts index 7837d02587..3ad99caada 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/HDXMarkdownChart.tsx b/packages/app/src/HDXMarkdownChart.tsx index bcd858c2b1..01528de015 100644 --- a/packages/app/src/HDXMarkdownChart.tsx +++ b/packages/app/src/HDXMarkdownChart.tsx @@ -76,8 +76,15 @@ const HDXMarkdownChart = memo( // Without variables in scope nothing is substituted, so a `$word` is prose. if (!markdown || !names?.length) return toolbarItems; - // Only names are checked for markdown, so the selections don't matter. - const allVariables = names.map(name => ({ name, values: [] })); + // Unreferenced names only need to exist; referenced ones keep their + // reference data, which decides whether a field like `${src.name}` is valid. + const allVariables = names.map( + name => + referencedVariables?.find(variable => variable.name === name) ?? { + name, + values: [], + }, + ); const issues = validateVariableReferencesInTemplate( markdown, allVariables, diff --git a/packages/app/src/__tests__/HDXMarkdownChart.test.tsx b/packages/app/src/__tests__/HDXMarkdownChart.test.tsx index 46b3849023..d9fb1e6ab3 100644 --- a/packages/app/src/__tests__/HDXMarkdownChart.test.tsx +++ b/packages/app/src/__tests__/HDXMarkdownChart.test.tsx @@ -1,4 +1,6 @@ import React from 'react'; +import { buildReferenceChartVariables } from '@hyperdx/common-utils/dist/referenceVariables'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; import { screen } from '@testing-library/react'; import HDXMarkdownChart from '@/HDXMarkdownChart'; @@ -87,6 +89,53 @@ describe('HDXMarkdownChart', () => { expect(screen.queryByTestId('variable-validation')).not.toBeInTheDocument(); }); + it('renders data source and connection fields without flagging them', () => { + const referenceVariables = buildReferenceChartVariables( + [ + { + type: 'CONNECTION', + name: 'Connection', + variableName: 'Connection', + }, + { + type: 'DATA_SOURCE', + name: 'Logs', + variableName: 'Logs', + allowedSourceKinds: [SourceKind.Log], + }, + ], + { + values: new Map([ + ['Connection', 'conn-1'], + ['Logs', 'logs-1'], + ]), + connections: [{ id: 'conn-1', name: 'Prod' }], + sources: [ + { + id: 'logs-1', + name: 'My logs', + from: { databaseName: 'default', tableName: 'otel_logs' }, + }, + ], + }, + ); + + renderWithMantine( + , + ); + + expect( + screen.getByText('Connection: Prod, source: My logs'), + ).toBeInTheDocument(); + expect(screen.queryByTestId('variable-validation')).not.toBeInTheDocument(); + }); + it('flags nothing when every reference is known', () => { renderWithMantine( referencedNames.has(name)) - .map(({ filter: blocking }) => blocking.name), + blockingFilterNames: getFiltersDeclaringVariables( + unsatisfiedRequiredFilters ?? [], + referencedNames, + ).map(blocking => blocking.name), }; }, [ filter.sourceType, diff --git a/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts b/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts index 31b91cbcc8..83147e3377 100644 --- a/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts +++ b/packages/app/src/components/SQLEditor/__tests__/variableCompletions.test.ts @@ -1,4 +1,9 @@ -import { ChartVariable } from '@hyperdx/common-utils/dist/types'; +import { buildReferenceChartVariables } from '@hyperdx/common-utils/dist/referenceVariables'; +import { + ChartVariable, + MetricsDataType, + SourceKind, +} from '@hyperdx/common-utils/dist/types'; import { buildLuceneVariableSuggestions, @@ -12,6 +17,34 @@ const SERVICE: ChartVariable = { expression: 'ServiceName', }; +const [METRICS] = buildReferenceChartVariables( + [ + { + type: 'DATA_SOURCE', + name: 'Metrics source', + variableName: 'm', + allowedSourceKinds: [SourceKind.Metric], + }, + ], + { + values: new Map([['m', 'metrics']]), + sources: [ + { + id: 'metrics', + name: 'Metrics', + from: { databaseName: 'default', tableName: '' }, + metricTables: { + [MetricsDataType.Gauge]: 'otel_gauge', + [MetricsDataType.Histogram]: '', + [MetricsDataType.Sum]: 'otel_sum', + [MetricsDataType.Summary]: '', + [MetricsDataType.ExponentialHistogram]: '', + }, + }, + ], + }, +); + const labels = (variables: ChartVariable[] | undefined) => buildSqlVariableCompletions(variables).map(completion => completion.label); @@ -49,10 +82,26 @@ describe('buildSqlVariableCompletions', () => { '${service:csv}', '${service:regex}', '${service:lucene}', + '${service:sqlidentifier}', ]), ); }); + it('offers the fields the selected source renders', () => { + expect(labels([METRICS])).toEqual([ + '$__filter', + '$__conditionalAll', + '${m.table.gauge}', + '${m.table.sum}', + '${m.database}', + '${m.name}', + '${m.id}', + ]); + expect(footnoteOf([METRICS], '${m.table.sum}')).toBe( + 'Expands to: `otel_sum`', + ); + }); + it('withholds the markdown and promql formats, which only apply elsewhere', () => { expect(labels([SERVICE])).not.toContain('${service:markdown}'); expect(labels([SERVICE])).not.toContain('${service:promql}'); @@ -115,6 +164,10 @@ describe('buildLuceneVariableSuggestions', () => { expect(buildLuceneVariableSuggestions(variables)).toEqual([]); }); + it('leaves out data source variables', () => { + expect(buildLuceneVariableSuggestions([METRICS])).toEqual([]); + }); + it('offers the bare reference and nothing else', () => { // No macros: they expand to SQL predicates a Lucene parser cannot read. // No braced or explicit-format forms either — in a Lucene input the bare diff --git a/packages/app/src/components/SQLEditor/variableCompletions.tsx b/packages/app/src/components/SQLEditor/variableCompletions.tsx index 10df934e5b..efd4469767 100644 --- a/packages/app/src/components/SQLEditor/variableCompletions.tsx +++ b/packages/app/src/components/SQLEditor/variableCompletions.tsx @@ -4,8 +4,13 @@ import { MacroSuggestion, VARIABLE_MACRO_SUGGESTIONS, } from '@hyperdx/common-utils/dist/macros'; -import { ChartVariable } from '@hyperdx/common-utils/dist/types'; import { + ChartReferenceVariable, + ChartVariable, +} from '@hyperdx/common-utils/dist/types'; +import { + getReferenceFieldReferences, + hasSelection, isFilterSingleSelect, substituteVariables, TemplateLanguage, @@ -26,6 +31,8 @@ const COMPLETION_FORMATS: Record< sqlstring: "Quoted and comma-separated, escaped for SQL. e.g. 'a', 'b', 'c'", csv: 'Comma-separated and unquoted. Not SQL-escaped. e.g. a,b,c', + sqlidentifier: + 'Comma-separated identifiers, each backtick-quoted. e.g. `a`, `b c`', regex: 'A regex alternation. Regex escaped. e.g. (a|b|c)', lucene: 'An OR of quoted terms, for Lucene inputs. e.g. ("a" OR "b" OR "c"). Quote the reference (field:"$var") for exact-match behavior. Leave unquoted (field:$var) for substring matching.', @@ -137,9 +144,34 @@ function variableCompletionFactory( }; } +/** + * The field references a data source or connection variable offers, each with + * its current expansion. + */ +function getReferenceVariableCompletions( + variable: ChartVariable, + reference: ChartReferenceVariable, + language: TemplateLanguage, +): SQLCompletion[] { + const { name } = variable; + const buildCompletion = variableCompletionFactory(variable, language); + return getReferenceFieldReferences(name, reference).map( + ({ field, reference: label }) => + buildCompletion( + label, + field === '' + ? `The ${reference.noun} ${name} selects.` + : `The ${field} of the ${reference.noun} ${name} selects.`, + ), + ); +} + /** Every reference form available in SQL for the given variable, each with its current expansion. */ function getSqlVariableCompletions(variable: ChartVariable): SQLCompletion[] { const { name } = variable; + if (variable.reference) { + return getReferenceVariableCompletions(variable, variable.reference, 'sql'); + } const buildCompletion = variableCompletionFactory(variable, 'sql'); return [ @@ -184,6 +216,13 @@ function getPromqlVariableCompletions( variable: ChartVariable, ): SQLCompletion[] { const { name } = variable; + if (variable.reference) { + return getReferenceVariableCompletions( + variable, + variable.reference, + 'promql', + ); + } const reference = variableCompletionFactory(variable, 'promql'); return [ @@ -230,7 +269,8 @@ const substituteLucene = (text: string, variables: ChartVariable[]) => /** * Suggestions for a Lucene expression: the bare `$name` reference of each - * variable, and nothing else. + * value variable, and nothing else. A data source or connection variable is + * left out, since its table or name is rarely a useful Lucene term. * * The macros are deliberately absent — they expand to SQL predicates, and * the lucene format empty state `("")` is safe without needing macros. @@ -238,15 +278,17 @@ const substituteLucene = (text: string, variables: ChartVariable[]) => export function buildLuceneVariableSuggestions( variables: ChartVariable[] | undefined, ): LuceneVariableSuggestion[] { - return (variables ?? []).map(variable => { - const reference = `$${variable.name}`; - const expansion = substituteLucene(reference, [variable]); - return { - value: reference, - label: reference, - description: `The selected values of ${variable.name}. Expands to: ${expansion} by default, or (Field:"value1" OR Field:"value2") when quoted like Field:"$${variable.name}".`, - }; - }); + return (variables ?? []) + .filter(variable => variable.reference == null) + .map(variable => { + const reference = `$${variable.name}`; + const expansion = substituteLucene(reference, [variable]); + return { + value: reference, + label: reference, + description: `The selected values of ${variable.name}. Expands to: ${expansion} by default, or (Field:"value1" OR Field:"value2") when quoted like Field:"$${variable.name}".`, + }; + }); } /** @@ -267,9 +309,7 @@ export function expandLuceneVariablesForEnglishDisplay( text: string, variables: ChartVariable[] | undefined, ): string { - const selected = (variables ?? []).filter( - variable => variable.values.length > 0, - ); + const selected = (variables ?? []).filter(hasSelection); if (selected.length === 0) return text; try { return substituteLucene(text, selected); diff --git a/packages/app/src/components/alerts/AlertDetailChart.tsx b/packages/app/src/components/alerts/AlertDetailChart.tsx index 60608d154e..213cf4023b 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/src/hooks/__tests__/useDashboardFilters.test.tsx b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx index 11a37c787d..912b72d5b7 100644 --- a/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx +++ b/packages/app/src/hooks/__tests__/useDashboardFilters.test.tsx @@ -3,11 +3,13 @@ import { AdhocDashboardFilter, AdhocFilterCondition, BroadcastFilter, + ChartVariable, DashboardFilter, DashboardFilterValue, QueryExpressionDashboardFilter, SourceKind, } from '@hyperdx/common-utils/dist/types'; +import { substituteVariables } from '@hyperdx/common-utils/dist/variables'; import { act, renderHook } from '@testing-library/react'; import useDashboardFilters from '@/hooks/useDashboardFilters'; @@ -1525,6 +1527,9 @@ describe('useDashboardFilters', () => { }); }); describe('data source variables', () => { + const expandSql = (template: string, variables: ChartVariable[]) => + substituteVariables(template, { variables, inputLanguage: 'sql' }); + const dataSourceFilter: DashboardFilter = { id: 'ds', type: 'DATA_SOURCE', @@ -1545,7 +1550,7 @@ describe('useDashboardFilters', () => { appliesToSourceIds: ['$logs'], }; - it('exposes the selected source by variable name, not as a text variable', () => { + it('exposes the selected source by variable name', () => { mockState = [{ type: 'variable', name: 'logs', values: ['src-1'] }]; const { result } = renderHook(() => useDashboardFilters([dataSourceFilter]), @@ -1554,11 +1559,32 @@ describe('useDashboardFilters', () => { expect(result.current.referenceVariableValues).toEqual( new Map([['logs', 'src-1']]), ); - expect(result.current.variables).toEqual([]); + expect(expandSql('FROM $logs', result.current.variables)).toBe('FROM '); expect(result.current.ignoredVariableNames).toEqual([]); expect(result.current.unsatisfiedRequiredFilters).toEqual([]); }); + it('exposes the selected source to text references', () => { + mockState = [{ type: 'variable', name: 'logs', values: ['src-1'] }]; + const { result } = renderHook(() => + useDashboardFilters([dataSourceFilter], { + sources: [ + { + id: 'src-1', + name: 'My logs', + kind: SourceKind.Log, + connection: 'conn-1', + from: { databaseName: 'default', tableName: 'otel_logs' }, + }, + ], + }), + ); + + expect( + expandSql('SELECT ${logs.name} FROM $logs', result.current.variables), + ).toBe("SELECT 'My logs' FROM `default`.`otel_logs`"); + }); + it('exposes connection variables and resolves filter connections', () => { const connectionFilter: DashboardFilter = { id: 'conn', @@ -1585,7 +1611,10 @@ describe('useDashboardFilters', () => { expect(result.current.resolvedFilters[1]).toMatchObject({ connection: 'conn-1', }); - expect(result.current.variables).toEqual([]); + expect(result.current.variables.map(({ name }) => name)).toEqual([ + 'cluster', + 'logs', + ]); }); describe('a selection the variable no longer offers', () => { @@ -1609,12 +1638,14 @@ describe('useDashboardFilters', () => { name: 'Logs A', kind: SourceKind.Log, connection: 'conn-a', + from: { databaseName: 'default', tableName: 'logs' }, }, { id: 'traces-a', name: 'Traces A', kind: SourceKind.Trace, connection: 'conn-a', + from: { databaseName: 'default', tableName: 'logs' }, }, ]; const render = ( @@ -1701,18 +1732,21 @@ describe('useDashboardFilters', () => { name: 'Logs', kind: SourceKind.Log, connection: 'conn-a', + from: { databaseName: 'default', tableName: 'logs' }, }, { id: 'logs-b', name: 'Logs', kind: SourceKind.Log, connection: 'conn-b', + from: { databaseName: 'default', tableName: 'logs' }, }, { id: 'traces-a', name: 'Traces', kind: SourceKind.Trace, connection: 'conn-a', + from: { databaseName: 'default', tableName: 'logs' }, }, ]; const render = ( @@ -1832,6 +1866,7 @@ describe('useDashboardFilters', () => { name: 'Metrics', kind: SourceKind.Metric, connection: 'conn-a', + from: { databaseName: 'default', tableName: 'logs' }, }, ]; mockState = [{ type: 'variable', name: 'logs', values: ['metric-1'] }]; diff --git a/packages/app/src/hooks/useDashboardFilters.tsx b/packages/app/src/hooks/useDashboardFilters.tsx index 61d8500256..bbd188d683 100644 --- a/packages/app/src/hooks/useDashboardFilters.tsx +++ b/packages/app/src/hooks/useDashboardFilters.tsx @@ -29,10 +29,12 @@ import { mergeAdhocConditions, } from '@hyperdx/common-utils/dist/filters'; import { + buildReferenceChartVariables, getConnectionVariableFilters, getReferenceVariableFilters, getSourceVariableFilters, isSourceOfferedByVariable, + ReferenceVariableSource, ReferenceVariableValues, resolveFilterReferences, resolveVariableReference, @@ -149,12 +151,11 @@ const useDashboardFilters = ( /** * The team's sources. While given, a data source variable's selection * may name a source instead of holding its ID, and a selection that the - * variable no longer offers counts as no selection. + * variable no longer offers counts as no selection. Text references to + * the variable (`$src`, `${src.table}`) read the selected source's tables. */ - sources?: readonly Pick< - TSource, - 'id' | 'name' | 'kind' | 'connection' | 'disabled' - >[]; + sources?: readonly (ReferenceVariableSource & + Pick)[]; /** * The team's connections. While given, a connection variable's selection * may name a connection instead of holding its ID. @@ -356,6 +357,13 @@ const useDashboardFilters = ( selectedId(filter.id), ]), ); + variables.push( + ...buildReferenceChartVariables(filters, { + values: referenceVariableValues, + sources, + connections, + }), + ); return { selectionByFilterId, 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 71c7e87333..534f2ddea6 100644 --- a/packages/app/tests/e2e/features/dashboard-source-variables.spec.ts +++ b/packages/app/tests/e2e/features/dashboard-source-variables.spec.ts @@ -290,6 +290,58 @@ test.describe( }); }); + test('substitutes the selected source into SQL and markdown text', async () => { + const editor = dashboardPage.chartEditor; + + await test.step('Create a data source variable', async () => { + await dashboardPage.createNewDashboard(); + await dashboardPage.openEditFiltersModal(); + await dashboardPage.addDataSourceFilterToDashboard( + 'Logs source', + ['Logs'], + 'logs', + ); + await dashboardPage.closeFiltersModal(); + }); + + await test.step('A raw SQL tile reads its table from the variable', async () => { + await dashboardPage.addTile(); + await expect(editor.nameInput).toBeVisible(); + await editor.waitForDataToLoad(); + await editor.setChartType(DisplayType.Number); + await editor.setChartName('Text reference count'); + await editor.switchToSqlMode(); + await editor.typeSqlQuery('SELECT count() FROM $logs'); + await editor.save(); + await expect( + dashboardPage.getTileMissingRequiredFilters(0), + ).toContainText('Logs source'); + }); + + await test.step('A markdown tile names the selected source', async () => { + await dashboardPage.addMarkdownTile( + 'Source note', + 'Reading from ${logs.name}', + ); + await expect(dashboardPage.getTile(1)).toContainText('Reading from'); + await expect(dashboardPage.getTile(1)).not.toContainText('${logs'); + }); + + await test.step('Selecting a source fills in both tiles', async () => { + await dashboardPage.selectReferenceFilterValue( + 'Logs source', + DEFAULT_LOGS_SOURCE_NAME, + ); + await expect( + dashboardPage.getTileMissingRequiredFilters(0), + ).toHaveCount(0); + await expect(dashboardPage.getNumberTileValue(0)).toBeVisible(); + await expect(dashboardPage.getTile(1)).toContainText( + `Reading from ${DEFAULT_LOGS_SOURCE_NAME}`, + ); + }); + }); + // A filter edit can leave other filters with a variable they can't always // use. It still saves, and the filter shows an error while it can't. test("saves a kind other filters can't use, and flags them while it's selected", async ({ diff --git a/packages/app/tests/e2e/features/dashboard.spec.ts b/packages/app/tests/e2e/features/dashboard.spec.ts index 2d6d864d05..d86e41c51f 100644 --- a/packages/app/tests/e2e/features/dashboard.spec.ts +++ b/packages/app/tests/e2e/features/dashboard.spec.ts @@ -1945,13 +1945,14 @@ test.describe('Dashboard', { tag: ['@dashboard'] }, () => { // entries the popup is empty the moment the brace is typed. await dashboardPage.chartEditor.replaceSqlQuery('${'); const options = dashboardPage.chartEditor.sqlCompletionOptions(); - await expect(options).toHaveCount(5); + await expect(options).toHaveCount(6); // Compared as a set: ranking between equally-good matches is // CodeMirror's business, not something worth pinning here. expect((await options.allTextContents()).sort()).toEqual( [ '${svc}', '${svc:sqlstring}', + '${svc:sqlidentifier}', '${svc:regex}', '${svc:csv}', '${svc:lucene}', diff --git a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts index 300e037754..4ce6707304 100644 --- a/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts +++ b/packages/common-utils/src/__tests__/dashboardFilterValues.test.ts @@ -4,6 +4,7 @@ import { getAdhocFilterTargetsForTile, getBlockingRequiredFilterNames, getBlockingRequiredFilters, + getFiltersDeclaringVariables, getUnsatisfiedRequiredFilters, parseDashboardFilterValues, resolveFilterSelection, @@ -22,6 +23,7 @@ import type { SavedChartConfig, StaticListDashboardFilter, } from '@/types'; +import { SourceKind } from '@/types'; const filter = ( overrides: Partial = {}, @@ -655,6 +657,30 @@ describe('dashboardFilterValues', () => { }); }); + describe('getFiltersDeclaringVariables', () => { + const dataSource: DashboardFilter = { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + const env = staticFilter(); + + it('matches value and data source variables by name', () => { + expect( + getFiltersDeclaringVariables([env, dataSource], ['logs', 'env']), + ).toEqual([env, dataSource]); + expect(getFiltersDeclaringVariables([env, dataSource], ['logs'])).toEqual( + [dataSource], + ); + }); + }); + describe('getBlockingRequiredFilters', () => { const names = ( filters: DashboardFilter[], @@ -704,6 +730,33 @@ describe('dashboardFilterValues', () => { expect(names(filters, { referencedVariableNames: [] })).toEqual([]); }); + it('blocks a tile whose text references a data source variable', () => { + const dataSource: DashboardFilter = { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + expect( + names([dataSource], { + referencedVariableNames: ['logs'], + consumesBroadcastFilters: false, + }), + ).toEqual(['Logs source']); + expect( + names([dataSource], { + referencedVariableNames: [], + consumesBroadcastFilters: false, + }), + ).toEqual([]); + }); + // A filter with no explicit variableName is still referenced by the token // derived from its display name. it('matches a filter by its derived variable name', () => { diff --git a/packages/common-utils/src/__tests__/filters.test.ts b/packages/common-utils/src/__tests__/filters.test.ts index 849b27736d..b33a07d0f1 100644 --- a/packages/common-utils/src/__tests__/filters.test.ts +++ b/packages/common-utils/src/__tests__/filters.test.ts @@ -37,6 +37,7 @@ import { validateSavedQuery, validateVariableName, } from '@/filters'; +import { buildReferenceChartVariables } from '@/referenceVariables'; import type { AdhocDashboardFilter, AdhocFilterCondition, @@ -53,6 +54,7 @@ import type { import { DASHBOARD_VARIABLE_NAME_MAX_LENGTH, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, + SourceKind, } from '@/types'; import { isFilterSingleSelect } from '@/variables'; @@ -1436,6 +1438,38 @@ describe('filters', () => { ).toEqual(['svc']); }); + it('reports a data source variable only until it selects a source', () => { + const where = 'ServiceName IN (SELECT s FROM $src)'; + const src = (selected: boolean) => + buildReferenceChartVariables( + [ + { + type: 'DATA_SOURCE', + name: 'Source', + variableName: 'src', + allowedSourceKinds: [SourceKind.Log], + }, + ], + { + values: new Map([['src', selected ? 'logs' : undefined]]), + sources: [ + { + id: 'logs', + name: 'Logs', + from: { databaseName: 'default', tableName: 'logs' }, + }, + ], + }, + )[0]; + + expect(getPendingFilterValuesVariables({ where }, [src(false)])).toEqual([ + 'src', + ]); + expect(getPendingFilterValuesVariables({ where }, [src(true)])).toEqual( + [], + ); + }); + it('reports a braced reference once, however often it appears', () => { expect( getPendingFilterValuesVariables( diff --git a/packages/common-utils/src/__tests__/variableReferenceFields.test.ts b/packages/common-utils/src/__tests__/variableReferenceFields.test.ts new file mode 100644 index 0000000000..22f31da406 --- /dev/null +++ b/packages/common-utils/src/__tests__/variableReferenceFields.test.ts @@ -0,0 +1,484 @@ +import { + MacroExpansionError, + VariableFieldReferenceError, +} from '@/macroErrors'; +import { + buildReferenceChartVariables, + getEmptyDashboardVariables, + ReferenceVariableSource, +} from '@/referenceVariables'; +import { + ChartVariable, + DashboardFilter, + MetricsDataType, + MetricTable, + SourceKind, +} from '@/types'; +import { + formatVariableValues, + getReferenceFieldReferences, + getVariableReferences, + substituteVariables, + TemplateLanguage, + validateVariableReferencesInTemplate, +} from '@/variables'; + +const referenceFilterFields = { + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, +} as const; + +const sourceFilter = ( + variableName: string, + allowedSourceKinds: SourceKind[], +): DashboardFilter => ({ + ...referenceFilterFields, + id: `${variableName}-filter`, + type: 'DATA_SOURCE', + name: variableName, + variableName, + allowedSourceKinds, +}); + +const connectionFilter = (variableName: string): DashboardFilter => ({ + ...referenceFilterFields, + id: `${variableName}-filter`, + type: 'CONNECTION', + name: variableName, + variableName, +}); + +/** A data source variable selecting `source`, or nothing when it is undefined. */ +const sourceVariable = ( + variableName: string, + source: Omit | undefined, + allowedSourceKinds: SourceKind[] = [SourceKind.Log], +): ChartVariable => { + const [variable] = buildReferenceChartVariables( + [sourceFilter(variableName, allowedSourceKinds)], + { + values: new Map([[variableName, source && 'selected']]), + sources: source ? [{ id: 'selected', ...source }] : [], + }, + ); + return variable; +}; + +const connectionVariable = ( + variableName: string, + connectionName: string | undefined, +): ChartVariable => { + const [variable] = buildReferenceChartVariables( + [connectionFilter(variableName)], + { + values: new Map([[variableName, connectionName && 'selected']]), + connections: connectionName + ? [{ id: 'selected', name: connectionName }] + : [], + }, + ); + return variable; +}; + +const LOGS_SOURCE = { + name: 'My Logs', + from: { databaseName: 'default', tableName: 'otel_logs' }, +}; + +const LOGS = sourceVariable('src', LOGS_SOURCE); +const UNSELECTED_SOURCE = sourceVariable('src', undefined); +const ODD_NAMES = sourceVariable('src', { + name: 'Odd', + from: { databaseName: 'my-db', tableName: 'logs v2' }, +}); + +const NO_METRIC_TABLES: MetricTable = { + [MetricsDataType.Gauge]: '', + [MetricsDataType.Histogram]: '', + [MetricsDataType.Sum]: '', + [MetricsDataType.Summary]: '', + [MetricsDataType.ExponentialHistogram]: '', +}; + +const metricVariable = (metricTables: Partial) => + sourceVariable( + 'm', + { + name: 'Metrics', + from: { databaseName: 'default', tableName: '' }, + metricTables: { ...NO_METRIC_TABLES, ...metricTables }, + }, + [SourceKind.Metric], + ); + +const ONE_TABLE_METRICS = metricVariable({ + [MetricsDataType.Gauge]: 'otel_metrics_gauge', +}); +const MANY_TABLE_METRICS = metricVariable({ + [MetricsDataType.Gauge]: 'otel_metrics_gauge', + [MetricsDataType.Sum]: 'otel_metrics_sum', + [MetricsDataType.ExponentialHistogram]: 'otel_metrics_exp', +}); + +const CONNECTION = connectionVariable('conn', 'Prod'); + +const SERVICE: ChartVariable = { name: 'svc', values: ['api', 'web'] }; + +const expand = ( + input: string, + variables: ChartVariable[], + inputLanguage: TemplateLanguage = 'sql', +) => substituteVariables(input, { variables, inputLanguage }); + +describe('sqlidentifier format', () => { + it('backtick-quotes every value', () => { + expect( + formatVariableValues({ values: ['a', 'limit', 'b c'] }, 'sqlidentifier'), + ).toBe('`a`, `limit`, `b c`'); + }); + + it('escapes backticks and backslashes, taking the value literally', () => { + expect( + formatVariableValues({ values: ['d`e', '`a b`'] }, 'sqlidentifier'), + ).toBe('`d\\`e`, `\\`a b\\``'); + }); + + it('keeps a value that tries to close the identifier inside it', () => { + const injected: ChartVariable = { + name: 'svc', + values: ['a\\`) OR 1=1 --'], + }; + expect(expand('WHERE ${svc:sqlidentifier} = 1', [injected])).toBe( + 'WHERE `a\\\\\\`) OR 1=1 --` = 1', + ); + }); + + it('renders nothing for an empty selection', () => { + expect(formatVariableValues({ values: [] }, 'sqlidentifier')).toBe(''); + }); + + it('applies to a value variable', () => { + expect(expand('SELECT ${svc:sqlidentifier}', [SERVICE])).toBe( + 'SELECT `api`, `web`', + ); + }); +}); + +describe('data source variable references', () => { + it.each([ + ['$src', '`default`.`otel_logs`'], + ['${src}', '`default`.`otel_logs`'], + ['${src.table}', '`otel_logs`'], + ['${src.database}', '`default`'], + ['${src.name}', "'My Logs'"], + ['${src.id}', "'selected'"], + ])('expands %s in SQL as %s', (reference, expected) => { + expect(expand(`SELECT * FROM ${reference}`, [LOGS])).toBe( + `SELECT * FROM ${expected}`, + ); + }); + + it('quotes each segment separately', () => { + expect(expand('FROM $src', [ODD_NAMES])).toBe('FROM `my-db`.`logs v2`'); + expect(expand('FROM ${src.table}', [ODD_NAMES])).toBe('FROM `logs v2`'); + }); + + it('escapes a backslash ending a table name', () => { + const trailingBackslash = sourceVariable('src', { + name: 'Odd', + from: { databaseName: 'd', tableName: 't\\' }, + }); + expect(expand('FROM $src', [trailingBackslash])).toBe('FROM `d`.`t\\\\`'); + }); + + it('applies a requested format to the field', () => { + expect(expand('WHERE t = ${src.table:sqlstring}', [LOGS])).toBe( + "WHERE t = 'otel_logs'", + ); + expect(expand("WHERE n = '${src.name:csv}'", [LOGS])).toBe( + "WHERE n = 'My Logs'", + ); + expect(expand('${src:csv}', [LOGS])).toBe('default.otel_logs'); + expect(expand('SELECT ${src.name:sqlidentifier}', [LOGS])).toBe( + 'SELECT `My Logs`', + ); + }); + + it('renders the name as plain text in markdown', () => { + expect(expand('# ${src.name}', [LOGS], 'markdown')).toBe('# My Logs'); + expect(expand('Table: $src', [LOGS], 'markdown')).toBe( + 'Table: default\\.otel\\_logs', + ); + }); + + it('renders nothing while unselected', () => { + expect(expand('FROM $src', [UNSELECTED_SOURCE])).toBe('FROM '); + expect(expand('${src.name}', [UNSELECTED_SOURCE], 'markdown')).toBe(''); + }); + + it('renders nothing when the selection is not a known source', () => { + const [variable] = buildReferenceChartVariables( + [sourceFilter('src', [SourceKind.Log])], + { + values: new Map([['src', 'missing']]), + sources: [{ id: 'other', ...LOGS_SOURCE }], + }, + ); + expect(expand('FROM $src', [variable])).toBe('FROM '); + }); + + it('still rejects an unknown field while unselected', () => { + expect(() => expand('${src.nope}', [UNSELECTED_SOURCE])).toThrow( + VariableFieldReferenceError, + ); + }); + + it('rejects an unknown field, listing the fields it has', () => { + expect(() => expand('${src.columns}', [LOGS])).toThrow( + "'${src.columns}' reads a field $src doesn't have. Expected one of: " + + '$src, ${src.table}, ${src.database}, ${src.name}, ${src.id}.', + ); + expect(() => expand('${src.name.first}', [LOGS])).toThrow( + VariableFieldReferenceError, + ); + }); + + it('leaves a field on an unknown variable as written', () => { + expect(expand('SELECT ${other.table}', [LOGS])).toBe( + 'SELECT ${other.table}', + ); + }); + + it('expands an exact match in lucene', () => { + expect(expand('SourceName:"${src.name}"', [LOGS], 'lucene')).toBe( + '(SourceName:"My Logs")', + ); + }); + + it('matches everything in lucene while unselected', () => { + expect( + expand('SourceName:"${src.name}"', [UNSELECTED_SOURCE], 'lucene'), + ).toBe('SourceName:("")'); + }); + + it('escapes the name for the promql string it sits in', () => { + const quoted = sourceVariable('src', { + name: 'a"b', + from: { databaseName: 'd', tableName: 't' }, + }); + expect(expand('up{source="${src.name}"}', [quoted], 'promql')).toBe( + 'up{source="a\\"b"}', + ); + }); + + describe('metric sources', () => { + it('requires the table to be named even when only one is configured', () => { + const message = + "can't render for the selected data source. Use one of: ${m.table.gauge}, ${m.database}, ${m.name}, ${m.id}."; + expect(() => expand('FROM $m', [ONE_TABLE_METRICS])).toThrow( + `'$m' ${message}`, + ); + expect(() => expand('FROM ${m.table}', [ONE_TABLE_METRICS])).toThrow( + `'\${m.table}' ${message}`, + ); + }); + + it('picks a named table', () => { + expect(expand('FROM ${m.table.sum}', [MANY_TABLE_METRICS])).toBe( + 'FROM `otel_metrics_sum`', + ); + expect( + expand('FROM ${m.table.exponential_histogram}', [MANY_TABLE_METRICS]), + ).toBe('FROM `otel_metrics_exp`'); + }); + + it('lists the fields that render when the table is left out', () => { + const message = + "can't render for the selected data source. Use one of: ${m.table.gauge}, ${m.table.sum}, ${m.table.exponential_histogram}, ${m.database}, ${m.name}, ${m.id}."; + expect(() => expand('FROM ${m.table}', [MANY_TABLE_METRICS])).toThrow( + `'\${m.table}' ${message}`, + ); + expect(() => expand('FROM $m', [MANY_TABLE_METRICS])).toThrow( + `'$m' ${message}`, + ); + }); + + it('rejects a table the source does not configure, listing the fields that render', () => { + expect(() => + expand('FROM ${m.table.histogram}', [ONE_TABLE_METRICS]), + ).toThrow( + "'${m.table.histogram}' can't render for the selected data source. Use one of: " + + '${m.table.gauge}, ${m.database}, ${m.name}, ${m.id}.', + ); + }); + + it('rejects a metric table on a selected non-metric source', () => { + const mixed = sourceVariable('src', LOGS_SOURCE, [ + SourceKind.Log, + SourceKind.Metric, + ]); + expect(() => expand('FROM ${src.table.gauge}', [mixed])).toThrow( + "'${src.table.gauge}' can't render for the selected data source.", + ); + }); + + it('has no metric table fields on a variable that allows no metric source', () => { + expect(() => expand('FROM ${src.table.gauge}', [LOGS])).toThrow( + "'${src.table.gauge}' reads a field $src doesn't have.", + ); + }); + }); +}); + +describe('connection variable references', () => { + it('expands to the connection name', () => { + expect(expand('$conn', [CONNECTION])).toBe("'Prod'"); + expect(expand('${conn.name}', [CONNECTION], 'markdown')).toBe('Prod'); + }); + + it('expands the connection id', () => { + expect(expand('${conn.id}', [CONNECTION])).toBe("'selected'"); + }); + + it('renders nothing while unselected', () => { + expect(expand('$conn', [connectionVariable('conn', undefined)])).toBe(''); + }); + + it('rejects a field a connection does not have', () => { + expect(() => expand('${conn.table}', [CONNECTION])).toThrow( + "'${conn.table}' reads a field $conn doesn't have. Expected one of: $conn, ${conn.name}, ${conn.id}.", + ); + }); +}); + +describe('fields on a value variable', () => { + it('are rejected', () => { + expect(() => expand('${svc.table}', [SERVICE])).toThrow( + VariableFieldReferenceError, + ); + }); +}); + +describe('variable macros on a reference variable', () => { + it.each(['$__filter(SourceName, $src)', '$__conditionalAll(1 = 1, $src)'])( + 'reject %s', + template => { + expect(() => expand(template, [LOGS])).toThrow(MacroExpansionError); + }, + ); +}); + +describe('getReferenceFieldReferences', () => { + const references = (variable: ChartVariable) => + variable.reference + ? getReferenceFieldReferences(variable.name, variable.reference).map( + ({ reference }) => reference, + ) + : []; + + it('offers every field while nothing is selected', () => { + expect( + references( + sourceVariable('m', undefined, [SourceKind.Log, SourceKind.Metric]), + ), + ).toContain('${m.table.summary}'); + }); + + it('offers only the fields the selection renders', () => { + expect(references(MANY_TABLE_METRICS)).toEqual([ + '${m.table.gauge}', + '${m.table.sum}', + '${m.table.exponential_histogram}', + '${m.database}', + '${m.name}', + '${m.id}', + ]); + }); +}); + +describe('getVariableReferences', () => { + it('reports the field path', () => { + expect(getVariableReferences('${src.table.gauge:sqlidentifier}')).toEqual([ + expect.objectContaining({ + name: 'src', + path: ['table', 'gauge'], + format: 'sqlidentifier', + }), + ]); + }); +}); + +describe('validateVariableReferencesInTemplate with reference variables', () => { + const validate = (template: string, language: TemplateLanguage = 'sql') => + validateVariableReferencesInTemplate(template, [LOGS, CONNECTION], { + language, + }); + + it('accepts a valid reference without the value-variable warnings', () => { + expect(validate('SELECT * FROM $src WHERE x = ${src.name}')).toEqual({ + errors: [], + warnings: [], + }); + }); + + it('reports an unknown field', () => { + expect(validate('SELECT ${src.columns}').errors).toEqual([ + expect.stringContaining( + "'${src.columns}' reads a field $src doesn't have", + ), + ]); + }); + + it('reports a quoted name', () => { + expect(validate("WHERE n = '${src.name}'").errors).toEqual([ + '${src.name} is wrapped in quotes, but the sqlstring format already quotes the value. Remove the quotes, or use ${src.name:csv} inside them.', + ]); + }); + + it('reports a quoted name while unselected', () => { + expect( + validateVariableReferencesInTemplate("WHERE n = '${src.name}'", [ + UNSELECTED_SOURCE, + ]).errors, + ).toHaveLength(1); + }); + + it('reports an unknown field in markdown', () => { + expect(validate('${conn.database}', 'markdown').errors).toEqual([ + expect.stringContaining( + "'${conn.database}' reads a field $conn doesn't have", + ), + ]); + }); + + it('reports a field on a value variable', () => { + expect( + validateVariableReferencesInTemplate('SELECT ${svc.table}', [SERVICE]) + .errors, + ).toEqual([ + "'${svc.table}' reads a field, but $svc is not a data source or connection variable, so it has none.", + ]); + }); + + it('reports a metric source reference that names no table', () => { + expect( + validateVariableReferencesInTemplate('FROM $m', [ONE_TABLE_METRICS]) + .errors, + ).toEqual([expect.stringContaining("'$m' can't render")]); + }); +}); + +describe('getEmptyDashboardVariables', () => { + it('includes the reference variables, unselected', () => { + const variables = getEmptyDashboardVariables([ + sourceFilter('src', [SourceKind.Log]), + connectionFilter('conn'), + ]); + expect(variables.map(variable => variable.name)).toEqual(['src', 'conn']); + expect(expand('FROM $src WHERE c = $conn', variables)).toBe( + 'FROM WHERE c = ', + ); + }); +}); diff --git a/packages/common-utils/src/__tests__/variables.test.ts b/packages/common-utils/src/__tests__/variables.test.ts index 6451859658..7d9a801aec 100644 --- a/packages/common-utils/src/__tests__/variables.test.ts +++ b/packages/common-utils/src/__tests__/variables.test.ts @@ -2175,7 +2175,7 @@ describe('validateVariableReferencesInTemplate', () => { it('warns about an unknown format', () => { expect(markdown('${service:nope}', [SERVICE]).warnings).toEqual([ '${service:nope} uses an unknown format, so no variables are substituted. ' + - 'Expected one of: sqlstring, regex, csv, lucene, markdown, promql, url.', + 'Expected one of: sqlstring, sqlidentifier, regex, csv, lucene, markdown, promql, url.', ]); }); diff --git a/packages/common-utils/src/dashboardFilterValues.ts b/packages/common-utils/src/dashboardFilterValues.ts index a0e7922d12..e868431d64 100644 --- a/packages/common-utils/src/dashboardFilterValues.ts +++ b/packages/common-utils/src/dashboardFilterValues.ts @@ -262,6 +262,26 @@ export function getAdhocFilterTargetsForTile( ); } +/** + * The filters that declare a variable named in `names`: value variables, and + * data source and connection variables, whether a field or text references them. + */ +export function getFiltersDeclaringVariables( + filters: T[], + names: Iterable, +): T[] { + const named = new Set(names); + const declaring = new Set( + [ + ...getDashboardVariableFilters(filters), + ...getReferenceVariableFilters(filters), + ] + .filter(({ name }) => named.has(name)) + .map(({ filter }) => filter), + ); + return filters.filter(filter => declaring.has(filter)); +} + /** * The subset of `unsatisfiedRequiredFilters` that blocks the given tile. * @@ -284,24 +304,17 @@ export function getBlockingRequiredFilters( referenceVariableNames?: readonly string[]; }, ): DashboardFilter[] { - const referenceVariableNames = new Set(tile.referenceVariableNames ?? []); - const referenceVariableFilterIds = new Set( - getReferenceVariableFilters(unsatisfiedRequiredFilters) - .filter(({ name }) => referenceVariableNames.has(name)) - .map(({ filter }) => filter.id), - ); - const referencedNamesSet = new Set(tile.referencedVariableNames ?? []); - const referencedFilterIds = new Set( - getDashboardVariableFilters(unsatisfiedRequiredFilters) - .filter(({ name }) => referencedNamesSet.has(name)) - .map(({ filter }) => filter.id), + const referencedFilters = new Set( + getFiltersDeclaringVariables(unsatisfiedRequiredFilters, [ + ...(tile.referencedVariableNames ?? []), + ...(tile.referenceVariableNames ?? []), + ]), ); return unsatisfiedRequiredFilters.filter( filter => isFilterGlobalRequirement(filter) || - referencedFilterIds.has(filter.id) || - referenceVariableFilterIds.has(filter.id) || + referencedFilters.has(filter) || (tile.consumesBroadcastFilters && doesFilterApplyToSource(filter, tile.sourceId)), ); diff --git a/packages/common-utils/src/filters.ts b/packages/common-utils/src/filters.ts index d443fd303b..c5f26af1d6 100644 --- a/packages/common-utils/src/filters.ts +++ b/packages/common-utils/src/filters.ts @@ -36,6 +36,7 @@ import { escapePromqlStringValue, formatVariableValues, getVariableReferences, + hasSelection, substituteVariables, } from '@/variables'; @@ -1170,8 +1171,8 @@ export function isReferenceVariableFilterType( /** Type guard for reference variable filters; see `isReferenceVariableFilterType`. */ export function isReferenceVariableFilter< - T extends { type: DashboardFilterKind }, ->(filter: T): filter is Extract { + T extends { type?: DashboardFilterKind }, +>(filter: T): filter is T & { type: 'DATA_SOURCE' | 'CONNECTION' } { return isReferenceVariableFilterType(filter.type); } @@ -1494,9 +1495,11 @@ export type FilterForVariableDeclaration = { /** * The variable-enabled filters a dashboard declares, paired with the name each - * one answers to, in filter order. Data source variables are left out: their - * value selects a tile's source or connection and is never substituted into - * query text. + * one answers to, in filter order. Data source and connection variables are + * left out: their selection is an ID that text references read fields of, not + * values to render, so they are built separately by + * `buildReferenceChartVariables`. To match a filter by name across both, use + * `getFiltersDeclaringVariables`. */ export function getDashboardVariableFilters< T extends FilterForVariableDeclaration, @@ -1637,7 +1640,7 @@ export function getPendingFilterValuesVariables( if (variables == null || !where.trim() || whereLanguage !== 'sql') return []; const emptyVariableNames = new Set( - variables.filter(v => v.values.length === 0).map(v => v.name), + variables.filter(v => !hasSelection(v)).map(v => v.name), ); if (emptyVariableNames.size === 0) return []; diff --git a/packages/common-utils/src/macroErrors.ts b/packages/common-utils/src/macroErrors.ts index 302806cd55..7eef6e2539 100644 --- a/packages/common-utils/src/macroErrors.ts +++ b/packages/common-utils/src/macroErrors.ts @@ -20,6 +20,20 @@ export class MacroExpansionError extends Error { } } +/** + * Thrown when a field reference like `${src.table}` can't render because it + * references a field the variable doesn't have. + */ +export class VariableFieldReferenceError extends Error { + constructor( + public readonly variableName: string, + message: string, + ) { + super(message); + this.name = 'VariableFieldReferenceError'; + } +} + /** * Thrown during expansion when `$__filter` / `$__conditionalAll` names a * variable that the context does not declare. diff --git a/packages/common-utils/src/referenceVariables.ts b/packages/common-utils/src/referenceVariables.ts index d59405ad4a..458402a53a 100644 --- a/packages/common-utils/src/referenceVariables.ts +++ b/packages/common-utils/src/referenceVariables.ts @@ -1,7 +1,9 @@ import { castArray, isString, uniq } from 'lodash'; import { + FilterForVariableDeclaration, getAdhocFilterSourceKinds, + getDashboardVariableDeclarations, isConnectionFilter, isDataSourceFilter, isReferenceVariableFilter, @@ -10,12 +12,17 @@ import { SQL_QUERY_FILTER_SOURCE_KINDS, } from '@/filters'; import { + ChartReferenceField, + ChartVariable, ConnectionDashboardFilter, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, DashboardFilter, DataSourceDashboardFilter, + MetricsDataType, NON_PROMQL_SOURCE_KINDS, SourceKind, + TMetricSource, + TSource, } from '@/types'; /** @@ -58,6 +65,144 @@ export function getObjectName( /** Selected ID per reference variable name; undefined when unselected. */ export type ReferenceVariableValues = ReadonlyMap; +/** The parts of a source that text references to a data source variable read. */ +export type ReferenceVariableSource = Pick & + Partial>; + +/** What text references to a connection variable read from its selected connection. */ +export type ReferenceVariableConnection = { id: string; name: string }; + +/** A filter that may declare a reference variable, and the source kinds it allows. */ +type ReferenceVariableFilter = FilterForVariableDeclaration & { + allowedSourceKinds?: SourceKind[]; +}; + +/** The `${src.table.}` field naming each metric table. */ +const METRIC_TABLE_FIELDS = Object.values(MetricsDataType).map( + type => [type.replace(/ /g, '_'), type] as const, +); + +const identifierField = (parts: string[] | undefined): ChartReferenceField => ({ + type: 'identifier', + parts, +}); + +/** + * The fields of a data source variable. Metric table fields are declared when + * the variable can select a metric source. A metric source never renders + * `$src` or `${src.table}`: picking its only table would silently change what + * a tile queries once the source gains another, so the table must be named. + */ +function getSourceFields( + source: ReferenceVariableSource | undefined, + allowsMetricSources: boolean, +): Record { + const metricTables = new Map(Object.entries(source?.metricTables ?? {})); + const isMetricSource = METRIC_TABLE_FIELDS.some(([, type]) => + metricTables.get(type), + ); + const table = isMetricSource ? undefined : source?.from.tableName; + const database = source?.from.databaseName; + + return Object.fromEntries([ + [ + '', + identifierField( + database != null && table != null ? [database, table] : undefined, + ), + ], + ['table', identifierField(table != null ? [table] : undefined)], + ...(allowsMetricSources + ? METRIC_TABLE_FIELDS.map(([field, type]) => { + const metricTable = metricTables.get(type); + return [ + `table.${field}`, + identifierField(metricTable ? [metricTable] : undefined), + ]; + }) + : []), + ['database', identifierField(database != null ? [database] : undefined)], + ['name', { type: 'text', text: source?.name }], + ['id', { type: 'text', text: source?.id }], + ]); +} + +function getConnectionFields( + connection: ReferenceVariableConnection | undefined, +): Record { + const name: ChartReferenceField = { type: 'text', text: connection?.name }; + return { + '': name, + name, + id: { type: 'text', text: connection?.id }, + }; +} + +/** + * The data source and connection variables a dashboard declares, as the + * variables text references (`$src`, `${src.table}`) expand against. A + * variable with no selection, or one selecting an ID not in `sources` / + * `connections`, is unselected and expands to nothing. + */ +export function buildReferenceChartVariables( + filters: ReferenceVariableFilter[] | undefined, + { + values, + sources, + connections, + }: { + values?: ReferenceVariableValues; + sources?: readonly ReferenceVariableSource[]; + connections?: readonly ReferenceVariableConnection[]; + } = {}, +): ChartVariable[] { + return getReferenceVariableFilters(filters).map( + ({ filter, name }): ChartVariable => { + const id = values?.get(name); + if (filter.type === 'CONNECTION') { + const connection = id ? connections?.find(c => c.id === id) : undefined; + return { + name, + values: [], + reference: { + noun: 'connection', + hasSelection: connection != null, + fields: getConnectionFields(connection), + }, + }; + } + const source = id ? sources?.find(s => s.id === id) : undefined; + const allowsMetricSources = + filter.allowedSourceKinds?.includes(SourceKind.Metric) ?? false; + return { + name, + values: [], + reference: { + noun: 'data source', + hasSelection: source != null, + fields: getSourceFields(source, allowsMetricSources), + }, + }; + }, + ); +} + +/** + * Every variable a dashboard declares, with nothing selected: how templates + * expand where no selection applies, such as alerts and saved-template checks. + */ +export function getEmptyDashboardVariables( + filters: ReferenceVariableFilter[] | undefined, +): ChartVariable[] { + return [ + ...getDashboardVariableDeclarations(filters).map(declaration => ({ + ...declaration, + values: [], + })), + ...buildReferenceChartVariables(filters), + ]; +} + /** A data source variable's identity, as offered by source pickers. */ export type SourceVariableDeclaration = { name: string; @@ -128,14 +273,14 @@ export function getConnectionVariableFilters( */ export function getReferenceVariableFilters< T extends { - type: DashboardFilter['type']; + type?: DashboardFilter['type']; name: string; variableName?: string; }, >( filters: T[] | undefined, ): { - filter: Extract; + filter: T & { type: 'DATA_SOURCE' | 'CONNECTION' }; name: string; }[] { return pairWithVariableNames( diff --git a/packages/common-utils/src/types.ts b/packages/common-utils/src/types.ts index 97450c9348..06925fdc3b 100644 --- a/packages/common-utils/src/types.ts +++ b/packages/common-utils/src/types.ts @@ -1929,15 +1929,56 @@ export const _ChartConfigSchema = SharedChartSettingsSchema.extend({ groupByColumnsOnLeft: z.boolean().optional(), }); +/** + * One field a reference variable can be read by, as in `${src.table}`. Its + * value is set once the variable selects something that has it. + */ +export const ChartReferenceFieldSchema = z.discriminatedUnion('type', [ + z.object({ + /** A name rendered as an identifier, qualified by its parts (`db.table`). */ + type: z.literal('identifier'), + parts: z.array(z.string()).optional(), + }), + z.object({ + type: z.literal('text'), + text: z.string().optional(), + }), +]); + +export type ChartReferenceField = z.infer; + +/** What a data source or connection variable selects, as text references read it. */ +export const ChartReferenceVariableSchema = z.object({ + /** What the variable selects, for messages, e.g. `data source`. */ + noun: z.string(), + /** + * Whether the selection resolved to a known source or connection. Without + * one every field renders nothing; with one, a field it lacks is an error. + */ + hasSelection: z.boolean(), + /** + * Every field the variable can be read by, whether or not anything is + * selected, keyed by its path: `table.gauge` for `${src.table.gauge}`, and + * the empty string for the bare `$src`. + */ + fields: z.record(z.string(), ChartReferenceFieldSchema), +}); + +export type ChartReferenceVariable = z.infer< + typeof ChartReferenceVariableSchema +>; + /** A dashboard variable as seen by a tile's query. */ export const ChartVariableSchema = z.object({ name: z.string(), /** The filter's target expression; enables the 1-arg `$__filter($name)` form. */ expression: z.string().optional(), - /** Empty means nothing is selected. */ + /** Empty means nothing is selected. Always empty for a reference variable. */ values: z.array(z.string()), /** The filter's selection cap; 1 means the variable is single-select. */ maxSelections: z.number().optional(), + /** Set for a variable that supports ${var.field} references. */ + reference: ChartReferenceVariableSchema.optional(), }); export type ChartVariable = z.infer; diff --git a/packages/common-utils/src/variables.ts b/packages/common-utils/src/variables.ts index 001752c4bd..a9715374ad 100644 --- a/packages/common-utils/src/variables.ts +++ b/packages/common-utils/src/variables.ts @@ -1,4 +1,5 @@ import lucene from '@hyperdx/lucene'; +import { partition } from 'lodash'; import { getPromqlSeries } from './core/promql'; import { @@ -10,6 +11,7 @@ import { MacroExpansionError, MalformedMacroArgsError, UnknownVariableError, + VariableFieldReferenceError, } from './macroErrors'; import { decodeSpecialTokensToSource, @@ -18,6 +20,8 @@ import { } from './queryParser'; import { ChartConfigWithOptDateRange, + ChartReferenceField, + ChartReferenceVariable, ChartVariable, DASHBOARD_VARIABLE_NAME_PATTERN, DASHBOARD_VARIABLE_NAME_PATTERN_ANCHORED, @@ -32,6 +36,7 @@ import { /** Rendering formats a reference can request via `${name:format}`. */ export const VARIABLE_FORMATS = [ 'sqlstring', + 'sqlidentifier', 'regex', 'csv', 'lucene', @@ -49,6 +54,16 @@ export function isFilterSingleSelect( return 'maxSelections' in filter && filter.maxSelections === 1; } +/** + * Whether a variable has a selection: a value for a value variable, a source + * or connection for a data source or connection variable. + */ +export function hasSelection(variable: ChartVariable): boolean { + return variable.reference + ? variable.reference.hasSelection + : variable.values.length > 0; +} + const isVariableFormat = (format: string): format is VariableFormat => (VARIABLE_FORMATS as readonly string[]).includes(format); @@ -56,6 +71,14 @@ const isVariableFormat = (format: string): format is VariableFormat => const isStringLiteralFormat = (format: string | undefined) => format === 'regex' || format === 'promql'; +/** + * Backtick-quote a value as a ClickHouse identifier, taken literally. ClickHouse + * reads a backslash as an escape inside backticks, so it is escaped along with + * the backtick; otherwise a value ending in `\` could close the identifier early. + */ +const quoteSqlIdentifier = (value: string) => + `\`${value.replace(/\\/g, '\\\\').replace(/`/g, '\\`')}\``; + const escapeRegexValue = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); @@ -98,6 +121,9 @@ export function formatVariableValues( return values.length === 0 ? 'NULL' : values.map(value => `'${escapeSqlString(value)}'`).join(', '); + case 'sqlidentifier': + // Always quoted: a bare-looking value can still be a reserved word. + return values.map(quoteSqlIdentifier).join(', '); case 'regex': return formatRegexValues(values); case 'promql': @@ -145,6 +171,8 @@ export type TemplateToken = | { kind: 'braced'; name: string; + /** The fields after the name, as in `${src.table.gauge}`; empty for none. */ + path: string[]; format?: string; raw: string; inStringLiteral: boolean; @@ -163,11 +191,11 @@ const isVariableMacroName = (name: string): name is VariableMacroName => // eslint-disable-next-line security/detect-non-literal-regexp const BARE_NAME_REGEX = new RegExp(`^${DASHBOARD_VARIABLE_NAME_PATTERN}`); -// Pattern used for recognizing ${var} and ${var:format} references, and for extracting the name and format. +// Pattern used for recognizing ${var}, ${var.field} and ${var:format} references, and for extracting the name, field path and format. // (eslint ignored because DASHBOARD_VARIABLE_NAME_PATTERN is a shared constant, not user input) // eslint-disable-next-line security/detect-non-literal-regexp const BRACED_REFERENCE_REGEX = new RegExp( - `^(${DASHBOARD_VARIABLE_NAME_PATTERN})(?::([a-zA-Z][a-zA-Z0-9_]*))?$`, + `^(${DASHBOARD_VARIABLE_NAME_PATTERN})((?:\\.[a-zA-Z_][a-zA-Z0-9_]*)*)(?::([a-zA-Z][a-zA-Z0-9_]*))?$`, ); /** @@ -237,7 +265,7 @@ export function findBalancedParens(input: string, start: number): number { * * At each `$` the scanner tries, in order: * 1. a known `$__` macro (longest match, requiring a non-word char after the name so `$__filter` never matches the prefix of `$__filters`), - * 2. a `${name}` / `${name:format}` reference, then a + * 2. a `${name}` / `${name.field}` / `${name:format}` reference, then a * 3. bare `$name` reference (maximal munch). Anything else is plain text, and an unknown `$__x` is emitted verbatim. * * `onMalformed` controls what happens when a macro's argument list has no @@ -367,7 +395,8 @@ export function scanTemplateTokens( tokens.push({ kind: 'braced', name: match[1], - format: match[2], + path: match[2] ? match[2].slice(1).split('.') : [], + format: match[3], raw: input.slice(i, closeIndex + 1), inStringLiteral, }); @@ -576,13 +605,24 @@ function requireVariableNameArg( ); } -/** Require that a variable with the given name exists in the context. Throws an error if not found. */ +/** + * Require that a value variable with the given name exists in the context. + * Throws an error if not found, or if it is a data source or connection + * variable, which has no values to filter on. + */ function requireVariable( ctx: VariableContext, macroName: VariableMacroName, variableName: string, ): ChartVariable { const variable = ctx.variables.find(v => v.name === variableName); + if (variable?.reference) { + throw new MacroExpansionError( + macroName, + `Macro '$__${macroName}' can't use $${variableName}, a ${variable.reference.noun} variable, ` + + `which selects no values. Reference it directly, as in $${variableName}.`, + ); + } if (!variable) { const available = ctx.variables.map(v => v.name); throw new UnknownVariableError( @@ -653,6 +693,123 @@ function expandConditionalAllMacro( return `(${args[0]})`; } +/** How a reference to a field is written: `$src` for the bare form, else `${src.field}`. */ +function formatFieldReference(name: string, key: string): string { + return key === '' ? `$${name}` : `\${${name}.${key}}`; +} + +/** The segments a field renders, joined by `.`; undefined while it has no value. */ +function getFieldSegments(field: ChartReferenceField): string[] | undefined { + if (field.type === 'identifier') return field.parts; + return field.text != null ? [field.text] : undefined; +} + +/** A reference to a data source or connection variable, paired with the field it reads. */ +type ParsedReference = { + reference: ChartReferenceVariable; + field: ChartReferenceField; +}; + +/** + * The field a reference reads; undefined for a value variable, which has + * none. Throws for a field the variable doesn't have, whether or not anything + * is selected. + */ +function parseReference( + variable: ChartVariable, + path: readonly string[], + raw: string, +): ParsedReference | undefined { + const { name, reference } = variable; + if (reference == null) { + if (path.length === 0) return undefined; + throw new VariableFieldReferenceError( + name, + `'${raw}' reads a field, but $${name} is not a data source or connection variable, so it has none.`, + ); + } + + const fields = new Map(Object.entries(reference.fields)); + const field = fields.get(path.join('.')); + if (field == null) { + throw new VariableFieldReferenceError( + name, + `'${raw}' reads a field $${name} doesn't have. Expected one of: ` + + `${Array.from(fields.keys(), key => formatFieldReference(name, key)).join(', ')}.`, + ); + } + return { reference, field }; +} + +/** + * The segments a parsed reference renders; undefined while nothing is + * selected. Throws when the selection doesn't have the field. + */ +function resolveReferenceSegments( + name: string, + { reference, field }: ParsedReference, + raw: string, +): string[] | undefined { + if (!reference.hasSelection) return undefined; + const segments = getFieldSegments(field); + if (segments) return segments; + + const available = Object.entries(reference.fields) + .filter(([, f]) => getFieldSegments(f) != null) + .map(([key]) => formatFieldReference(name, key)); + throw new VariableFieldReferenceError( + name, + `'${raw}' can't render for the selected ${reference.noun}. Use one of: ${available.join(', ')}.`, + ); +} + +/** + * The fields a data source or connection variable offers, and how each is + * referenced: every field while nothing is selected, else the fields the + * selection renders. `field` is empty for the bare `$name` form. + */ +export function getReferenceFieldReferences( + name: string, + reference: ChartReferenceVariable, +): { field: string; reference: string }[] { + return Object.entries(reference.fields) + .filter(([, field]) => !reference.hasSelection || getFieldSegments(field)) + .map(([key]) => ({ + field: key, + reference: formatFieldReference(name, key), + })); +} + +/** + * The format a value reference renders in: the requested one, else the + * language's default. In SQL a reference variable's identifier field renders + * as an identifier, and its text as a string. + */ +function getEffectiveFormat( + parsed: ParsedReference | undefined, + requestedFormat: VariableFormat | undefined, + language: TemplateLanguage, +): VariableFormat { + if (requestedFormat != null) return requestedFormat; + if (parsed && language === 'sql') { + return parsed.field.type === 'text' ? 'sqlstring' : 'sqlidentifier'; + } + return languageSettings(language).defaultFormat; +} + +/** Render a reference's segments, joined by `.`, as one value in `format`. */ +function formatReferenceSegments( + segments: string[], + format: VariableFormat, +): string { + return format === 'sqlidentifier' + ? segments.map(quoteSqlIdentifier).join('.') + : formatVariableValues( + { values: [segments.join('.')], maxSelections: 1 }, + format, + ); +} + /** * Expand one non-text token against a variable context. A macro token's * arguments must already be expanded, so call this through `expandTemplate`. @@ -682,10 +839,23 @@ export function expandVariableToken( ); } - const settings = languageSettings(ctx.inputLanguage); - const format = requestedFormat ?? settings.defaultFormat; - const rendered = formatVariableValues(variable, format); + const parsed = parseReference( + variable, + token.kind === 'braced' ? token.path : [], + token.raw, + ); + const format = getEffectiveFormat(parsed, requestedFormat, ctx.inputLanguage); + let rendered: string; + if (parsed == null) { + rendered = formatVariableValues(variable, format); + } else { + const segments = resolveReferenceSegments(variable.name, parsed, token.raw); + if (segments == null) return ''; + rendered = formatReferenceSegments(segments, format); + } + + const settings = languageSettings(ctx.inputLanguage); return isStringLiteralFormat(format) && settings.escapeForStringLiteral ? settings.escapeForStringLiteral(rendered) : rendered; @@ -735,7 +905,16 @@ function getLuceneFormattedValues( const settings = languageSettings(ctx.inputLanguage); if ((requestedFormat ?? settings.defaultFormat) !== 'lucene') return undefined; - return ctx.variables.find(variable => variable.name === token.name)?.values; + const variable = ctx.variables.find(v => v.name === token.name); + if (!variable) return undefined; + const parsed = parseReference( + variable, + token.kind === 'braced' ? token.path : [], + token.raw, + ); + if (parsed == null) return variable.values; + const segments = resolveReferenceSegments(variable.name, parsed, token.raw); + return segments ? [segments.join('.')] : []; } /** @@ -1094,6 +1273,8 @@ export type VariableReference = { kind: 'macro' | 'bare' | 'braced'; /** The requested format, only ever set for `${name:format}`. */ format?: string; + /** The fields read, as in `${src.table}`; unset for none. */ + path?: string[]; /** Whether the reference sits inside a single- or double-quoted string. */ inStringLiteral: boolean; /** @@ -1151,6 +1332,10 @@ export function getVariableReferences( name: token.name, kind: token.kind, format: token.kind === 'braced' ? token.format : undefined, + path: + token.kind === 'braced' && token.path.length > 0 + ? token.path + : undefined, inStringLiteral: token.inStringLiteral, guardedBy, raw: token.raw, @@ -1319,18 +1504,37 @@ export function validateVariableReferencesInTemplate( } // An unrecognized format throws during expansion, so it is already reported. - const resolved = valueReferences.filter( - r => - knownVariableNames.has(r.name) && - (r.format == null || isVariableFormat(r.format)), + const variableByName = new Map(variables.map(v => [v.name, v])); + // Expansion is only attempted above for macros, so field errors are found + // here. A reference with a field error is left out of the checks below. + const fieldErrors = new Set(); + const resolved = valueReferences.flatMap(r => { + const variable = variableByName.get(r.name); + const { format } = r; + if (variable == null || (format != null && !isVariableFormat(format))) + return []; + try { + const parsed = parseReference(variable, r.path ?? [], r.raw); + if (parsed) resolveReferenceSegments(variable.name, parsed, r.raw); + const effectiveFormat = getEffectiveFormat(parsed, format, language); + return [{ ...r, variable, effectiveFormat }]; + } catch (e) { + if (!(e instanceof VariableFieldReferenceError)) throw e; + fieldErrors.add(e.message); + return []; + } + }); + errors.push(...fieldErrors); + + const [referenceRefs, valueVariableRefs] = partition( + resolved, + r => r.variable.reference != null, ); - // The two checks below are specific to SQL's `sqlstring` default format. + // The checks below are specific to SQL's `sqlstring` format. if (language === 'sql') { - const quoted = resolved.filter( - r => - (r.format ?? settings.defaultFormat) === 'sqlstring' && - r.inStringLiteral, + const quoted = valueVariableRefs.filter( + r => r.effectiveFormat === 'sqlstring' && r.inStringLiteral, ); if (quoted.length > 0) { const [{ name }] = quoted; @@ -1339,9 +1543,20 @@ export function validateVariableReferencesInTemplate( ); } - const unguarded = resolved.filter( + const quotedReferences = referenceRefs.filter( + r => r.effectiveFormat === 'sqlstring' && r.inStringLiteral, + ); + if (quotedReferences.length > 0) { + const [{ name, path }] = quotedReferences; + const field = path ? `.${path.join('.')}` : ''; + errors.push( + `${formatReferenceList(quotedReferences)} is wrapped in quotes, but the sqlstring format already quotes the value. Remove the quotes, or use \${${name}${field}:csv} inside them.`, + ); + } + + const unguarded = valueVariableRefs.filter( r => - (r.format ?? settings.defaultFormat) === 'sqlstring' && + r.effectiveFormat === 'sqlstring' && !r.inStringLiteral && r.guardedBy !== r.name, ); @@ -1356,15 +1571,13 @@ export function validateVariableReferencesInTemplate( // A regex or promql expansion is only valid as a quoted matcher value: an // alternation like `(api|web)`, `.*`, or an empty value is a syntax error // anywhere else, so `up{service=~$svc}` and `${svc}_total` are mistakes. + // A reference variable's one value, such as a metric name, is valid unquoted. if (language === 'promql') { - const unquoted = resolved.filter( - r => - isStringLiteralFormat(r.format ?? settings.defaultFormat) && - !r.inStringLiteral, + const unquoted = valueVariableRefs.filter( + r => isStringLiteralFormat(r.effectiveFormat) && !r.inStringLiteral, ); const isExactValue = (r: (typeof unquoted)[number]) => - (r.format ?? settings.defaultFormat) === 'promql' && - variables.some(v => v.name === r.name && isFilterSingleSelect(v)); + r.effectiveFormat === 'promql' && isFilterSingleSelect(r.variable); const groups = [ { refs: unquoted.filter(isExactValue), kind: 'a string', op: '=' }, {