diff --git a/.changeset/source-vars-1.md b/.changeset/source-vars-1.md new file mode 100644 index 000000000..eeacef4d1 --- /dev/null +++ b/.changeset/source-vars-1.md @@ -0,0 +1,7 @@ +--- +'@hyperdx/common-utils': minor +'@hyperdx/api': minor +'@hyperdx/app': patch +--- + +feat: add data source and connection variable types to dashboards diff --git a/.changeset/source-vars-2.md b/.changeset/source-vars-2.md new file mode 100644 index 000000000..32fd79c38 --- /dev/null +++ b/.changeset/source-vars-2.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/api': minor +--- + +feat: support data source and connection variables in the external API and MCP diff --git a/.changeset/source-vars-3.md b/.changeset/source-vars-3.md new file mode 100644 index 000000000..743757dbd --- /dev/null +++ b/.changeset/source-vars-3.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +feat: add data source variables to dashboard filters and tiles diff --git a/.changeset/source-vars-4.md b/.changeset/source-vars-4.md new file mode 100644 index 000000000..312539ba4 --- /dev/null +++ b/.changeset/source-vars-4.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +feat: let tiles and filters use a data source variable as their source diff --git a/.changeset/source-vars-5.md b/.changeset/source-vars-5.md new file mode 100644 index 000000000..49079c548 --- /dev/null +++ b/.changeset/source-vars-5.md @@ -0,0 +1,8 @@ +--- +'@hyperdx/app': minor +'@hyperdx/api': minor +'@hyperdx/common-utils': minor +--- + +feat: add connection variables for raw SQL tiles, SQL query filters, and +connection-scoped data source variables diff --git a/packages/api/openapi.json b/packages/api/openapi.json index 65ea9dff2..d3d0e8dc9 100644 --- a/packages/api/openapi.json +++ b/packages/api/openapi.json @@ -1883,7 +1883,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -1980,7 +1980,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2057,7 +2057,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2144,7 +2144,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2227,7 +2227,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2288,7 +2288,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2343,7 +2343,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2437,7 +2437,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2495,7 +2495,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2559,7 +2559,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to query.", + "description": "ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2599,7 +2599,7 @@ }, "sourceId": { "type": "string", - "description": "ID of the data source to mine patterns from.", + "description": "ID of the data source to mine patterns from, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard.", "example": "65f5e4a3b9e77c001a111111" }, "select": { @@ -2664,7 +2664,7 @@ }, "connectionId": { "type": "string", - "description": "ID of the ClickHouse connection to execute the query against.", + "description": "ID of the ClickHouse connection to execute the query against, or\n`$connectionVariable` of a CONNECTION filter on the dashboard.\n", "example": "65f5e4a3b9e77c001a567890" }, "sqlTemplate": { @@ -2675,7 +2675,7 @@ }, "sourceId": { "type": "string", - "description": "Optional ID of the data source associated with this Raw SQL chart. Used for applying dashboard filters.", + "description": "Optional ID of the data source associated with this Raw SQL chart, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. Used for applying dashboard filters.", "example": "65f5e4a3b9e77c001a567890" }, "numberFormat": { @@ -4031,6 +4031,12 @@ }, { "$ref": "#/components/schemas/AdhocFilterInput" + }, + { + "$ref": "#/components/schemas/DataSourceFilterInput" + }, + { + "$ref": "#/components/schemas/ConnectionFilterInput" } ], "discriminator": { @@ -4040,7 +4046,179 @@ "STATIC_LIST": "#/components/schemas/StaticListFilterInput", "PROMETHEUS_LABEL": "#/components/schemas/PrometheusLabelFilterInput", "SQL_QUERY": "#/components/schemas/SqlQueryFilterInput", - "ADHOC": "#/components/schemas/AdhocFilterInput" + "ADHOC": "#/components/schemas/AdhocFilterInput", + "DATA_SOURCE": "#/components/schemas/DataSourceFilterInput", + "CONNECTION": "#/components/schemas/ConnectionFilterInput" + } + } + }, + "DataSourceFilterInput": { + "type": "object", + "description": "A variable whose single, required value is a source. Tiles reference it\nas `$variableName` in their sourceId, and other filters in sourceId or\nappliesToSourceIds, so viewers can switch the source those read. Tiles\nthat use it do not load until a source is selected, and cannot have\nalerts.\n", + "required": [ + "type", + "name", + "allowedSourceKinds" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "DATA_SOURCE" + ], + "description": "Filter type discriminator. Must be \"DATA_SOURCE\".", + "example": "DATA_SOURCE" + }, + "name": { + "type": "string", + "minLength": 1, + "description": "Display name of the variable's dropdown", + "example": "Logs source" + }, + "variableName": { + "type": "string", + "maxLength": 64, + "pattern": "^[a-zA-Z][a-zA-Z0-9_]*$", + "description": "Token tiles and filters reference the selected source by, as `$variableName`.", + "example": "logs" + }, + "isGlobalRequirement": { + "type": "boolean", + "default": false, + "description": "Blocks every tile on the dashboard until a value is selected. False\n(the default) blocks only the tiles that reference the variable.\n", + "example": true + }, + "minSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable always requires a selection.", + "example": 1 + }, + "maxSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable is always single-select.", + "example": 1 + }, + "isBroadcastEnabled": { + "type": "boolean", + "enum": [ + false + ], + "default": false, + "description": "Must be false or omitted.", + "example": false + }, + "isVariableEnabled": { + "type": "boolean", + "enum": [ + true + ], + "default": true, + "description": "Must be true if provided, and is true when omitted.", + "example": true + }, + "allowedSourceKinds": { + "type": "array", + "minItems": 1, + "items": { + "type": "string", + "enum": [ + "log", + "trace", + "session", + "metric", + "promql" + ] + }, + "description": "Kinds of sources offered. A field can reference the variable if it\naccepts at least one listed kind. A tile whose selected source is a\nkind it cannot use shows an error instead of running.\n", + "example": [ + "log" + ] + }, + "connectionId": { + "type": "string", + "description": "Optional connection the offered sources are limited to: a\nconnection ID, or `$name` of a CONNECTION filter on the dashboard.\n", + "example": "$conn" + } + } + }, + "ConnectionFilterInput": { + "type": "object", + "description": "A variable whose single, required value is a connection. Raw SQL tiles\nreference it as `$variableName` in their connectionId, and data source\nvariables and SQL query filters in theirs. Tiles that use it do not load\nuntil a connection is selected, and cannot have alerts.\n", + "required": [ + "type", + "name" + ], + "properties": { + "type": { + "type": "string", + "enum": [ + "CONNECTION" + ], + "description": "Filter type discriminator. Must be \"CONNECTION\".", + "example": "CONNECTION" + }, + "name": { + "type": "string", + "minLength": 1, + "description": "Display name of the variable's dropdown", + "example": "Connection" + }, + "variableName": { + "type": "string", + "maxLength": 64, + "pattern": "^[a-zA-Z][a-zA-Z0-9_]*$", + "description": "Token raw SQL tiles reference the selected connection by, as `$variableName`.", + "example": "conn" + }, + "isGlobalRequirement": { + "type": "boolean", + "default": false, + "description": "Blocks every tile on the dashboard until a value is selected. False\n(the default) blocks only the tiles that reference the variable.\n", + "example": true + }, + "minSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable always requires a selection.", + "example": 1 + }, + "maxSelections": { + "type": "integer", + "enum": [ + 1 + ], + "default": 1, + "description": "Must be 1 if provided. The variable is always single-select.", + "example": 1 + }, + "isBroadcastEnabled": { + "type": "boolean", + "enum": [ + false + ], + "default": false, + "description": "Must be false or omitted.", + "example": false + }, + "isVariableEnabled": { + "type": "boolean", + "enum": [ + true + ], + "default": true, + "description": "Must be true if provided, and is true when omitted.", + "example": true } } }, @@ -4076,7 +4254,7 @@ }, "sourceId": { "type": "string", - "description": "Source ID this dashboard filter key applies to", + "description": "Source ID this dashboard filter key applies to, or `$name` of a DATA_SOURCE filter on the dashboard", "example": "65f5e4a3b9e77c001a111111" }, "sourceMetricType": { @@ -4370,7 +4548,7 @@ }, "connectionId": { "type": "string", - "description": "ID of the ClickHouse connection the query runs on.", + "description": "ClickHouse connection the query runs on: a connection ID, or\n`$name` of a CONNECTION filter on the dashboard.\n", "example": "65f5e4a3b9e77c001a567890" }, "sqlTemplate": { @@ -4469,7 +4647,7 @@ "items": { "type": "string" }, - "description": "IDs of the sources whose keys and values the filter suggests, all of sourceType.", + "description": "IDs of the sources whose keys and values the filter suggests, all of sourceType, or `$name` of data source variables.", "example": [ "65f5e4a3b9e77c001a111111" ] @@ -4493,7 +4671,7 @@ "items": { "type": "string" }, - "description": "IDs of the sources whose tiles the conditions apply to, all of\nsourceType. Omit or send an empty array to apply to the tiles of\nthe filter's sources.\n", + "description": "IDs of the sources whose tiles the conditions apply to, all of\nsourceType, or `$name` of data source variables. Omit or send an\nempty array to apply to the tiles of the filter's sources.\n", "example": [ "65f5e4a3b9e77c001a111111" ] diff --git a/packages/api/src/controllers/alerts.ts b/packages/api/src/controllers/alerts.ts index f1c69d0ee..f49cf85a6 100644 --- a/packages/api/src/controllers/alerts.ts +++ b/packages/api/src/controllers/alerts.ts @@ -9,6 +9,7 @@ import { isPromqlSavedChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { configUsesReferenceVariable } from '@hyperdx/common-utils/dist/referenceVariables'; import { isRangeThresholdType } from '@hyperdx/common-utils/dist/types'; import { groupBy } from 'lodash'; import { type FilterQuery, Types } from 'mongoose'; @@ -97,6 +98,11 @@ export const validateAlertInput = async ( // The alert checker cannot evaluate these tiles, so the alert would never run. if (tile.config != null && !savedChartConfigSupportsAlerts(tile.config)) { + if (configUsesReferenceVariable(tile.config)) { + throw new Api400Error( + 'Alerts are not supported on tiles that use a data source or connection variable', + ); + } if (isPromqlSavedChartConfig(tile.config)) { throw new Api400Error('Alerts are not supported on PromQL tiles'); } diff --git a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts index eef1d0838..1285ec729 100644 --- a/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/patchDashboard.int.test.ts @@ -1400,4 +1400,86 @@ describe('MCP Dashboard Tools - clickstack_patch_dashboard', () => { expect(tile.config.showOperandSeries).toBe(false); }); }); + + describe('reference variables', () => { + const createDashboard = () => + new Dashboard({ + name: 'Variable dashboard', + tiles: [ + { + id: 'tile', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + name: 'Tile', + source: ctx.traceSource._id.toString(), + displayType: 'line', + select: [{ aggFn: 'count', valueExpression: '' }], + where: '', + }, + }, + ], + filters: [ + { + id: 'ds-filter', + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + team: ctx.team._id, + }).save(); + + const patchSource = (dashboardId: string, sourceId: string) => + callTool(ctx.client!, 'clickstack_patch_dashboard', { + dashboardId, + tileId: 'tile', + tile: { + name: 'Tile', + config: { + displayType: 'line', + sourceId, + select: [{ aggFn: 'count' }], + }, + }, + }); + + it('patches a tile to read from a declared data source variable', async () => { + const dashboard = await createDashboard(); + + const result = await patchSource(dashboard._id.toString(), '$traces'); + + expect(result.isError).toBeFalsy(); + const stored = await Dashboard.findById(dashboard._id).lean(); + expect(stored?.tiles[0].config).toMatchObject({ source: '$traces' }); + }); + + it('rejects a patch referencing an undeclared variable', async () => { + const dashboard = await createDashboard(); + + const result = await patchSource(dashboard._id.toString(), '$nope'); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain( + 'does not name a data source variable', + ); + }); + + it('accepts a patch that keeps a reference the dashboard no longer satisfies', async () => { + const dashboard = await createDashboard(); + await patchSource(dashboard._id.toString(), '$traces'); + await Dashboard.updateOne({ _id: dashboard._id }, { filters: [] }); + + const result = await patchSource(dashboard._id.toString(), '$traces'); + + expect(result.isError).toBeFalsy(); + }); + }); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts index 48de1b8f6..5042fc502 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTile.int.test.ts @@ -11,6 +11,7 @@ import { seedExponentialHistogramMetric, } from '@/fixtures'; import { callTool, getFirstText } from '@/mcp/__tests__/mcpTestUtils'; +import Dashboard from '@/models/dashboard'; import { Source } from '@/models/source'; import { setupDashboardTests } from './setup'; @@ -1373,4 +1374,85 @@ describe('MCP Dashboard Tools - clickstack_query_tile', () => { expect(rows.map(r => r.ServiceName)).toEqual(['svc-e', 'svc-d', 'svc-c']); }); }); + + describe('reference variables', () => { + const createVariableDashboard = (savedFilterValues: unknown[] = []) => + new Dashboard({ + name: 'Variable dashboard', + tiles: [ + { + id: 'variable-tile', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + name: 'Count', + source: '$traces', + displayType: 'number', + select: [{ aggFn: 'count', valueExpression: '' }], + where: '', + }, + }, + ], + filters: [ + { + id: 'ds-filter', + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + savedFilterValues, + team: ctx.team._id, + }).save(); + + it("runs a tile on its data source variable's saved selection", async () => { + const dashboard = await createVariableDashboard([ + { + type: 'variable', + name: 'traces', + values: [ctx.traceSource._id.toString()], + }, + ]); + + const result = await callTool(ctx.client!, 'clickstack_query_tile', { + dashboardId: dashboard._id.toString(), + tileId: 'variable-tile', + }); + + expect(result.isError).toBeFalsy(); + }); + + it('runs a tile on a selection passed in variableValues', async () => { + const dashboard = await createVariableDashboard(); + + const result = await callTool(ctx.client!, 'clickstack_query_tile', { + dashboardId: dashboard._id.toString(), + tileId: 'variable-tile', + variableValues: [ + { name: 'traces', values: [ctx.traceSource._id.toString()] }, + ], + }); + + expect(result.isError).toBeFalsy(); + }); + + it('reports a data source variable with no selection', async () => { + const dashboard = await createVariableDashboard(); + + const result = await callTool(ctx.client!, 'clickstack_query_tile', { + dashboardId: dashboard._id.toString(), + tileId: 'variable-tile', + }); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain('$traces variable'); + }); + }); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts index afaeff978..6b154c40e 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTiles.int.test.ts @@ -594,4 +594,59 @@ describe('MCP Dashboard Tools - clickstack_query_tiles', () => { expect(text).toContain('prod, staging'); }); }); + + it('reports a tile whose data source variable has no selection without failing the batch', async () => { + const sourceId = ctx.traceSource._id.toString(); + const createResult = await callTool( + ctx.client!, + 'clickstack_save_dashboard', + { + name: 'Batch reference variable test', + tiles: [ + { + name: 'Fixed', + config: { + displayType: 'number', + sourceId, + select: [{ aggFn: 'count' }], + }, + }, + { + name: 'Variable', + config: { + displayType: 'number', + sourceId: '$traces', + select: [{ aggFn: 'count' }], + }, + }, + ], + filters: [ + { + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + }, + ], + }, + ); + expect(createResult.isError).toBeFalsy(); + const dashboard = JSON.parse(getFirstText(createResult)); + + const result = await callTool(ctx.client!, 'clickstack_query_tiles', { + dashboardId: dashboard.id, + ...wideRange(), + }); + + expect(result.isError).toBeFalsy(); + const { tiles } = JSON.parse(getFirstText(result)); + expect(tiles).toEqual([ + expect.objectContaining({ name: 'Fixed', status: 'ok' }), + expect.objectContaining({ + name: 'Variable', + status: 'error', + error: expect.stringContaining('$traces variable'), + }), + ]); + }); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts index 3b270d960..597ef883c 100644 --- a/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/queryTilesHandler.test.ts @@ -17,6 +17,15 @@ jest.mock('@/mcp/tools/query/helpers', () => { }; }); +jest.mock('@/mcp/tools/dashboards/variables', () => { + const actual = jest.requireActual('@/mcp/tools/dashboards/variables'); + return { + ...actual, + getReferenceTargets: () => + Promise.resolve({ sources: [], connectionIds: new Set() }), + }; +}); + jest.mock('@/models/dashboard', () => ({ __esModule: true, default: { findOne: (...args: unknown[]) => mockFindOne(...args) }, diff --git a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts index 9624eca73..b750454e5 100644 --- a/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/saveDashboard.int.test.ts @@ -4132,4 +4132,127 @@ describe('MCP Dashboard Tools - clickstack_save_dashboard', () => { ]); }); }); + + describe('reference variables', () => { + const filters = [ + { + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + isGlobalRequirement: true, + }, + { + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + connectionId: '$conn', + }, + ]; + + it('saves and returns variables and tiles that reference them', async () => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [ + { + name: 'Builder', + config: { + displayType: 'line', + sourceId: '$traces', + select: [{ aggFn: 'count' }], + }, + }, + { + name: 'Raw SQL', + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sqlTemplate: 'SELECT 1', + }, + }, + ], + filters, + }); + + expect(result.isError).toBeFalsy(); + const output = JSON.parse(getFirstText(result)); + expect(output.filters).toEqual([ + expect.objectContaining(filters[0]), + expect.objectContaining(filters[1]), + ]); + expect( + output.tiles.map((t: ExternalDashboardTileWithId) => t.config), + ).toEqual([ + expect.objectContaining({ sourceId: '$traces' }), + expect.objectContaining({ connectionId: '$conn' }), + ]); + }); + + it('saves a SQL query filter that runs on a connection variable', async () => { + const sqlFilter = { + type: 'SQL_QUERY', + name: 'Environment', + variableName: 'env', + connectionId: '$conn', + sqlTemplate: 'SELECT DISTINCT env FROM envs', + }; + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [], + filters: [filters[0], sqlFilter], + }); + + expect(result.isError).toBeFalsy(); + expect(JSON.parse(getFirstText(result)).filters[1]).toMatchObject( + sqlFilter, + ); + }); + + it('rejects a tile referencing an undeclared variable', async () => { + const result = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [ + { + name: 'Builder', + config: { + displayType: 'line', + sourceId: '$traces', + select: [{ aggFn: 'count' }], + }, + }, + ], + }); + + expect(result.isError).toBe(true); + expect(getFirstText(result)).toContain( + 'does not name a data source variable', + ); + }); + + it('checks an update without filters against the stored variables', async () => { + const builderTile = (sourceId: string) => ({ + name: 'Builder', + config: { + displayType: 'line', + sourceId, + select: [{ aggFn: 'count' }], + }, + }); + const created = await callTool(ctx.client!, 'clickstack_save_dashboard', { + name: 'Variable dashboard', + tiles: [builderTile(ctx.traceSource._id.toString())], + filters, + }); + expect(created.isError).toBeFalsy(); + + const updated = await callTool(ctx.client!, 'clickstack_save_dashboard', { + id: JSON.parse(getFirstText(created)).id, + name: 'Variable dashboard', + tiles: [builderTile('$traces')], + }); + + expect(updated.isError).toBeFalsy(); + }); + }); }); diff --git a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts index bd6ffe6a6..0e9034c09 100644 --- a/packages/api/src/mcp/__tests__/dashboards/validation.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/validation.test.ts @@ -11,6 +11,7 @@ import { getRawSqlMissingSourceError, getRawSqlTileMacroWarnings, getRawSqlTilesMissingRequiredSource, + getSavedFilterValueWarnings, getTileVariableWarnings, } from '@/mcp/tools/dashboards/validation'; import type { @@ -982,3 +983,31 @@ describe('getFilterVariableWarnings', () => { }); }); }); + +describe('getSavedFilterValueWarnings', () => { + const filters = [ + { type: 'DATA_SOURCE' as const, name: 'Traces', variableName: 'traces' }, + { type: 'CONNECTION' as const, name: 'Cluster', variableName: 'conn' }, + ]; + + it('accepts saved values for data source and connection variables', () => { + expect( + getSavedFilterValueWarnings( + [ + { type: 'variable', name: 'traces', values: ['s1'] }, + { type: 'variable', name: 'conn', values: ['c1'] }, + ], + filters, + ), + ).toEqual([]); + }); + + it('warns about a saved value no filter declares', () => { + expect( + getSavedFilterValueWarnings( + [{ type: 'variable', name: 'nope', values: ['x'] }], + filters, + ), + ).toHaveLength(1); + }); +}); diff --git a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts index 6d3bcc42b..9d5e0e45a 100644 --- a/packages/api/src/mcp/__tests__/dashboards/variables.test.ts +++ b/packages/api/src/mcp/__tests__/dashboards/variables.test.ts @@ -1,10 +1,16 @@ +import { SourceKind } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import { + type ReferenceTargets, resolveDashboardVariables, + resolveTileVariableReferences, withResolvedFilterVariableNames, } from '@/mcp/tools/dashboards/variables'; -import type { ExternalDashboardFilterWithId } from '@/utils/zod'; +import type { + ExternalDashboardFilterWithId, + ExternalDashboardTileWithId, +} from '@/utils/zod'; const sourceId = new mongoose.Types.ObjectId().toString(); @@ -322,3 +328,282 @@ describe('withResolvedFilterVariableNames', () => { ]); }); }); + +describe('resolveTileVariableReferences', () => { + const objectId = () => new mongoose.Types.ObjectId().toString(); + const connectionId = objectId(); + const otherConnectionId = objectId(); + const traceSourceId = objectId(); + const logSourceId = objectId(); + const metricSourceId = objectId(); + const promqlSourceId = objectId(); + 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, + }, + ], + connectionIds: new Set([connectionId, otherConnectionId]), + }; + + const referenceVariableFields = { + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + } as const; + const connectionVariable: ExternalDashboardFilterWithId = { + ...referenceVariableFields, + id: objectId(), + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + }; + const tracesVariable = ( + connection?: string, + ): ExternalDashboardFilterWithId => ({ + ...referenceVariableFields, + id: objectId(), + type: 'DATA_SOURCE', + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + connectionId: connection, + }); + + const sourceVariable = ( + allowedSourceKinds: SourceKind[], + ): ExternalDashboardFilterWithId => ({ + ...referenceVariableFields, + id: objectId(), + type: 'DATA_SOURCE', + name: 'Source', + variableName: 'src', + allowedSourceKinds, + }); + + const builderTile: ExternalDashboardTileWithId = { + id: 'builder', + name: 'Builder', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + displayType: 'number', + sourceId: '$traces', + select: [{ aggFn: 'count', where: '' }], + }, + }; + const rawSqlTile: ExternalDashboardTileWithId = { + id: 'raw-sql', + name: 'Raw SQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sqlTemplate: 'SELECT 1', + }, + }; + + const promqlTile: ExternalDashboardTileWithId = { + id: 'promql', + name: 'PromQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'promql', + displayType: 'line', + sourceId: '$src', + expressions: [{ expression: 'up' }], + }, + } as ExternalDashboardTileWithId; + const searchTile: ExternalDashboardTileWithId = { + id: 'search', + name: 'Search', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + displayType: 'search', + sourceId: '$src', + select: '', + where: '', + whereLanguage: 'sql', + }, + }; + const rawSqlSourceTile: ExternalDashboardTileWithId = { + ...rawSqlTile, + id: 'raw-sql-source', + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sourceId: '$src', + sqlTemplate: 'SELECT 1', + }, + }; + + const resolve = ( + tile: ExternalDashboardTileWithId, + filters: ExternalDashboardFilterWithId[], + selections: Record, + ) => + resolveTileVariableReferences( + tile, + filters, + Object.entries(selections).map(([name, values]) => ({ name, values })), + [], + targets, + ); + + it("resolves a connection reference to the variable's selection", () => { + const result = resolve(rawSqlTile, [connectionVariable], { + conn: [connectionId], + }); + + expect(result).toEqual({ + tile: { + ...rawSqlTile, + config: { ...rawSqlTile.config, connectionId }, + }, + }); + }); + + it('resolves a source on the connection its connection variable selects', () => { + const result = resolve( + builderTile, + [connectionVariable, tracesVariable('$conn')], + { conn: [connectionId], traces: [traceSourceId] }, + ); + + expect(result).toEqual({ + tile: { + ...builderTile, + config: { ...builderTile.config, sourceId: traceSourceId }, + }, + }); + }); + + it('resolves a source of a kind the tile accepts', () => { + const result = resolve( + promqlTile, + [sourceVariable([SourceKind.Log, SourceKind.Promql])], + { src: [promqlSourceId] }, + ); + + expect(result).toEqual({ + tile: { + ...promqlTile, + config: { ...promqlTile.config, sourceId: promqlSourceId }, + }, + }); + }); + + it.each<{ + case: string; + tile: ExternalDashboardTileWithId; + selection: string; + kinds: SourceKind[]; + }>([ + { + case: 'a log source on a PromQL tile', + tile: promqlTile, + selection: logSourceId, + kinds: [SourceKind.Log, SourceKind.Promql], + }, + { + case: 'a metric source on a search tile', + tile: searchTile, + selection: metricSourceId, + kinds: [SourceKind.Log, SourceKind.Metric], + }, + ])('rejects $case', ({ tile, selection, kinds }) => { + expect( + resolve(tile, [sourceVariable(kinds)], { src: [selection] }), + ).toEqual({ + error: expect.stringContaining('this tile only accepts'), + }); + }); + + it('resolves a raw SQL source on the connection the query runs on', () => { + const result = resolve( + rawSqlSourceTile, + [connectionVariable, sourceVariable([SourceKind.Log])], + { conn: [connectionId], src: [logSourceId] }, + ); + + expect(result).toEqual({ + tile: { + ...rawSqlSourceTile, + config: { + ...rawSqlSourceTile.config, + connectionId, + sourceId: logSourceId, + }, + }, + }); + }); + + it('rejects a raw SQL source on another connection than the query', () => { + const result = resolve( + rawSqlSourceTile, + [connectionVariable, sourceVariable([SourceKind.Log])], + { conn: [connectionId], src: [otherConnectionLogSourceId] }, + ); + + expect(result).toEqual({ + error: expect.stringContaining( + `the source is on connection "${otherConnectionId}"`, + ), + }); + }); + + it.each<{ + case: string; + tile: ExternalDashboardTileWithId; + filters: ExternalDashboardFilterWithId[]; + selections: Record; + variable: string; + }>([ + { + case: 'a source selection that is not a source', + tile: builderTile, + filters: [tracesVariable()], + selections: { traces: [connectionId] }, + variable: '$traces', + }, + { + case: 'a source variable whose connection variable has no selection', + tile: builderTile, + filters: [connectionVariable, tracesVariable('$conn')], + selections: { traces: [traceSourceId] }, + variable: '$conn', + }, + { + case: 'a connection selection that is not a connection', + tile: rawSqlTile, + filters: [connectionVariable], + selections: { conn: [traceSourceId] }, + variable: '$conn', + }, + ])('rejects $case', ({ tile, filters, selections, variable }) => { + expect(resolve(tile, filters, selections)).toEqual({ + error: expect.stringContaining(`${variable} variable`), + }); + }); +}); diff --git a/packages/api/src/mcp/prompts/dashboards/content.ts b/packages/api/src/mcp/prompts/dashboards/content.ts index bbfb7167d..125b3c16e 100644 --- a/packages/api/src/mcp/prompts/dashboards/content.ts +++ b/packages/api/src/mcp/prompts/dashboards/content.ts @@ -137,6 +137,8 @@ Apply these before calling clickstack_save_dashboard. Each rule is enforced by t 9h. USE AN ADHOC FILTER TO LET THE USER BUILD FREE-FORM CONDITIONS. filters: [{ type: "ADHOC", name, sourceType: "sql", sources: [""], variableName? }] adds an input where the user picks any column or map key, an operator, and a value; clicking a value in a tile adds a condition too. Every condition is ANDed onto the tiles of its sources (or of appliesToSourceIds) with no per-tile wiring. It is never a variable: its variableName only names the entry its conditions are saved under. Seed conditions with savedFilterValues: [{ type: "adhoc", name: "", conditions: [{ key: "ServiceName", operator: "IN", value: "api" }] }]; IN conditions on the same key are ORed. Declare at most one ad hoc filter per source, since a click updates every ad hoc filter on the clicked tile's source. +9i. TO LET VIEWERS SWITCH THE SOURCE OR CONNECTION, USE A DATA_SOURCE OR CONNECTION FILTER. filters: [{ type: "DATA_SOURCE", name: "Logs source", variableName: "logs", allowedSourceKinds: ["log"] }] adds a required source picker; tiles then set sourceId: "$logs" (filters may use it in sourceId or appliesToSourceIds). A CONNECTION filter does the same for raw SQL tiles' and SQL_QUERY filters' connectionId, and a DATA_SOURCE filter's optional connectionId limits its sources to one connection. Keep allowedSourceKinds to kinds charts treat alike (log + trace, or one kind). Tiles that use either cannot have alerts, and clickstack_query_tile needs a selection for the variable (variableValues or the dashboard's saved value). + 10. UPDATE IS REPLACE, NOT MERGE. clickstack_save_dashboard with an id overwrites tiles, containers, and filters in their entirety. Call clickstack_get_dashboard first when you only want to add or rename one entry; do not send a partial set or you will silently drop everything you omitted. 11. GROUP RELATED TILES INTO CONTAINERS. REQUIRED at five or more tiles, no exceptions. An ungrouped wall of nine or ten tiles is a readability failure even when each tile is correct in isolation. Containers are the right way to introduce structure; markdown tiles for section labels are not. diff --git a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts index 36d5f43a2..c19c9d871 100644 --- a/packages/api/src/mcp/tools/dashboards/patchDashboard.ts +++ b/packages/api/src/mcp/tools/dashboards/patchDashboard.ts @@ -201,6 +201,7 @@ export function registerPatchDashboard({ teamId, tiles: [mergedTile], existingTiles: existingDashboard.tiles ?? [], + existingFilters: existingDashboard.filters, containers: existingDashboard.containers ?? [], }); if (validationError) { diff --git a/packages/api/src/mcp/tools/dashboards/queryTile.ts b/packages/api/src/mcp/tools/dashboards/queryTile.ts index b6cd385b5..1e610b0cd 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTile.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTile.ts @@ -13,7 +13,12 @@ import { getRawSqlTileMacroWarnings, getTileVariableWarnings, } from './validation'; -import { mcpVariableValuesParam, resolveDashboardVariables } from './variables'; +import { + getReferenceTargets, + mcpVariableValuesParam, + resolveDashboardVariables, + resolveTileVariableReferences, +} from './variables'; export function registerQueryTile({ context, @@ -79,8 +84,8 @@ export function registerQueryTile({ const externalDashboard = convertToExternalDashboard(dashboard, { hidePromql: !isPromqlEnabled(context), }); - const tile = externalDashboard.tiles.find(t => t.id === tileId); - if (!tile) { + const storedTile = externalDashboard.tiles.find(t => t.id === tileId); + if (!storedTile) { return mcpUserError( `Tile not found: ${tileId}. Available tile IDs: ${externalDashboard.tiles.map(t => t.id).join(', ')}`, ); @@ -94,6 +99,18 @@ export function registerQueryTile({ return mcpUserError(resolvedVariables.error); } + const resolvedTile = resolveTileVariableReferences( + storedTile, + externalDashboard.filters, + variableValues, + externalDashboard.savedFilterValues, + await getReferenceTargets(teamId.toString()), + ); + if ('error' in resolvedTile) { + return mcpUserError(resolvedTile.error); + } + const { tile } = resolvedTile; + const result = await runConfigTile( teamId.toString(), tile, diff --git a/packages/api/src/mcp/tools/dashboards/queryTiles.ts b/packages/api/src/mcp/tools/dashboards/queryTiles.ts index 44af35c95..a1716461f 100644 --- a/packages/api/src/mcp/tools/dashboards/queryTiles.ts +++ b/packages/api/src/mcp/tools/dashboards/queryTiles.ts @@ -19,7 +19,12 @@ import { getRawSqlTileMacroWarnings, getTileVariableWarnings, } from './validation'; -import { mcpVariableValuesParam, resolveDashboardVariables } from './variables'; +import { + getReferenceTargets, + mcpVariableValuesParam, + resolveDashboardVariables, + resolveTileVariableReferences, +} from './variables'; /** * How many tiles to query against ClickHouse at once. Kept lowish so a batch @@ -230,6 +235,8 @@ export function registerQueryTiles({ .slice(MAX_TILES_PER_CALL) .map(t => t.id); + const referenceTargets = await getReferenceTargets(teamId.toString()); + // Fix one shared deadline for the whole batch that every tile races. const deadlineAt = Date.now() + BATCH_DEADLINE_MS; @@ -251,6 +258,17 @@ export function registerQueryTiles({ return { ...base, status: 'skipped' }; } + const resolvedTile = resolveTileVariableReferences( + tile, + externalDashboard.filters, + variableValues, + externalDashboard.savedFilterValues, + referenceTargets, + ); + if ('error' in resolvedTile) { + return { ...base, status: 'error', error: resolvedTile.error }; + } + // Run the query under the shared deadline. It's passed as a thunk // so withDeadline can skip issuing it entirely once the budget is // spent (see withDeadline). withDeadline hands the thunk an @@ -263,10 +281,13 @@ export function registerQueryTiles({ try { const result = await withDeadline( signal => - runConfigTile(teamId.toString(), tile, startDate, endDate, { - abortSignal: signal, - variables, - }), + runConfigTile( + teamId.toString(), + resolvedTile.tile, + startDate, + endDate, + { abortSignal: signal, variables }, + ), deadlineAt, ); diff --git a/packages/api/src/mcp/tools/dashboards/schemas.ts b/packages/api/src/mcp/tools/dashboards/schemas.ts index 090d00522..0440330f1 100644 --- a/packages/api/src/mcp/tools/dashboards/schemas.ts +++ b/packages/api/src/mcp/tools/dashboards/schemas.ts @@ -26,6 +26,7 @@ import { PromqlQueryTypeSchema, PromqlReducerSchema, SearchConditionTrimmedLanguageSchema, + SourceKind, SQLIntervalSchema, SqlQueryDashboardFilterSchema, StaticListDashboardFilterSchema, @@ -41,10 +42,18 @@ import { externalAdhocSavedFilterValueSchema, externalSqlSavedFilterValueSchema, externalVariableSavedFilterValueSchema, + objectIdOrVariableReferenceSchema, objectIdSchema, tagsSchema, } from '@/utils/zod'; +const SOURCE_VARIABLE_REFERENCE_NOTE = + 'May instead be `$name`, a reference to a DATA_SOURCE filter (variable) on this ' + + 'dashboard, so viewers can switch the source; the variable must offer at least ' + + 'one kind this field accepts.'; + +const SOURCE_ID_DESCRIPTION = `Source ID - call clickstack_list_sources. ${SOURCE_VARIABLE_REFERENCE_NOTE}`; + /** * Metric type values exposed on dashboard tile select items. Restricted to * the kinds the query renderer can translate today; summary is intentionally @@ -651,7 +660,7 @@ const mcpTimeChartDisplayFields = { }; const mcpRowListSourceFields = { - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), where: z .string() .optional() @@ -739,7 +748,7 @@ export const mcpLineTileSchema = mcpTileLayoutSchema.extend({ .object({ ...rejectedTileWhereFields, displayType: z.literal('line').describe('Line chart over time'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -776,7 +785,7 @@ export const mcpLineTileSchema = mcpTileLayoutSchema.extend({ }); const mcpStackedTimeChartConfigFields = { - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -828,7 +837,7 @@ const mcpTableTileSchema = mcpTileLayoutSchema.extend({ .object({ ...rejectedTileWhereFields, displayType: z.literal('table').describe('Tabular aggregated data'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -884,7 +893,7 @@ export const mcpNumberTileSchema = mcpTileLayoutSchema.extend({ displayType: z .literal('number') .describe('Single aggregate scalar value'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .min(1) @@ -925,7 +934,7 @@ const mcpPieTileSchema = mcpTileLayoutSchema.extend({ .object({ ...rejectedTileWhereFields, displayType: z.literal('pie').describe('Pie chart'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .length(1) @@ -973,7 +982,7 @@ const mcpCategoricalBarTileSchema = mcpTileLayoutSchema.extend({ displayType: z .literal('bar') .describe('Bar chart — one bar per group value (not a time series)'), - sourceId: z.string().describe('Source ID – call clickstack_list_sources'), + sourceId: z.string().describe(SOURCE_ID_DESCRIPTION), select: z .array(mcpTileSelectItemSchema) .length(1) @@ -1061,7 +1070,8 @@ const mcpHeatmapTileSchema = mcpTileLayoutSchema.extend({ .string() .describe( 'Source ID. Must be a Trace source today; use clickstack_list_sources and ' + - 'pick one whose kind is "trace".', + 'pick one whose kind is "trace". ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), select: z .array(mcpHeatmapSelectItemSchema) @@ -1106,7 +1116,8 @@ const mcpHeatmapSeriesTileSchema = mcpTileLayoutSchema.extend({ sourceId: z .string() .describe( - 'Source ID of a Trace, Log, or Metric source - call clickstack_list_sources', + 'Source ID of a Trace, Log, or Metric source - call clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), select: z .array(mcpTileSelectItemSchema) @@ -1203,7 +1214,9 @@ export const mcpSqlTileSchema = mcpTileLayoutSchema.extend({ connectionId: z .string() .describe( - 'Connection ID (not sourceId) – call clickstack_list_sources to find available connections', + 'Connection ID (not sourceId) – call clickstack_list_sources to find available connections. ' + + 'May instead be `$name`, a reference to a CONNECTION filter (variable) on this ' + + 'dashboard, so viewers can switch the connection the query runs on.', ), sourceId: z .string() @@ -1213,7 +1226,8 @@ export const mcpSqlTileSchema = mcpTileLayoutSchema.extend({ 'ALWAYS set this for raw SQL tiles UNLESS the query reads from multiple tables ' + '(e.g. JOINs or sub-queries spanning several sources), in which case omit it. ' + 'sourceId is REQUIRED by two macros: $__filters and $__sourceTable. ' + - 'The sourceId must belong to the same connection as connectionId.', + 'The sourceId must belong to the same connection as connectionId. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), sqlTemplate: z.string().describe(` Raw ClickHouse SQL query. SQL guidelines: @@ -1341,7 +1355,8 @@ const mcpPromqlTileSchema = mcpTileLayoutSchema.extend({ sourceId: z .string() .describe( - 'ID of a source whose kind is "promql" – call clickstack_list_sources', + 'ID of a source whose kind is "promql" – call clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), expressions: z .array(mcpPromqlExpressionSchema) @@ -1670,9 +1685,10 @@ const mcpQueryExpressionFilterSchema = z "not declared in any of this dashboard's filters is silently dropped at click time. " + 'Declare an expression here for every column you plan to drive via row-click.', ), - sourceId: objectIdSchema.describe( + sourceId: objectIdOrVariableReferenceSchema.describe( 'Source the filter values are pulled from (for the dropdown). ' + - 'Get IDs from clickstack_list_sources.', + 'Get IDs from clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), sourceMetricType: z .nativeEnum(MetricsDataType) @@ -1701,7 +1717,7 @@ const mcpQueryExpressionFilterSchema = z 'Query language of `where`. Set it explicitly.', ), appliesToSourceIds: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .optional() .describe( 'Source IDs (from clickstack_list_sources) that this filter is applied to. ' + @@ -1778,8 +1794,9 @@ const mcpSqlQueryFilterSchema = z .describe( 'Filter type discriminator for a filter whose dropdown values come from a ClickHouse SQL query.', ), - connectionId: objectIdSchema.describe( - 'ClickHouse connection the query runs on. Get IDs from clickstack_list_sources.', + connectionId: objectIdOrVariableReferenceSchema.describe( + 'ClickHouse connection the query runs on: a connection ID from ' + + 'clickstack_list_sources, or `$name` of a CONNECTION filter on this dashboard.', ), sqlTemplate: SqlQueryDashboardFilterSchema.shape.sqlTemplate.describe( 'ClickHouse SELECT whose FIRST column becomes the dropdown values (cast to ' + @@ -1805,8 +1822,9 @@ const mcpPromqlLabelFilterSchema = z .describe( "Filter type discriminator for a filter whose dropdown lists a Prometheus label's values.", ), - sourceId: objectIdSchema.describe( - 'ID of a source whose kind is "promql". Get IDs from clickstack_list_sources.', + sourceId: objectIdOrVariableReferenceSchema.describe( + 'ID of a source whose kind is "promql". Get IDs from clickstack_list_sources. ' + + SOURCE_VARIABLE_REFERENCE_NOTE, ), label: PromqlLabelDashboardFilterSchema.shape.label.describe( 'Label whose values fill the dropdown, e.g. "job". ' + @@ -1846,11 +1864,11 @@ const mcpAdhocFilterSchema = z '"sql": keys are the columns and map keys of Log, Trace, or Session sources.', ), sources: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .min(1) .describe( 'IDs of the Log, Trace, or Session sources (from clickstack_list_sources) ' + - 'whose keys and values the filter suggests.', + 'whose keys and values the filter suggests, or `$name` of DATA_SOURCE filters.', ), where: z .string() @@ -1863,7 +1881,7 @@ const mcpAdhocFilterSchema = z 'Query language of `where`.', ), appliesToSourceIds: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .optional() .describe( 'IDs of the sources whose tiles the conditions apply to, of the same kind ' + @@ -1885,31 +1903,92 @@ const mcpPromqlAdhocFilterSchema = mcpAdhocFilterSchema.extend({ 'as label matchers to every selector in PromQL tiles.', ), sources: z - .array(objectIdSchema) + .array(objectIdOrVariableReferenceSchema) .min(1) .describe( 'IDs of the sources (from clickstack_list_sources) whose keys and values ' + - 'the filter suggests: Log, Trace, or Session sources for sourceType ' + - '"sql", promql sources for "promql".', + 'the filter suggests, or `$name` of DATA_SOURCE filters: Log, Trace, or ' + + 'Session sources for sourceType "sql", promql sources for "promql".', ), where: mcpAdhocFilterSchema.shape.where.describe( `${mcpAdhocFilterSchema.shape.where.description} sourceType "sql" only; rejected when sourceType is "promql".`, ), }); +// Reference variables are always single-select and required, so they take +// none of the selection-limit fields. +const mcpReferenceVariableBaseShape = { + id: mcpDashboardFilterBaseShape.id, + name: mcpDashboardFilterBaseShape.name, + variableName: mcpDashboardFilterBaseShape.variableName, + // Always required, so the base description's minSelections condition doesn't apply + isGlobalRequirement: mcpDashboardFilterBaseShape.isGlobalRequirement.describe( + 'Block EVERY tile on the dashboard until a value is selected, not just ' + + 'the ones that reference this variable.', + ), +}; + +const mcpDataSourceFilterSchema = z + .object({ + ...mcpReferenceVariableBaseShape, + type: z + .literal(DashboardFilterType.enum.DATA_SOURCE) + .describe( + 'Filter type discriminator for a variable whose value is a source.', + ), + allowedSourceKinds: z + .array(z.nativeEnum(SourceKind)) + .min(1) + .describe( + 'Kinds of sources offered in the dropdown. A tile or filter can reference the ' + + 'variable if it accepts at least one listed kind. A tile whose selected source ' + + 'is a kind it cannot use (e.g. a log source on a PromQL tile) errors instead of ' + + 'running, so prefer kinds that charts treat alike (log + trace, or a single kind).', + ), + connectionId: objectIdOrVariableReferenceSchema + .optional() + .describe( + 'Optional connection the offered sources are limited to: a connection ID, or ' + + '`$name` of a CONNECTION filter on this dashboard.', + ), + }) + .describe( + 'A variable whose single, required value is a source. Tiles and other filters ' + + 'reference it as `$variableName` in sourceId (or appliesToSourceIds) instead of a ' + + 'source ID; tiles stay blocked until a source is selected.', + ); + +const mcpConnectionFilterSchema = z + .object({ + ...mcpReferenceVariableBaseShape, + type: z + .literal(DashboardFilterType.enum.CONNECTION) + .describe( + 'Filter type discriminator for a variable whose value is a connection.', + ), + }) + .describe( + 'A variable whose single, required value is a connection. Raw SQL tiles reference ' + + 'it as `$variableName` in connectionId, and DATA_SOURCE and SQL_QUERY filters in ' + + 'connectionId.', + ); + const mcpDashboardFilterSchema = z .discriminatedUnion('type', [ mcpQueryExpressionFilterSchema, mcpStaticListFilterSchema, mcpSqlQueryFilterSchema, mcpAdhocFilterSchema, + mcpDataSourceFilterSchema, + mcpConnectionFilterSchema, ]) .describe( 'A dashboard-level filter the user can adjust in the dashboard filter bar. ' + 'QUERY_EXPRESSION queries its dropdown values from a source column; ' + 'STATIC_LIST declares them inline; SQL_QUERY reads them from a SQL query. ' + 'STATIC_LIST and SQL_QUERY are always variable-only. ADHOC holds free-form ' + - 'conditions and always broadcasts.', + 'conditions and always broadcasts. DATA_SOURCE and CONNECTION select the ' + + 'source or connection that tiles referencing them as `$variableName` use.', ); const mcpPromqlDashboardFilterSchema = z @@ -1919,6 +1998,8 @@ const mcpPromqlDashboardFilterSchema = z mcpSqlQueryFilterSchema, mcpPromqlLabelFilterSchema, mcpPromqlAdhocFilterSchema, + mcpDataSourceFilterSchema, + mcpConnectionFilterSchema, ]) .describe( 'A dashboard-level filter the user can adjust in the dashboard filter bar. ' + @@ -1926,7 +2007,8 @@ const mcpPromqlDashboardFilterSchema = z 'STATIC_LIST declares them inline; SQL_QUERY reads them from a SQL query; ' + 'PROMETHEUS_LABEL lists the values of a label on a promql source. Those three ' + 'are always variable-only. ADHOC holds free-form conditions on SQL or promql ' + - 'sources and always broadcasts.', + 'sources and always broadcasts. DATA_SOURCE and CONNECTION select the source ' + + 'or connection that tiles referencing them as `$variableName` use.', ); export type McpDashboardFilter = z.infer; @@ -2011,7 +2093,16 @@ const mcpFiltersParam = z ']\n' + 'with savedFilterValues: [{ "type": "adhoc", "name": "conditions", "conditions": ' + '[{ "key": "ServiceName", "operator": "IN", "value": "api" }, ' + - '{ "key": "ServiceName", "operator": "IN", "value": "web" }] }].', + '{ "key": "ServiceName", "operator": "IN", "value": "web" }] }].\n\n' + + 'Example (data source variable: viewers pick which logs source every tile reads):\n' + + '[\n' + + ' { "type": "DATA_SOURCE", "name": "Logs source", "variableName": "logs",\n' + + ' "allowedSourceKinds": ["log"] }\n' + + ']\n' + + 'Tiles then set "sourceId": "$logs". A CONNECTION filter works the same way for ' + + 'raw SQL tiles ("connectionId": "$conn"); a DATA_SOURCE filter may set ' + + '"connectionId" to limit its sources to one connection. Alerts are not supported ' + + 'on tiles that use either.', ); const PROMQL_FILTERS_EXAMPLE = diff --git a/packages/api/src/mcp/tools/dashboards/validation.ts b/packages/api/src/mcp/tools/dashboards/validation.ts index d678b3772..d323c86ac 100644 --- a/packages/api/src/mcp/tools/dashboards/validation.ts +++ b/packages/api/src/mcp/tools/dashboards/validation.ts @@ -6,6 +6,8 @@ import { getFilterVariableName, isAdhocConditionSupported, isFilterVariableEnabled, + isReferenceVariableFilterType, + pairWithVariableNames, validateSqlQueryFilterTemplate, } from '@hyperdx/common-utils/dist/filters'; import { @@ -264,7 +266,8 @@ export function getFilterVariableWarnings( * `name` matches no filter of its kind, or an ad hoc condition its filter's * source type can't express, is silently ignored when the dashboard loads, so * it looks like a saved default but never applies. Warn so the agent can fix - * it. + * it. Data source and connection variables count as variable-enabled filters, + * though they are not text variables. */ export function getSavedFilterValueWarnings( savedFilterValues: DashboardFilterValue[] | undefined, @@ -273,11 +276,16 @@ export function getSavedFilterValueWarnings( | undefined, ): string[] { if (!savedFilterValues?.length) return []; - const declaredNames = new Set( - getDashboardVariableDeclarations(filters).map( + const declaredNames = new Set([ + ...getDashboardVariableDeclarations(filters).map( declaration => declaration.name, ), - ); + ...pairWithVariableNames( + (filters ?? []).filter(filter => + isReferenceVariableFilterType(filter.type), + ), + ).map(({ name }) => name), + ]); const adhocSourceTypeByName = new Map( (filters ?? []).flatMap(filter => filter.type === 'ADHOC' && filter.sourceType diff --git a/packages/api/src/mcp/tools/dashboards/variables.ts b/packages/api/src/mcp/tools/dashboards/variables.ts index f1b98a611..7f5e91cb9 100644 --- a/packages/api/src/mcp/tools/dashboards/variables.ts +++ b/packages/api/src/mcp/tools/dashboards/variables.ts @@ -2,18 +2,48 @@ import { getDashboardVariableDeclarations, getDashboardVariableFilters, getFilterVariableName, + isDataSourceFilter, isFilterVariableEnabled, isStaticListFilter, } from '@hyperdx/common-utils/dist/filters'; -import type { ChartVariable } from '@hyperdx/common-utils/dist/types'; +import { getSavedConfigAllowedSourceKinds } from '@hyperdx/common-utils/dist/guards'; +import { + getReferenceVariableFilters, + getStringField, + isSourceOfferedByVariable, + parseVariableReference, +} from '@hyperdx/common-utils/dist/referenceVariables'; +import type { + ChartVariable, + SavedChartConfig, + SourceKind, +} from '@hyperdx/common-utils/dist/types'; import { isFilterSingleSelect } from '@hyperdx/common-utils/dist/variables'; import { z } from 'zod'; +import { getConnectionsByTeam } from '@/controllers/connection'; +import { getSources } from '@/controllers/sources'; +import { + convertToInternalTileConfig, + type ExternalDashboard, + isConfigTile, + isRawSqlExternalTileConfig, +} from '@/routers/external-api/v2/utils/dashboards'; import type { ExternalDashboardFilter, ExternalDashboardFilterWithId, + ExternalDashboardTileWithId, } from '@/utils/zod'; +type ExternalFilters = + | (ExternalDashboardFilter | ExternalDashboardFilterWithId)[] + | undefined; + +/** Names of the data source and connection variables a dashboard declares. */ +function getReferenceVariableNames(filters: ExternalFilters): Set { + return new Set(getReferenceVariableFilters(filters).map(({ name }) => name)); +} + /** Optional per-variable selection for a tile run. */ export const mcpVariableValuesParam = z .array( @@ -28,7 +58,9 @@ export const mcpVariableValuesParam = z .array(z.string()) .describe( 'Values to treat as selected. An empty array means nothing is selected for this variable. ' + - "For a STATIC_LIST filter's variable, every value must be one of the filter's declared options.", + "For a STATIC_LIST filter's variable, every value must be one of the filter's declared options. " + + 'For a DATA_SOURCE or CONNECTION variable, pass one source or connection ID; it ' + + "overrides the dashboard's saved selection.", ), }), ) @@ -65,9 +97,11 @@ export function resolveDashboardVariables( if (!variableValues?.length) return { variables }; const byName = new Map(variables.map(variable => [variable.name, variable])); + // Resolved separately, by resolveTileVariableReferences + const referenceVariableNames = getReferenceVariableNames(filters); const unknownVariableValues = variableValues .map(({ name }) => name) - .filter(name => !byName.has(name)); + .filter(name => !byName.has(name) && !referenceVariableNames.has(name)); if (unknownVariableValues.length > 0) { const available = variables.length > 0 @@ -121,12 +155,197 @@ export function resolveDashboardVariables( // Override the default empty selection with the given variableValues for (const { name, values } of variableValues) { - byName.get(name)!.values = values; + const variable = byName.get(name); + if (variable) variable.values = values; } return { variables }; } +/** The team's sources and connections that a reference variable may select. */ +export type ReferenceTargets = { + sources: { + id: string; + kind: SourceKind; + connection: string; + disabled?: boolean; + }[]; + connectionIds: ReadonlySet; +}; + +export async function getReferenceTargets( + teamId: string, +): Promise { + const [sources, connections] = await Promise.all([ + getSources(teamId), + getConnectionsByTeam(teamId), + ]); + return { + sources: sources.map(source => ({ + id: source._id.toString(), + kind: source.kind, + connection: source.connection.toString(), + disabled: source.disabled, + })), + connectionIds: new Set(connections.map(c => c._id.toString())), + }; +} + +/** + * 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 = new Map(); + for (const value of savedFilterValues ?? []) { + if (value.type === 'variable') selections.set(value.name, value.values); + } + // resolveDashboardVariables has already rejected unknown names + for (const { name, values } of variableValues ?? []) { + selections.set(name, values); + } + const sourceVariables = new Map( + getReferenceVariableFilters(filters).flatMap(({ filter, name }) => + isDataSourceFilter(filter) ? [[name, filter] as const] : [], + ), + ); + + const isSourceOffered = (name: string, id: string) => { + const variable = sourceVariables.get(name); + const source = targets.sources.find(source => source.id === id); + if (variable == null || source == null) return false; + // An unselected connection variable stays a reference, which matches no source + const connectionName = parseVariableReference(variable.connectionId); + const connection = + connectionName == null + ? variable.connectionId + : (selections.get(connectionName)?.[0] ?? variable.connectionId); + return isSourceOfferedByVariable(source, { + allowedSourceKinds: variable.allowedSourceKinds, + connection, + }); + }; + + const describeOffer = (name: string) => { + const variable = sourceVariables.get(name); + if (variable == null) return 'no sources'; + const connectionName = parseVariableReference(variable.connectionId); + const connection = + connectionName != null + ? ` on the connection the $${connectionName} variable selects` + : variable.connectionId + ? ` on connection ${variable.connectionId}` + : ''; + return `enabled ${variable.allowedSourceKinds.join(', ')} sources${connection}`; + }; + + let config: object = tile.config; + for (const field of ['sourceId', 'connectionId'] as const) { + const name = parseVariableReference(getStringField(config, field)); + if (name == null) continue; + const subject = `Tile "${tile.id}" reads its ${field} from the $${name} variable`; + const values = selections.get(name) ?? []; + if (values.length !== 1) { + return { + error: + values.length === 0 + ? `${subject}, which has no selection. Pass one ID for it in variableValues, or save a selection on the dashboard.` + : `${subject}, which accepts exactly one value.`, + }; + } + const [id] = values; + const isOffered = + field === 'connectionId' + ? targets.connectionIds.has(id) + : isSourceOffered(name, id); + if (!isOffered) { + const offer = + field === 'connectionId' + ? 'connections on this team' + : describeOffer(name); + return { + error: `${subject}, which selects "${id}" but only offers ${offer}.`, + }; + } + config = { ...config, [field]: id }; + } + + const resolved = { ...tile, config }; + const tileError = getResolvedSourceError(resolved, tile.config, targets); + return tileError != null ? { error: tileError } : { tile: resolved }; +} + +/** + * Checks a resolved source the variable offers but the tile can't use, which + * the dashboard shows as an error in place of the tile: a kind the tile's + * chart type doesn't accept, or, for raw SQL, a source on another connection + * than the query runs on. + */ +function getResolvedSourceError( + tile: ExternalDashboardTileWithId, + storedConfig: object, + targets: ReferenceTargets, +): string | null { + if (!isConfigTile(tile)) return null; + const sourceId = getStringField(tile.config, 'sourceId'); + const source = targets.sources.find(s => s.id === sourceId); + if (source == null) return null; + const sourceName = parseVariableReference( + getStringField(storedConfig, 'sourceId'), + ); + const connectionName = parseVariableReference( + getStringField(storedConfig, 'connectionId'), + ); + + if (sourceName != null) { + let config: SavedChartConfig; + try { + config = convertToInternalTileConfig(tile).config; + } catch { + // A shape the converter refuses fails when the tile runs + return null; + } + const allowedKinds = getSavedConfigAllowedSourceKinds(config); + if (!allowedKinds.includes(source.kind)) { + return ( + `Tile "${tile.id}" reads its sourceId from the $${sourceName} variable, which ` + + `selects "${source.id}", a ${source.kind} source, but this tile only accepts ` + + `${allowedKinds.join(', ')} sources.` + ); + } + } + + if ( + (sourceName != null || connectionName != null) && + isRawSqlExternalTileConfig(tile.config) && + source.connection !== tile.config.connectionId + ) { + const from = [sourceName, connectionName] + .filter((name): name is string => name != null) + .map(name => `$${name}`) + .join(' and '); + return ( + `Tile "${tile.id}" resolves source "${source.id}" and connection ` + + `"${tile.config.connectionId}" from ${from}, but the source is on connection ` + + `"${source.connection}". Select a source on the connection the query runs on.` + ); + } + return null; +} + /** Options of each static filter, keyed by the variable name it answers to. */ function buildStaticOptionsByName( filters: ExternalDashboardFilter[] | undefined, diff --git a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts index 405e260fd..d6065229c 100644 --- a/packages/api/src/routers/api/__tests__/dashboard.int.test.ts +++ b/packages/api/src/routers/api/__tests__/dashboard.int.test.ts @@ -1519,6 +1519,185 @@ describe('dashboard router', () => { ); }); + describe('data source variables', () => { + const dataSourceFilter = { + id: new Types.ObjectId().toString(), + type: 'DATA_SOURCE' as const, + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + it('persists a tile and a filter that reference the variable', async () => { + const tile = makeTile({ sourceId: '$logs' }); + const queriedFilter = { + id: new Types.ObjectId().toString(), + type: 'QUERY_EXPRESSION' as const, + name: 'Service', + expression: 'ServiceName', + source: '$logs', + }; + + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [tile], + filters: [dataSourceFilter, queriedFilter], + }) + .expect(200); + + expect(created.body.tiles[0].config.source).toBe('$logs'); + expect(created.body.filters).toEqual([dataSourceFilter, queriedFilter]); + }); + + it('rejects a reference to an unknown variable', async () => { + const res = await agent + .post('/dashboards') + .send({ ...MOCK_DASHBOARD, tiles: [makeTile({ sourceId: '$nope' })] }) + .expect(400); + + expect(JSON.stringify(res.body)).toMatch( + /does not name a data source variable/, + ); + }); + + it('rejects a variable offering no kind the reference can use', async () => { + const res = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [ + { ...dataSourceFilter, allowedSourceKinds: [SourceKind.Promql] }, + ], + }) + .expect(400); + + expect(res.body.message).toMatch(/offers no kind of source/); + }); + + it('accepts a variable offering some kinds the reference cannot use', async () => { + await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [ + { + ...dataSourceFilter, + allowedSourceKinds: [SourceKind.Log, SourceKind.Promql], + }, + ], + }) + .expect(200); + }); + + it('validates a PATCH of tiles against the stored filters', async () => { + const created = await agent + .post('/dashboards') + .send({ ...MOCK_DASHBOARD, filters: [dataSourceFilter] }) + .expect(200); + + await agent + .patch(`/dashboards/${created.body.id}`) + .send({ tiles: [makeTile({ sourceId: '$logs' })] }) + .expect(200); + const res = await agent + .patch(`/dashboards/${created.body.id}`) + .send({ + tiles: [ + makeTile({ sourceId: '$logs' }), + makeTile({ sourceId: '$nope' }), + ], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + // Only references an update adds are checked, so editing a variable + // doesn't fail on the tiles and filters that already use it. + it('saves a filter edit that leaves stored references unsatisfied', async () => { + const adhocFilter = { + id: new Types.ObjectId().toString(), + type: 'ADHOC' as const, + name: 'Conditions', + sourceType: 'sql' as const, + sources: ['$logs'], + isBroadcastEnabled: true, + isVariableEnabled: true, + }; + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [dataSourceFilter, adhocFilter], + }) + .expect(200); + + await agent + .patch(`/dashboards/${created.body.id}`) + .send({ + filters: [ + { ...dataSourceFilter, allowedSourceKinds: [SourceKind.Promql] }, + adhocFilter, + ], + }) + .expect(200); + await agent + .patch(`/dashboards/${created.body.id}`) + .send({ filters: [adhocFilter] }) + .expect(200); + }); + + it('drops an alert on a tile that uses the variable', async () => { + await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [ + makeTile({ + sourceId: '$logs', + alert: makeMockAlert(webhook._id.toString()), + }), + ], + filters: [dataSourceFilter], + }) + .expect(200); + + expect(await Alert.countDocuments({ team: team._id })).toBe(0); + }); + + it('rejects a tile alert on a tile that uses the variable', async () => { + const created = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + tiles: [makeTile({ sourceId: '$logs' })], + filters: [dataSourceFilter], + }) + .expect(200); + + const res = await agent + .post('/alerts') + .send( + makeAlertInput({ + dashboardId: created.body.id, + tileId: created.body.tiles[0].id, + webhookId: webhook._id.toString(), + }), + ) + .expect(400); + + expect(res.body.message).toMatch(/data source or connection variable/); + }); + }); + describe('promql-label filters', () => { const createPromqlSource = () => Source.create({ @@ -1966,6 +2145,42 @@ describe('dashboard router', () => { expect(updated.body.filters).toEqual([moved]); }); + + const connectionFilter = { + id: new Types.ObjectId().toString(), + type: 'CONNECTION' as const, + name: 'Connection', + variableName: 'conn', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + it('accepts a connection variable as the connection', async () => { + const filter = makeSqlFilter({ connection: '$conn' }); + + const created = await agent + .post('/dashboards') + .send({ ...MOCK_DASHBOARD, filters: [connectionFilter, filter] }) + .expect(200); + + expect(created.body.filters).toEqual([connectionFilter, filter]); + }); + + it('rejects a reference that names no connection variable', async () => { + const response = await agent + .post('/dashboards') + .send({ + ...MOCK_DASHBOARD, + filters: [makeSqlFilter({ connection: '$conn' })], + }) + .expect(400); + + expect(response.body.message).toMatch( + /does not name a connection variable/, + ); + }); }); describe('ad hoc filters', () => { diff --git a/packages/api/src/routers/api/dashboards.ts b/packages/api/src/routers/api/dashboards.ts index e88f39e32..ac54d3e74 100644 --- a/packages/api/src/routers/api/dashboards.ts +++ b/packages/api/src/routers/api/dashboards.ts @@ -1,9 +1,11 @@ import { + getVariableReferenceError, validateDashboardFilterModes, validateDashboardFilterOptionUniqueness, validateDashboardFilterVariableNames, } from '@hyperdx/common-utils/dist/dashboardValidation'; import { isSqlQueryFilter } from '@hyperdx/common-utils/dist/filters'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { DashboardFilter, DashboardSchema, @@ -77,7 +79,10 @@ async function validateFilterSources( filters: DashboardFilter[] = [], existingFilters: DashboardFilter[] = [], ): Promise { - const refs = getChangedFilterSourceRefs(filters, existingFilters); + const refs = getChangedFilterSourceRefs(filters, existingFilters).filter( + // Variable references are checked by validateDashboardVariableReferences + ref => parseVariableReference(ref.id) == null, + ); if (refs.length === 0) return null; return getFilterSourceRefError(refs, await getSources(teamId.toString())); } @@ -85,7 +90,8 @@ async function validateFilterSources( /** * Rejects SQL_QUERY filters whose connection doesn't belong to the team. As in * `validateFilterSources`, a connection the stored filter with the same ID - * already used is skipped. Returns an error message, or null. + * already used is skipped, and so is a variable reference. Returns an error + * message, or null. */ async function validateFilterConnections( teamId: ObjectId, @@ -101,7 +107,10 @@ async function validateFilterConnections( filters .filter(isSqlQueryFilter) .filter( - filter => existingConnectionById.get(filter.id) !== filter.connection, + filter => + // Variable references are checked by validateDashboardVariableReferences + parseVariableReference(filter.connection) == null && + existingConnectionById.get(filter.id) !== filter.connection, ) .map(filter => filter.connection), ); @@ -181,10 +190,9 @@ router.post( // dashboard to the provisioner. const dashboard = _.omit(req.body, 'provisioned'); - const filterError = await validateFilterReferences( - teamId, - req.body.filters, - ); + const filterError = + getVariableReferenceError(req.body.tiles, req.body.filters) ?? + (await validateFilterReferences(teamId, req.body.filters)); if (filterError != null) { return res.status(400).json({ message: filterError }); } @@ -229,11 +237,19 @@ router.patch( // null still signals field removal downstream. const updates = DashboardWithoutIdSchema.partial().parse(req.body); - const filterError = await validateFilterReferences( - teamId, - req.body.filters, - dashboard.filters, - ); + const filterError = + // Only references this update adds are checked, so a filter edit + // can't fail on tiles and filters it didn't touch + getVariableReferenceError( + req.body.tiles ?? dashboard.tiles, + req.body.filters ?? dashboard.filters, + dashboard, + ) ?? + (await validateFilterReferences( + teamId, + req.body.filters, + dashboard.filters, + )); if (filterError != null) { return res.status(400).json({ message: filterError }); } diff --git a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts index 92a72d976..88faec017 100644 --- a/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts +++ b/packages/api/src/routers/external-api/__tests__/dashboards.int.test.ts @@ -6329,6 +6329,35 @@ describe('External API v2 Dashboards - new format', () => { expect(response.body.message).toContain(connectionId); }); + it('accepts a connection variable as the connection', async () => { + const response = await sendFilters([ + { + id: new ObjectId().toString(), + type: 'CONNECTION', + name: 'Connection', + variableName: 'conn', + }, + sqlFilterInput({ connectionId: '$conn' }), + ]); + + expect(response.status).toBe(200); + expect(response.body.data.filters[1]).toMatchObject({ + type: 'SQL_QUERY', + connectionId: '$conn', + }); + }); + + it('rejects a reference that names no connection variable', async () => { + const response = await sendFilters([ + sqlFilterInput({ connectionId: '$conn' }), + ]); + + expect(response.status).toBe(400); + expect(response.body.message).toMatch( + /does not name a connection variable/, + ); + }); + it.each([ ['broadcast enabled', { isBroadcastEnabled: true }], ['not variable-enabled', { isVariableEnabled: false }], @@ -8511,6 +8540,381 @@ describe('External API v2 Dashboards - new format', () => { }); }); + describe('reference variables', () => { + const connectionFilter = { + type: 'CONNECTION' as const, + name: 'Connection', + variableName: 'conn', + }; + const dataSourceFilter = { + type: 'DATA_SOURCE' as const, + name: 'Traces source', + variableName: 'traces', + allowedSourceKinds: [SourceKind.Trace], + connectionId: '$conn', + }; + const rawSqlTile = { + name: 'Raw SQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'sql', + displayType: 'table', + connectionId: '$conn', + sqlTemplate: 'SELECT 1', + }, + }; + + it('round-trips the variables, their values and the tiles that use them', async () => { + const globalConnectionFilter = { + ...connectionFilter, + isGlobalRequirement: true, + }; + const savedFilterValues = [ + { type: 'variable', name: 'conn', values: [connection._id.toString()] }, + { + type: 'variable', + name: 'traces', + values: [traceSource._id.toString()], + }, + ]; + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' }), rawSqlTile], + tags: [], + filters: [globalConnectionFilter, dataSourceFilter], + savedFilterValues, + }) + .expect(200); + + const fetched = await authRequest( + 'get', + `${BASE_URL}/${created.body.data.id}`, + ).expect(200); + expect(fetched.body.data.filters).toEqual([ + expect.objectContaining(globalConnectionFilter), + expect.objectContaining(dataSourceFilter), + ]); + expect(fetched.body.data.tiles.map(t => t.config)).toEqual([ + expect.objectContaining({ sourceId: '$traces' }), + expect.objectContaining({ connectionId: '$conn' }), + ]); + expect(fetched.body.data.savedFilterValues).toEqual(savedFilterValues); + + const echoed = await authRequest( + 'put', + `${BASE_URL}/${created.body.data.id}`, + ) + .send(fetched.body.data) + .expect(200); + expect(echoed.body.data.filters).toEqual(fetched.body.data.filters); + expect(echoed.body.data.tiles.map(t => t.config)).toEqual( + fetched.body.data.tiles.map(t => t.config), + ); + }); + + it('rejects a tile referencing an undeclared variable', async () => { + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' })], + tags: [], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + it('rejects a connection reference to an undeclared connection variable', async () => { + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [rawSqlTile], + tags: [], + filters: [{ ...dataSourceFilter, connectionId: undefined }], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a connection variable/); + }); + + it('accepts a PromQL tile and PROMETHEUS_LABEL filter on a PromQL data source variable', async () => { + await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + name: 'PromQL', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + configType: 'promql', + displayType: 'line', + sourceId: '$prom', + expressions: [{ expression: 'up' }], + }, + }, + ], + tags: [], + filters: [ + { + type: 'DATA_SOURCE', + name: 'PromQL source', + variableName: 'prom', + allowedSourceKinds: [SourceKind.Promql], + }, + { + type: 'PROMETHEUS_LABEL', + name: 'Job', + sourceId: '$prom', + label: 'job', + }, + ], + }) + .expect(200); + }); + + it('accepts an ADHOC filter whose sources reference a data source variable', async () => { + const adhocFilter = { + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: ['$traces'], + appliesToSourceIds: ['$traces'], + }; + await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [], + tags: [], + filters: [omit(dataSourceFilter, 'connectionId'), adhocFilter], + }) + .expect(200); + + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [], + tags: [], + filters: [adhocFilter], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + it('accepts a raw SQL tile with a fixed source on a connection variable', async () => { + await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + ...rawSqlTile, + config: { + ...rawSqlTile.config, + sourceId: traceSource._id.toString(), + }, + }, + ], + tags: [], + filters: [connectionFilter], + }) + .expect(200); + }); + + it("rejects a raw SQL tile whose data source variable is limited to another connection than the tile's", async () => { + const otherConnection = await Connection.create({ + team: team._id, + name: 'Other Connection', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + + const res = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + ...rawSqlTile, + config: { + ...rawSqlTile.config, + connectionId: connection._id.toString(), + sourceId: '$traces', + }, + }, + ], + tags: [], + filters: [ + { + ...dataSourceFilter, + connectionId: otherConnection._id.toString(), + }, + ], + }) + .expect(400); + expect(res.body.message).toBe( + 'The following source IDs do not match the specified connections: $traces', + ); + }); + + it('checks a PUT without filters against the stored variables', async () => { + const dashboard = await createTestDashboard({ + filters: [ + { id: new ObjectId().toString(), ...connectionFilter }, + { + id: new ObjectId().toString(), + ...omit(dataSourceFilter, 'connectionId'), + connection: '$conn', + }, + ], + }); + + await authRequest('put', `${BASE_URL}/${dashboard._id}`) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' })], + tags: [], + }) + .expect(200); + }); + + // Only references an update adds are checked, so editing a variable + // doesn't fail on the tiles that already use it. + it('accepts a PUT whose filter change leaves stored references unsatisfied', async () => { + const variable = { ...dataSourceFilter, connectionId: undefined }; + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [makeExternalTile({ sourceId: '$traces' })], + tags: [], + filters: [variable], + }) + .expect(200); + const fetched = await authRequest( + 'get', + `${BASE_URL}/${created.body.data.id}`, + ).expect(200); + const url = `${BASE_URL}/${created.body.data.id}`; + const [storedVariable] = fetched.body.data.filters; + + await authRequest('put', url) + .send({ + ...fetched.body.data, + filters: [ + { ...storedVariable, allowedSourceKinds: [SourceKind.Promql] }, + ], + }) + .expect(200); + await authRequest('put', url) + .send({ ...fetched.body.data, filters: [] }) + .expect(200); + + const res = await authRequest('put', url) + .send({ + ...fetched.body.data, + filters: [], + tiles: [ + ...fetched.body.data.tiles, + makeExternalTile({ sourceId: '$nope' }), + ], + }) + .expect(400); + expect(res.body.message).toMatch(/does not name a data source variable/); + }); + + it("accepts a PUT that moves a raw SQL tile's data source variable to another connection", async () => { + const otherConnection = await Connection.create({ + team: team._id, + name: 'Other Connection', + host: config.CLICKHOUSE_HOST, + username: config.CLICKHOUSE_USER, + password: config.CLICKHOUSE_PASSWORD, + }); + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [ + { + ...rawSqlTile, + config: { + ...rawSqlTile.config, + connectionId: connection._id.toString(), + sourceId: '$traces', + }, + }, + ], + tags: [], + filters: [ + { ...dataSourceFilter, connectionId: connection._id.toString() }, + ], + }) + .expect(200); + const fetched = await authRequest( + 'get', + `${BASE_URL}/${created.body.data.id}`, + ).expect(200); + const [storedVariable] = fetched.body.data.filters; + + await authRequest('put', `${BASE_URL}/${created.body.data.id}`) + .send({ + ...fetched.body.data, + filters: [ + { + ...storedVariable, + connectionId: otherConnection._id.toString(), + }, + ], + }) + .expect(200); + }); + + it('deletes the alert of a tile that moves to a data source variable', async () => { + const tile = makeExternalTile({ sourceId: traceSource._id.toString() }); + const created = await authRequest('post', BASE_URL) + .send({ + name: 'Variable Dashboard', + tiles: [tile], + tags: [], + filters: [connectionFilter, dataSourceFilter], + }) + .expect(200); + const { id: dashboardId, tiles } = created.body.data; + const webhook = await Webhook.create({ + name: 'Test Webhook', + service: WebhookService.Slack, + url: 'https://hooks.slack.com/test', + team: team._id, + }); + const alert = await Alert.create({ + team: team._id, + dashboard: dashboardId, + tileId: tiles[0].id, + source: AlertSource.TILE, + threshold: 100, + interval: '1h', + thresholdType: AlertThresholdType.ABOVE, + channel: { type: 'webhook', webhookId: webhook._id.toString() }, + }); + + await authRequest('put', `${BASE_URL}/${dashboardId}`) + .send({ + ...created.body.data, + tiles: [ + { + ...tiles[0], + config: { ...tiles[0].config, sourceId: '$traces' }, + }, + ], + }) + .expect(200); + + expect(await Alert.findById(alert._id)).toBeNull(); + }); + }); + describe('ad hoc filters', () => { const adhocFilter = () => ({ id: new ObjectId().toString(), diff --git a/packages/api/src/routers/external-api/v2/dashboards.ts b/packages/api/src/routers/external-api/v2/dashboards.ts index 0b6bacea0..511775a03 100644 --- a/packages/api/src/routers/external-api/v2/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/dashboards.ts @@ -705,7 +705,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "line" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -792,7 +792,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "stacked_bar" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -862,7 +862,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "stacked_line" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -938,7 +938,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "table" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1012,7 +1012,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "number" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1071,7 +1071,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "pie" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1124,7 +1124,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "bar" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1217,7 +1217,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "distribution" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1265,7 +1265,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "series" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: array @@ -1314,7 +1314,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "search" * sourceId: * type: string - * description: ID of the data source to query. + * description: ID of the data source to query, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: string @@ -1345,7 +1345,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "event_patterns" * sourceId: * type: string - * description: ID of the data source to mine patterns from. + * description: ID of the data source to mine patterns from, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. * example: "65f5e4a3b9e77c001a111111" * select: * type: string @@ -1395,7 +1395,9 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "sql" * connectionId: * type: string - * description: ID of the ClickHouse connection to execute the query against. + * description: | + * ID of the ClickHouse connection to execute the query against, or + * `$connectionVariable` of a CONNECTION filter on the dashboard. * example: "65f5e4a3b9e77c001a567890" * sqlTemplate: * type: string @@ -1404,7 +1406,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "SELECT count() FROM otel_logs WHERE timestamp > now() - INTERVAL 1 HOUR" * sourceId: * type: string - * description: Optional ID of the data source associated with this Raw SQL chart. Used for applying dashboard filters. + * description: Optional ID of the data source associated with this Raw SQL chart, or `$sourceVariable` of a DATA_SOURCE filter on the dashboard. Used for applying dashboard filters. * example: "65f5e4a3b9e77c001a567890" * numberFormat: * $ref: '#/components/schemas/NumberFormat' @@ -2420,6 +2422,8 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * - $ref: '#/components/schemas/PrometheusLabelFilterInput' * - $ref: '#/components/schemas/SqlQueryFilterInput' * - $ref: '#/components/schemas/AdhocFilterInput' + * - $ref: '#/components/schemas/DataSourceFilterInput' + * - $ref: '#/components/schemas/ConnectionFilterInput' * discriminator: * propertyName: type * mapping: @@ -2428,6 +2432,145 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * PROMETHEUS_LABEL: '#/components/schemas/PrometheusLabelFilterInput' * SQL_QUERY: '#/components/schemas/SqlQueryFilterInput' * ADHOC: '#/components/schemas/AdhocFilterInput' + * DATA_SOURCE: '#/components/schemas/DataSourceFilterInput' + * CONNECTION: '#/components/schemas/ConnectionFilterInput' + * + * DataSourceFilterInput: + * type: object + * description: | + * A variable whose single, required value is a source. Tiles reference it + * as `$variableName` in their sourceId, and other filters in sourceId or + * appliesToSourceIds, so viewers can switch the source those read. Tiles + * that use it do not load until a source is selected, and cannot have + * alerts. + * required: + * - type + * - name + * - allowedSourceKinds + * properties: + * type: + * type: string + * enum: [DATA_SOURCE] + * description: Filter type discriminator. Must be "DATA_SOURCE". + * example: "DATA_SOURCE" + * name: + * type: string + * minLength: 1 + * description: Display name of the variable's dropdown + * example: "Logs source" + * variableName: + * type: string + * maxLength: 64 + * pattern: '^[a-zA-Z][a-zA-Z0-9_]*$' + * description: Token tiles and filters reference the selected source by, as `$variableName`. + * example: "logs" + * isGlobalRequirement: + * type: boolean + * default: false + * description: | + * Blocks every tile on the dashboard until a value is selected. False + * (the default) blocks only the tiles that reference the variable. + * example: true + * minSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable always requires a selection. + * example: 1 + * maxSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable is always single-select. + * example: 1 + * isBroadcastEnabled: + * type: boolean + * enum: [false] + * default: false + * description: Must be false or omitted. + * example: false + * isVariableEnabled: + * type: boolean + * enum: [true] + * default: true + * description: Must be true if provided, and is true when omitted. + * example: true + * allowedSourceKinds: + * type: array + * minItems: 1 + * items: + * type: string + * enum: [log, trace, session, metric, promql] + * description: | + * Kinds of sources offered. A field can reference the variable if it + * accepts at least one listed kind. A tile whose selected source is a + * kind it cannot use shows an error instead of running. + * example: ["log"] + * connectionId: + * type: string + * description: | + * Optional connection the offered sources are limited to: a + * connection ID, or `$name` of a CONNECTION filter on the dashboard. + * example: "$conn" + * + * ConnectionFilterInput: + * type: object + * description: | + * A variable whose single, required value is a connection. Raw SQL tiles + * reference it as `$variableName` in their connectionId, and data source + * variables and SQL query filters in theirs. Tiles that use it do not load + * until a connection is selected, and cannot have alerts. + * required: + * - type + * - name + * properties: + * type: + * type: string + * enum: [CONNECTION] + * description: Filter type discriminator. Must be "CONNECTION". + * example: "CONNECTION" + * name: + * type: string + * minLength: 1 + * description: Display name of the variable's dropdown + * example: "Connection" + * variableName: + * type: string + * maxLength: 64 + * pattern: '^[a-zA-Z][a-zA-Z0-9_]*$' + * description: Token raw SQL tiles reference the selected connection by, as `$variableName`. + * example: "conn" + * isGlobalRequirement: + * type: boolean + * default: false + * description: | + * Blocks every tile on the dashboard until a value is selected. False + * (the default) blocks only the tiles that reference the variable. + * example: true + * minSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable always requires a selection. + * example: 1 + * maxSelections: + * type: integer + * enum: [1] + * default: 1 + * description: Must be 1 if provided. The variable is always single-select. + * example: 1 + * isBroadcastEnabled: + * type: boolean + * enum: [false] + * default: false + * description: Must be false or omitted. + * example: false + * isVariableEnabled: + * type: boolean + * enum: [true] + * default: true + * description: Must be true if provided, and is true when omitted. + * example: true * * QueryExpressionFilterInput: * type: object @@ -2458,7 +2601,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "environment" * sourceId: * type: string - * description: Source ID this dashboard filter key applies to + * description: Source ID this dashboard filter key applies to, or `$name` of a DATA_SOURCE filter on the dashboard * example: "65f5e4a3b9e77c001a111111" * sourceMetricType: * type: string @@ -2762,7 +2905,9 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * example: "Environment" * connectionId: * type: string - * description: ID of the ClickHouse connection the query runs on. + * description: | + * ClickHouse connection the query runs on: a connection ID, or + * `$name` of a CONNECTION filter on the dashboard. * example: "65f5e4a3b9e77c001a567890" * sqlTemplate: * type: string @@ -2854,7 +2999,7 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * minItems: 1 * items: * type: string - * description: IDs of the sources whose keys and values the filter suggests, all of sourceType. + * description: IDs of the sources whose keys and values the filter suggests, all of sourceType, or `$name` of data source variables. * example: ["65f5e4a3b9e77c001a111111"] * where: * type: string @@ -2874,8 +3019,8 @@ const EXTERNAL_DASHBOARD_PROJECTION = { * type: string * description: | * IDs of the sources whose tiles the conditions apply to, all of - * sourceType. Omit or send an empty array to apply to the tiles of - * the filter's sources. + * sourceType, or `$name` of data source variables. Omit or send an + * empty array to apply to the tiles of the filter's sources. * example: ["65f5e4a3b9e77c001a111111"] * isBroadcastEnabled: * type: boolean diff --git a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts index 9ab380298..200f6f26b 100644 --- a/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts +++ b/packages/api/src/routers/external-api/v2/utils/__tests__/dashboards.test.ts @@ -8,6 +8,7 @@ import { MetricsDataType, PromqlReducer, PromqlSavedChartConfig, + SourceKind, } from '@hyperdx/common-utils/dist/types'; import mongoose from 'mongoose'; import { z } from 'zod'; @@ -539,6 +540,30 @@ describe('convertToExternalDashboard orphan-ref heal', () => { expect(hidden.savedFilterValues).toEqual([adhocValue]); }); + it('keeps data source variables that offer promql sources with hidePromql', () => { + const doc = makeDoc({ + filters: [ + { + id: 'mixed', + type: 'DATA_SOURCE', + name: 'mixed', + variableName: 'mixed', + allowedSourceKinds: [SourceKind.Metric, SourceKind.Promql], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + }); + + expect( + convertToExternalDashboard(doc, { hidePromql: true }).filters?.map( + f => f.id, + ), + ).toEqual(['mixed']); + }); + // seriesLimit is three-state (matching the internal schema): omitted = // default cap, 0 = unlimited, positive N = top-N. All three must survive a // GET->PUT round-trip: 0 and N pass through, null maps to absent (the diff --git a/packages/api/src/routers/external-api/v2/utils/dashboards.ts b/packages/api/src/routers/external-api/v2/utils/dashboards.ts index 0590b30fc..fbde606d5 100644 --- a/packages/api/src/routers/external-api/v2/utils/dashboards.ts +++ b/packages/api/src/routers/external-api/v2/utils/dashboards.ts @@ -6,6 +6,8 @@ import { TIME_SERIES_DISPLAY_TYPE_BY_NAME, } from '@hyperdx/common-utils/dist/core/utils'; import { + collectRefinementIssues, + getVariableReferenceError, validateDashboardContainersStructure, validateDashboardFilterFieldGating, validateDashboardFilterModes, @@ -24,6 +26,10 @@ import { isPromqlSavedChartConfig, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { + getSourceVariableDeclarations, + parseVariableReference, +} from '@hyperdx/common-utils/dist/referenceVariables'; import { AggregateFunctionSchema, BuilderSavedChartConfig, @@ -1327,7 +1333,12 @@ function getMissingSources( const existingSourceIds = new Set( sources.map(source => source._id.toString()), ); - return [...sourceIds].filter(sourceId => !existingSourceIds.has(sourceId)); + // Variable references are checked by validateDashboardVariableReferences + return [...sourceIds].filter( + sourceId => + parseVariableReference(sourceId) == null && + !existingSourceIds.has(sourceId), + ); } /** @@ -1585,16 +1596,18 @@ async function getMissingConnections( filters: (ExternalDashboardFilter | ExternalDashboardFilterWithId)[] = [], ): Promise { const connectionIds = new Set(); + // Variable references are checked by validateDashboardVariableReferences + const addConnectionId = (id: string | undefined) => { + if (id && parseVariableReference(id) == null) connectionIds.add(id); + }; for (const tile of tiles) { if (isConfigTile(tile) && isRawSqlExternalTileConfig(tile.config)) { - connectionIds.add(tile.config.connectionId); + addConnectionId(tile.config.connectionId); } } for (const filter of filters) { - if ('connectionId' in filter) { - connectionIds.add(filter.connectionId); - } + if ('connectionId' in filter) addConnectionId(filter.connectionId); } if (connectionIds.size === 0) return []; @@ -1697,8 +1710,26 @@ export function convertExternalFiltersToInternal( function getSourceConnectionMismatches( sources: SourceForValidation[], tiles: ExternalDashboardTileWithId[], + filters: DashboardFilter[], + existingTiles: DashboardDocument['tiles'] = [], ): string[] { + const existingConfigById = new Map( + existingTiles.map(tile => [tile.id, tile.config]), + ); const sourceById = new Map(sources.map(s => [s._id.toString(), s])); + const variableConnectionByName = new Map( + getSourceVariableDeclarations(filters).map(({ name, connection }) => [ + name, + connection, + ]), + ); + // A source variable's sources are on its declared connection, if any + const getSourceConnection = (sourceId: string) => { + const name = parseVariableReference(sourceId); + return name == null + ? sourceById.get(sourceId)?.connection.toString() + : variableConnectionByName.get(name); + }; const mismatched: string[] = []; for (const tile of tiles) { @@ -1707,9 +1738,30 @@ function getSourceConnectionMismatches( isRawSqlExternalTileConfig(tile.config) && tile.config.sourceId ) { - const source = sourceById.get(tile.config.sourceId); - if (source && source.connection.toString() !== tile.config.connectionId) { - mismatched.push(tile.config.sourceId); + const { connectionId, sourceId } = tile.config; + // Like other variable references, one the update leaves as it was + // isn't checked again; the dashboard shows the mismatch instead + const existingConfig = tile.id + ? existingConfigById.get(tile.id) + : undefined; + if ( + parseVariableReference(sourceId) != null && + existingConfig != null && + Reflect.get(existingConfig, 'source') === sourceId && + Reflect.get(existingConfig, 'connection') === connectionId + ) { + continue; + } + const sourceConnection = getSourceConnection(sourceId); + // A connection reference is only known once selected, so compare two + // IDs, or two references, but not one of each + if ( + sourceConnection != null && + (parseVariableReference(sourceConnection) == null) === + (parseVariableReference(connectionId) == null) && + sourceConnection !== connectionId + ) { + mismatched.push(sourceId); } } } @@ -1724,9 +1776,16 @@ export type TileValidationContext = { tiles: ExternalDashboardTileWithId[]; /** Filters to check for missing source IDs (create/full-update paths). */ filters?: (ExternalDashboardFilter | ExternalDashboardFilterWithId)[]; - /** Existing internal tiles for scoping heatmap change detection (update paths). */ + /** + * Existing internal tiles for scoping heatmap change detection and the + * variable reference check (update paths). + */ existingTiles?: DashboardDocument['tiles']; - /** Existing filters, whose source references aren't re-checked (update paths). */ + /** + * Existing internal filters (update paths). Their source references aren't + * re-checked, and tile variable references are checked against them when + * the request carries no `filters`. + */ existingFilters?: DashboardFilter[]; /** Container set to validate tile containerId/tabId refs against. */ containers: DashboardContainer[]; @@ -1753,6 +1812,26 @@ export async function validateDashboardTiles( return tileRefIssues.join('; '); } + // Stored IDs are kept so that the references an update leaves as they were + // can be told apart from the ones it adds, which are the only ones checked + const referenceFilters = filters + ? convertExternalFiltersToInternal( + filters, + new Set(existingFilters?.map(filter => filter.id)), + ) + : (existingFilters ?? []); + const variableReferenceError = getVariableReferenceError( + convertExternalTilesToInternal( + tiles, + new Set(existingTiles?.map(tile => tile.id)), + ), + referenceFilters, + existingTiles && { tiles: existingTiles, filters: existingFilters }, + ); + if (variableReferenceError) { + return variableReferenceError; + } + // Fetch sources/connections/onClick targets in parallel. const [ sources, @@ -1777,6 +1856,8 @@ export async function validateDashboardTiles( const sourceConnectionMismatches = getSourceConnectionMismatches( sources, tiles, + referenceFilters, + existingTiles, ); if (sourceConnectionMismatches.length > 0) { return `The following source IDs do not match the specified connections: ${sourceConnectionMismatches.join(', ')}`; @@ -1816,10 +1897,10 @@ export async function validateDashboardTiles( // PromQL tiles query through their source's connection and TimeSeries // table, which only a PromQL source carries. const nonPromqlTileSourceIds = getInvalidSourceIds( - getChangedPromqlTileSourceIds(tiles, existingTiles).map(id => ({ - id, - kinds: [SourceKind.Promql], - })), + getChangedPromqlTileSourceIds(tiles, existingTiles) + // A reference's kinds are checked by validateDashboardVariableReferences + .filter(id => parseVariableReference(id) == null) + .map(id => ({ id, kinds: [SourceKind.Promql] })), sources, ); if (nonPromqlTileSourceIds.length > 0) { @@ -1836,7 +1917,7 @@ export async function validateDashboardTiles( translateExternalFilterToFilter({ id: '', ...filter }), ), existingFilters, - ), + ).filter(ref => parseVariableReference(ref.id) == null), sources, ); if (filterSourceError != null) return filterSourceError; @@ -1951,15 +2032,13 @@ export function collectTileContainerRefIssues( containers: DashboardContainer[], tiles: ExternalDashboardTileWithId[], ): string[] { - const schema = z.object({}).superRefine((_, ctx) => { - const containerById = new Map( - containers.map(c => [c.id, c]), - ); - validateDashboardTileContainerRefs(containerById, tiles, ctx); - }); - const result = schema.safeParse({}); - if (result.success) return []; - return result.error.issues.map(issue => { + const containerById = new Map( + containers.map(c => [c.id, c]), + ); + const issues = collectRefinementIssues(ctx => + validateDashboardTileContainerRefs(containerById, tiles, ctx), + ); + return issues.map(issue => { const path = issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''; return `${path}${issue.message}`; }); diff --git a/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts b/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts index 3e1759481..c91e79b5b 100644 --- a/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts +++ b/packages/api/src/tasks/provisionDashboards/__tests__/provisionDashboards.int.test.ts @@ -143,6 +143,41 @@ describe('provisionDashboards', () => { // rejects the legacy enum and `readDashboardFiles` skips the file // outright, so a provisioned dashboard authored against #2265 // wouldn't ship at all. + it('parses a tile that references a declared data source variable', () => { + fs.writeFileSync( + path.join(tmpDir, 'source-variable.json'), + JSON.stringify({ + name: 'Source Variable', + tiles: [makeTile({ sourceId: '$logs' })], + filters: [ + { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: ['log'], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + }), + ); + expect(readDashboardFiles(tmpDir)).toHaveLength(1); + }); + + it('skips a tile that references an undeclared data source variable', () => { + fs.writeFileSync( + path.join(tmpDir, 'unknown-variable.json'), + JSON.stringify({ + name: 'Unknown Variable', + tiles: [makeTile({ sourceId: '$logs' })], + }), + ); + expect(readDashboardFiles(tmpDir)).toEqual([]); + }); + it('migrates legacy chart-N tile colors before schema validation', () => { const tile = makeTile(); (tile.config as any).color = 'chart-1'; diff --git a/packages/api/src/tasks/provisionDashboards/index.ts b/packages/api/src/tasks/provisionDashboards/index.ts index cf10427c7..4199d9618 100644 --- a/packages/api/src/tasks/provisionDashboards/index.ts +++ b/packages/api/src/tasks/provisionDashboards/index.ts @@ -1,4 +1,7 @@ -import { validateDashboardFilterOptionUniqueness } from '@hyperdx/common-utils/dist/dashboardValidation'; +import { + validateDashboardFilterOptionUniqueness, + validateDashboardVariableReferences, +} from '@hyperdx/common-utils/dist/dashboardValidation'; import { DashboardWithoutId, DashboardWithoutIdSchema, @@ -30,8 +33,10 @@ function migrateLegacyDashboardTileColorsRaw(raw: unknown): unknown { } const provisionedDashboardSchema = DashboardWithoutIdSchema.superRefine( - (data, ctx) => - validateDashboardFilterOptionUniqueness(data.filters ?? [], ctx), + (data, ctx) => { + validateDashboardFilterOptionUniqueness(data.filters ?? [], ctx); + validateDashboardVariableReferences(data.tiles, data.filters ?? [], ctx); + }, ); export function readDashboardFiles(dir: string): DashboardWithoutId[] { diff --git a/packages/api/src/utils/externalApi.ts b/packages/api/src/utils/externalApi.ts index a626c5e49..164e59d7f 100644 --- a/packages/api/src/utils/externalApi.ts +++ b/packages/api/src/utils/externalApi.ts @@ -269,6 +269,15 @@ export function translateFilterToExternalFilter( connectionId: filter.connection.toString(), }; + case 'DATA_SOURCE': + return { + ...omit(filter, 'connection'), + ...(filter.connection ? { connectionId: filter.connection } : {}), + }; + + case 'CONNECTION': + return filter; + case 'QUERY_EXPRESSION': { // Ignore variableName and appliesToSourceIds if the filter is not in a mode that uses them const ignoredKeys = [ @@ -310,6 +319,15 @@ export function translateExternalFilterToFilter( case 'QUERY_EXPRESSION': return { ...omit(filter, 'sourceId'), source: filter.sourceId }; + case 'DATA_SOURCE': + return { + ...omit(filter, 'connectionId'), + ...(filter.connectionId ? { connection: filter.connectionId } : {}), + }; + + case 'CONNECTION': + return filter; + default: filter satisfies never; return filter; diff --git a/packages/api/src/utils/zod.ts b/packages/api/src/utils/zod.ts index 05cd5c23d..87df22e50 100644 --- a/packages/api/src/utils/zod.ts +++ b/packages/api/src/utils/zod.ts @@ -1,4 +1,5 @@ import { validateChartConfigFormulas } from '@hyperdx/common-utils/dist/dashboardValidation'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { addDuplicateTileIdIssues, AdhocDashboardFilterSchema, @@ -12,8 +13,10 @@ import { AlertThresholdType, BackgroundChartSchema, ChartPaletteTokenSchema, + ConnectionDashboardFilterSchema, DASHBOARD_CONTAINER_ID_MAX, DASHBOARD_MAX_TILES, + DataSourceDashboardFilterSchema, HeatmapScaleTypeSchema, LineInterpolationSchema, MAX_LEGEND_TEMPLATE_LENGTH, @@ -54,6 +57,17 @@ export const objectIdSchema = z.string().refine(val => { return Types.ObjectId.isValid(val); }, 'Invalid ObjectId'); +/** + * A source or connection field: an ObjectId, or a `$name` reference to the + * dashboard's data source or connection variable of that name. + */ +export const objectIdOrVariableReferenceSchema = z + .string() + .refine( + val => Types.ObjectId.isValid(val) || parseVariableReference(val) != null, + 'Invalid ObjectId or $variable reference', + ); + /** * A repeatable query param. Express's parser yields a bare string for a single * occurrence and an array for several, and `?p[]=x` lands on the same key as @@ -175,7 +189,7 @@ export { tagsSchema }; const externalQueryExpressionFilterShape = QueryExpressionDashboardFilterSchema.omit({ source: true }).extend({ - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, }); // A static filter's mode flags each accept exactly one value, so callers may @@ -188,7 +202,7 @@ const externalStaticListFilterShape = StaticListDashboardFilterSchema.extend({ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({ source: true, }).extend({ - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, isBroadcastEnabled: z.literal(false).default(false), isVariableEnabled: z.literal(true).default(true), }); @@ -197,19 +211,39 @@ const externalPromqlLabelFilterShape = PromqlLabelDashboardFilterSchema.omit({ const externalSqlQueryFilterShape = SqlQueryDashboardFilterSchema.omit({ connection: true, }).extend({ - connectionId: objectIdSchema, + connectionId: objectIdOrVariableReferenceSchema, isBroadcastEnabled: z.literal(false).default(false), isVariableEnabled: z.literal(true).default(true), }); // Field names match the stored filter, so it needs no translation. const externalAdhocFilterShape = AdhocDashboardFilterSchema.extend({ - sources: z.array(objectIdSchema).min(1), - appliesToSourceIds: z.array(objectIdSchema).optional(), + sources: z.array(objectIdOrVariableReferenceSchema).min(1), + appliesToSourceIds: z.array(objectIdOrVariableReferenceSchema).optional(), isBroadcastEnabled: z.literal(true).default(true), isVariableEnabled: z.literal(true).default(true), }); +// Reference variables are always single-select and required, so these +// fields, like the mode flags, accept one value each and may be omitted. +const referenceVariableFixedFields = { + minSelections: z.literal(1).default(1), + maxSelections: z.literal(1).default(1), + isBroadcastEnabled: z.literal(false).default(false), + isVariableEnabled: z.literal(true).default(true), +}; + +const externalDataSourceFilterShape = DataSourceDashboardFilterSchema.omit({ + connection: true, +}).extend({ + connectionId: objectIdOrVariableReferenceSchema.optional(), + ...referenceVariableFixedFields, +}); + +const externalConnectionFilterShape = ConnectionDashboardFilterSchema.extend( + referenceVariableFixedFields, +); + export const externalDashboardFilterSchemaWithId = z.discriminatedUnion( 'type', [ @@ -218,6 +252,8 @@ export const externalDashboardFilterSchemaWithId = z.discriminatedUnion( externalPromqlLabelFilterShape.strict(), externalSqlQueryFilterShape.strict(), externalAdhocFilterShape.strict(), + externalDataSourceFilterShape.strict(), + externalConnectionFilterShape.strict(), ], ); @@ -236,6 +272,8 @@ export const externalDashboardFilterSchema = z.discriminatedUnion('type', [ externalPromqlLabelFilterShape.omit({ id: true }).strict(), externalSqlQueryFilterShape.omit({ id: true }).strict(), externalAdhocFilterShape.omit({ id: true }).strict(), + externalDataSourceFilterShape.omit({ id: true }).strict(), + externalConnectionFilterShape.omit({ id: true }).strict(), ]); export type ExternalDashboardFilter = z.infer< @@ -356,9 +394,9 @@ export type ExternalDashboardSelectItem = z.infer< const externalDashboardRawSqlChartConfigBaseSchema = z.object({ configType: z.literal('sql'), - connectionId: objectIdSchema, + connectionId: objectIdOrVariableReferenceSchema, sqlTemplate: z.string().max(100000), - sourceId: objectIdSchema.optional(), + sourceId: objectIdOrVariableReferenceSchema.optional(), numberFormat: NumberFormatSchema.optional(), }); @@ -381,7 +419,7 @@ const externalFormulasSchema = z.array(MetricFormulaSchema).max(10).optional(); const externalShowOperandSeriesSchema = z.boolean().optional(); const externalDashboardTimeChartConfigSchema = z.object({ - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).min(1).max(20), groupBy: z.string().max(10000).optional(), asRatio: z.boolean().optional(), @@ -452,7 +490,7 @@ const externalDashboardStackedLineRawSqlChartConfigSchema = const externalDashboardTableChartConfigSchema = z.object({ displayType: z.literal('table'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).min(1).max(20), groupBy: z.string().max(10000).optional(), having: z.string().max(10000).optional(), @@ -492,7 +530,7 @@ const externalDashboardCategoricalBarRawSqlChartConfigSchema = const externalDashboardNumberChartConfigSchema = z.object({ displayType: z.literal('number'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, // Exactly one select item unless `formulas` is set: a formula number tile // displays the (single) formula value and its select entries are the // formula's operands (e.g. A / (A + B)). The one-item rule for @@ -532,7 +570,7 @@ const externalDashboardNumberChartConfigSchema = z.object({ const externalDashboardPieChartConfigSchema = z.object({ displayType: z.literal('pie'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).length(1), groupBy: z.string().max(10000).optional(), orderBy: z.string().max(10000).optional(), @@ -543,7 +581,7 @@ const externalDashboardPieChartConfigSchema = z.object({ const externalDashboardCategoricalBarChartConfigSchema = z.object({ displayType: z.literal('bar'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).length(1), groupBy: z.string().max(10000).optional(), orderBy: z.string().max(10000).optional(), @@ -580,7 +618,7 @@ export type ExternalDashboardHeatmapSelectItem = z.infer< const externalDashboardHeatmapChartConfigSchema = z.object({ displayType: z.literal('heatmap'), heatmapMode: z.literal('distribution').optional(), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardHeatmapSelectItemSchema).length(1), where: z.string().max(10000).optional().default(''), // `whereLanguageSchema` (an alias for `SearchConditionLanguageSchema`) @@ -594,7 +632,7 @@ const externalDashboardHeatmapChartConfigSchema = z.object({ const externalDashboardHeatmapSeriesChartConfigSchema = z.object({ displayType: z.literal('heatmap'), heatmapMode: z.literal('series'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.array(externalDashboardSelectItemSchema).length(1), groupBy: z.string().max(10000).optional(), numberFormat: NumberFormatSchema.optional(), @@ -602,7 +640,7 @@ const externalDashboardHeatmapSeriesChartConfigSchema = z.object({ const externalDashboardSearchChartConfigSchema = z.object({ displayType: z.literal('search'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.string().max(10000), where: z.string().max(10000).optional().default(''), whereLanguage: whereLanguageSchema, @@ -626,7 +664,7 @@ const externalDashboardMarkdownChartConfigSchema = z.object({ const externalDashboardEventPatternsChartConfigSchema = z.object({ displayType: z.literal('event_patterns'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, select: z.string().max(10000).optional().default(''), where: z.string().max(10000).optional().default(''), whereLanguage: whereLanguageSchema, @@ -720,7 +758,7 @@ const externalPromqlLegendTemplateSchema = z const externalPromqlChartConfigBaseSchema = z.object({ configType: z.literal('promql'), - sourceId: objectIdSchema, + sourceId: objectIdOrVariableReferenceSchema, // Sets the Prometheus step and `$__interval` of range queries. granularity: z.union([SQLIntervalSchema, z.literal('auto')]).optional(), numberFormat: NumberFormatSchema.optional(), diff --git a/packages/app/src/DBDashboardImportPage.tsx b/packages/app/src/DBDashboardImportPage.tsx index 21c5936fd..749908f98 100644 --- a/packages/app/src/DBDashboardImportPage.tsx +++ b/packages/app/src/DBDashboardImportPage.tsx @@ -16,10 +16,15 @@ import { Controller, useForm, useWatch } from 'react-hook-form'; import { z } from 'zod'; import { zodResolver } from '@hookform/resolvers/zod'; import { convertToDashboardDocument } from '@hyperdx/common-utils/dist/core/utils'; +import { + collectRefinementIssues, + validateDashboardVariableReferences, +} from '@hyperdx/common-utils/dist/dashboardValidation'; import { type DashboardFilterQueryIssue, getAdhocFilterSourceKinds, isAdhocFilter, + isDataSourceFilter, isPrometheusLabelFilter, isQueryExpressionFilter, isSqlQueryFilter, @@ -34,6 +39,7 @@ import { displayTypeRequiresSource, isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { type DashboardFilter, type DashboardTemplate, @@ -75,6 +81,7 @@ import { import SelectControlled from './components/SelectControlled'; import { SourceMultiSelectControlled } from './components/SourceMultiSelect'; +import { useConnectionItems } from './hooks/useConnectionItems'; import api from './api'; import { usePageTitle } from './brand'; import { useConnections } from './connection'; @@ -130,6 +137,32 @@ function CollapsibleMessage({ ); } +/** + * A `$name` that names no variable of the right type in the template. The API + * rejects these too, but only once the mappings are filled in, and local mode + * doesn't check at all. + */ +export function getTemplateVariableReferenceIssues( + template: DashboardTemplate, +): string[] { + return collectRefinementIssues(ctx => + validateDashboardVariableReferences( + template.tiles, + template.filters ?? [], + ctx, + ), + ).map(({ path, message }) => { + const [collection, index] = path; + const owner = + collection === 'tiles' && typeof index === 'number' + ? `Tile "${template.tiles[index]?.config.name ?? index}"` + : collection === 'filters' && typeof index === 'number' + ? `Filter "${template.filters?.[index]?.name ?? index}"` + : path.join('.'); + return `${owner}: ${message}`; + }); +} + function FileSelection({ onComplete, }: { @@ -203,6 +236,24 @@ function FileSelection({ return; } + const referenceIssues = getTemplateVariableReferenceIssues(result.data); + if (referenceIssues.length > 0) { + onComplete(null); + setError({ + message: 'Failed to Import Dashboard', + details: ( + + {referenceIssues.map(issue => ( + + {issue} + + ))} + + ), + }); + return; + } + // The schema only guarantees saved filter values are well-shaped, not that // their condition strings parse. Surface a non-blocking warning so users // who hand-edited or generated the file know a value won't actually filter, @@ -398,11 +449,37 @@ function resolveAppliesToSources( return { ids: slots.filter(Boolean), slots }; } +/** + * A data source or connection variable reference (`$name`) is portable as + * written, so import neither maps it nor asks the user to. + */ +const isVariableRef = (name: string | undefined) => + parseVariableReference(name) != null; + +const sourceVariableRefs = (names: string[] | undefined) => + names?.filter(isVariableRef) ?? []; + +const mappableSourceNames = (names: string[] | undefined) => + names?.filter(name => !isVariableRef(name)); + /** Whether the filter names a single source that import must map. */ const isSourceBackedTemplateFilter = ( filter: DashboardFilter, ): filter is QueryExpressionDashboardFilter | PromqlLabelDashboardFilter => - isQueryExpressionFilter(filter) || isPrometheusLabelFilter(filter); + (isQueryExpressionFilter(filter) || isPrometheusLabelFilter(filter)) && + !isVariableRef(filter.source); + +/** + * Returns the filter if it names a connection import must map: a SQL query + * filter, or a data source variable limited to a connection. + */ +const connectionBackedTemplateFilter = (filter: DashboardFilter | undefined) => + filter && + (isSqlQueryFilter(filter) || isDataSourceFilter(filter)) && + filter.connection && + !isVariableRef(filter.connection) + ? filter + : undefined; /** Returns the filter if it names a source, or `undefined` if it doesn't. */ const sourceBackedTemplateFilter = (filter: DashboardFilter | undefined) => @@ -466,7 +543,7 @@ export function buildMappingFormSchema( connectionMappings: z.array(MappingValueSchema), /** A list of filter source mappings, ordered by input filter index */ filterSourceMappings: z.array(MappingValueSchema).optional(), - /** A list of filter connection mappings, ordered by input filter index. Only applicable for SQL query filters */ + /** Connection mappings of SQL query filters and data source variables, ordered by input filter index */ filterConnectionMappings: z.array(MappingValueSchema).optional(), /** * Per-filter applies-to source mappings. Each entry is an array of mapped @@ -497,6 +574,7 @@ export function buildMappingFormSchema( // meaningful source even when the template names one. if ( config.source && + !isVariableRef(config.source) && displayTypeRequiresSource(config.displayType) && !data.tileSourceMappings[idx] ) { @@ -508,7 +586,11 @@ export function buildMappingFormSchema( } // A raw SQL tile always gets a connection row, and its connection is // not optional — leaving it unpicked used to throw on `connection!.id`. - if (isRawSqlSavedChartConfig(config) && !data.connectionMappings[idx]) { + if ( + isRawSqlSavedChartConfig(config) && + !isVariableRef(config.connection) && + !data.connectionMappings[idx] + ) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['connectionMappings', idx], @@ -524,6 +606,16 @@ export function buildMappingFormSchema( }); input.filters?.forEach((filter, idx) => { + if ( + connectionBackedTemplateFilter(filter) && + !data.filterConnectionMappings?.[idx] + ) { + ctx.addIssue({ + code: z.ZodIssueCode.custom, + path: ['filterConnectionMappings', idx], + message: 'Select a connection for this filter', + }); + } if (isAdhocFilter(filter)) { const kinds = getAdhocFilterSourceKinds(filter.sourceType); const kindMessage = @@ -533,7 +625,10 @@ export function buildMappingFormSchema( const mappedSourceIds = data.filterAdhocSourceMappings?.[idx]?.filter( id => !!id, ); - if (!mappedSourceIds?.length) { + if ( + !mappedSourceIds?.length && + sourceVariableRefs(filter.sources).length === 0 + ) { ctx.addIssue({ code: z.ZodIssueCode.custom, path: ['filterAdhocSourceMappings', idx], @@ -556,17 +651,6 @@ export function buildMappingFormSchema( return; } - if (isSqlQueryFilter(filter)) { - if (!data.filterConnectionMappings?.[idx]) { - ctx.addIssue({ - code: z.ZodIssueCode.custom, - path: ['filterConnectionMappings', idx], - message: 'Select a connection for this filter', - }); - } - return; - } - if (!isSourceBackedTemplateFilter(filter)) return; const mappedSourceId = data.filterSourceMappings?.[idx]; if (!mappedSourceId) { @@ -603,6 +687,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { const router = useRouter(); const { data: sources } = useSources(); const { data: connections } = useConnections(); + const connectionItems = useConnectionItems(); const { data: dashboards } = useDashboards(); const { data: existingTags } = api.useTags(); const [dashboardId] = useQueryState('dashboardId', parseAsString); @@ -646,7 +731,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { const tileSourceMappings = input.tiles.map(tile => { const config = tile.config as SavedChartConfig; - if (!config.source) return ''; + if (!config.source || isVariableRef(config.source)) return ''; const match = sources.find( source => source.name.toLowerCase() === config.source!.toLowerCase(), ); @@ -655,17 +740,19 @@ export function Mapping({ input }: { input: DashboardTemplate }) { const findConnectionIdByName = (name: string) => connections.find(conn => conn.name.toLowerCase() === name.toLowerCase()) - ?.id || ''; + ?.id ?? ''; const connectionMappings = input.tiles.map(tile => { const config = tile.config as SavedChartConfig; - if (!isRawSqlSavedChartConfig(config)) return ''; + if (!isRawSqlSavedChartConfig(config) || isVariableRef(config.connection)) + return ''; return findConnectionIdByName(config.connection); }); - const filterConnectionMappings = input.filters?.map(filter => - isSqlQueryFilter(filter) ? findConnectionIdByName(filter.connection) : '', - ); + const filterConnectionMappings = input.filters?.map(filter => { + const connection = connectionBackedTemplateFilter(filter)?.connection; + return connection ? findConnectionIdByName(connection) : ''; + }); const filterSourceMappings = input.filters?.map(filter => { const sourceName = sourceBackedTemplateFilter(filter)?.source; @@ -724,8 +811,8 @@ export function Mapping({ input }: { input: DashboardTemplate }) { setValue('tileSourceMappings', tileSourceMappings); setValue('connectionMappings', connectionMappings); - setValue('filterSourceMappings', filterSourceMappings); setValue('filterConnectionMappings', filterConnectionMappings); + setValue('filterSourceMappings', filterSourceMappings); multiMappingSlotsRef.current.clear(); filterAppliesToSourceMappings?.forEach((mapping, idx) => { setValue(`filterAppliesToSourceMappings.${idx}`, mapping); @@ -916,8 +1003,8 @@ export function Mapping({ input }: { input: DashboardTemplate }) { sources, ]); - // Propagate connection mapping changes to other RawSQL tiles and SQL query - // filters with the same input connection + // Propagate connection mapping changes to other RawSQL tiles and filters + // with the same input connection useEffect(() => { if (isUpdatingRef.current) return; if (!input.tiles) return; @@ -950,9 +1037,11 @@ export function Mapping({ input }: { input: DashboardTemplate }) { ); if (filterIdx !== -1) { prevFilterConnectionMappingsRef.current = filterConnectionMappings; - const filter = input.filters?.[filterIdx]; - if (filter && isSqlQueryFilter(filter)) { - inputConnectionName = filter.connection; + const connection = connectionBackedTemplateFilter( + input.filters?.[filterIdx], + )?.connection; + if (connection) { + inputConnectionName = connection; connectionId = filterConnectionMappings[filterIdx] ?? ''; } } @@ -977,8 +1066,8 @@ export function Mapping({ input }: { input: DashboardTemplate }) { ?.map((filter, index) => ({ filter, index })) .filter( ({ filter }) => - isSqlQueryFilter(filter) && - filter.connection === inputConnectionName, + connectionBackedTemplateFilter(filter)?.connection === + inputConnectionName, ) .map(({ index }) => `filterConnectionMappings.${index}` as const) ?? []; @@ -1092,12 +1181,14 @@ export function Mapping({ input }: { input: DashboardTemplate }) { }; if (isRawSqlSavedChartConfig(tile.config)) { - const connection = findConnection(data.connectionMappings[idx]); + const connection = isVariableRef(tile.config.connection) + ? tile.config.connection + : findConnection(data.connectionMappings[idx])!.id; return { ...tile, config: applyOnClick({ ...tile.config, - connection: connection!.id, + connection, ...(source ? { source: source.id } : {}), }), }; @@ -1118,23 +1209,34 @@ export function Mapping({ input }: { input: DashboardTemplate }) { // Zip the source mappings with the input filters const zippedFilters = input.filters?.map((filter, idx) => { - const appliesTo = data.filterAppliesToSourceMappings?.[idx]?.filter( - id => !!id?.length, - ); - const appliesToSourceIds = appliesTo?.length ? appliesTo : undefined; + // Data source variable references carry over unmapped + const appliesTo = [ + ...sourceVariableRefs( + appliesToTemplateFilter(filter)?.appliesToSourceIds, + ), + ...(data.filterAppliesToSourceMappings?.[idx]?.filter( + id => !!id?.length, + ) ?? []), + ]; + const appliesToSourceIds = appliesTo.length ? appliesTo : undefined; if (isAdhocFilter(filter)) { return { ...filter, - sources: - data.filterAdhocSourceMappings?.[idx]?.filter(id => !!id) ?? [], + sources: [ + ...sourceVariableRefs(filter.sources), + ...(data.filterAdhocSourceMappings?.[idx]?.filter(id => !!id) ?? + []), + ], appliesToSourceIds, }; } - if (isSqlQueryFilter(filter)) { - const connection = findConnection( - data.filterConnectionMappings?.[idx], - ); - return { ...filter, connection: connection!.id }; + if (connectionBackedTemplateFilter(filter)) { + return { + ...filter, + // The form schema requires this mapping + connection: findConnection(data.filterConnectionMappings?.[idx])! + .id, + }; } const source = findSource(data.filterSourceMappings?.[idx]); return { @@ -1227,7 +1329,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { return ( {/** Mapping for the tile's source, if one exists (they're optional for raw sql tiles) */} - {tile.config.source && ( + {tile.config.source && !isVariableRef(tile.config.source) && ( {tile.config.name} Data source @@ -1246,7 +1348,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { )} {/** Mapping for the tile's connection, if it's a raw sql tile */} - {isRawSql && ( + {isRawSql && !isVariableRef(config.connection) && ( {tile.config.name} Data connection @@ -1255,10 +1357,7 @@ export function Mapping({ input }: { input: DashboardTemplate }) { ({ - value: conn.id, - label: conn.name, - }))} + data={connectionItems} placeholder="Select a connection" /> @@ -1310,10 +1409,33 @@ export function Mapping({ input }: { input: DashboardTemplate }) { {/** Map filter sources */} {input.filters?.map((filter, i) => { - const appliesToSourceIds = - appliesToTemplateFilter(filter)?.appliesToSourceIds; + const appliesToSourceIds = mappableSourceNames( + appliesToTemplateFilter(filter)?.appliesToSourceIds, + ); + const adhocSourceNames = isAdhocFilter(filter) + ? mappableSourceNames(filter.sources) + : undefined; return ( + {connectionBackedTemplateFilter(filter) && ( + + {filter.name} (Filter) + Data connection + + {connectionBackedTemplateFilter(filter)?.connection} + + + + + + + + )} {isSourceBackedTemplateFilter(filter) && ( {filter.name} (Filter) @@ -1338,29 +1460,11 @@ export function Mapping({ input }: { input: DashboardTemplate }) { )} - {isSqlQueryFilter(filter) && ( - - {filter.name} (Filter) - Data connection - {filter.connection} - - ({ - value: conn.id, - label: conn.name, - }))} - placeholder="Select a connection" - /> - - - )} - {isAdhocFilter(filter) && ( + {isAdhocFilter(filter) && !!adhocSourceNames?.length && ( {filter.name} (Filter) Data sources - {filter.sources.join(', ')} + {adhocSourceNames.join(', ')} ( () => JSON.parse(serializedMissingRequiredFilterNames), @@ -929,16 +962,13 @@ const Tile = ({ return url && addTimeZone(url); }, [dateRange, queriedConfig, source, addTimeZone]); + // An alert must query one fixed source and connection + const supportsAlerts = + !usesReferenceVariable && savedChartConfigSupportsAlerts(chart.config); + const hoverToolbar = useMemo(() => { if (readOnly) return null; - const isRawSql = isRawSqlSavedChartConfig(chart.config); - const isPromQL = isPromqlSavedChartConfig(chart.config); - const displayTypeSupportsAlerts = isRawSql - ? displayTypeSupportsRawSqlAlerts(chart.config.displayType) - : isPromQL - ? displayTypeSupportsPromQLAlerts(chart.config.displayType) - : displayTypeSupportsBuilderAlerts(chart.config.displayType); const canMoveToGroup = onMoveToGroup && moveTargets && moveTargets.length > 0; return ( @@ -968,7 +998,7 @@ const Tile = ({ )} - {displayTypeSupportsAlerts && + {supportsAlerts && (alert ? ( // Existing alert: bell with a colored status dot indicator. { if (readOnly) return null; - const isRawSql = isRawSqlSavedChartConfig(chart.config); - const isPromQL = isPromqlSavedChartConfig(chart.config); - const showAlerts = isRawSql - ? displayTypeSupportsRawSqlAlerts(chart.config.displayType) - : isPromQL - ? displayTypeSupportsPromQLAlerts(chart.config.displayType) - : displayTypeSupportsBuilderAlerts(chart.config.displayType); const canMoveToGroup = onMoveToGroup && moveTargets && moveTargets.length > 0; return ( @@ -1113,7 +1136,7 @@ const Tile = ({ Replay search )} - {showAlerts && ( + {supportsAlerts && ( <> - {`Missing required filters: ${missingRequiredFilterNames.join( + {`Missing required filters or variables: ${missingRequiredFilterNames.join( ', ', )}. Select a value for each to load this tile.`} @@ -1269,6 +1292,20 @@ const Tile = ({ The data source for this tile is not set. Edit the tile to select a data source. + ) : isSourceOnOtherConnection ? ( + + The selected data source is on a different connection than this + tile's query. Select a source on the same connection. + + ) : isSourceKindUnsupported ? ( + + The selected data source can't be used with this chart type. + Select a different source. + ) : ( <> {effectiveQueriedConfig && @@ -1501,6 +1538,8 @@ const Tile = ({ filterWarning, isSourceMissing, isSourceUnset, + isSourceOnOtherConnection, + isSourceKindUnsupported, isBlockedByRequiredFilters, missingRequiredFilterNames, hasBeenVisible, @@ -1900,28 +1939,6 @@ function DBDashboardPage({ const { data: allDashboards } = useDashboards(); const [highlightedTileId] = useQueryState('highlightedTileId'); - const tableConnections = useMemo(() => { - if (!dashboard) return []; - const tc: TableConnection[] = []; - - for (const { config } of dashboard.tiles) { - if (!isBuilderSavedChartConfig(config)) continue; - const source = sources?.find(v => v.id === config.source); - if (!source || source.disabled) continue; - // TODO: will need to update this when we allow for multiple metrics per chart - const firstSelect = config.select[0]; - const metricType = - typeof firstSelect !== 'string' ? firstSelect?.metricType : undefined; - const tableName = getMetricTableName(source, metricType); - if (!tableName) continue; - tc.push({ - ...tcFromSource(source), - tableName, - }); - } - - return tc; - }, [dashboard, sources]); const [granularity, setGranularity] = useQueryState( 'granularity', @@ -1966,8 +1983,61 @@ function DBDashboardPage({ ignoredVariableNames, getFilterQueriesForSource, variables, + referenceVariableValues, + resolvedFilters, + unresolvedReferenceVariablesByFilterId, + incompatibleReferenceVariablesByFilterId, unsatisfiedRequiredFilters, - } = useDashboardFilters(filters); + } = useDashboardFilters(filters, { sources }); + // Tiles as they query, by ID: source and connection variable references + // replaced by the selections. Edits and saves read `dashboard.tiles`, so the + // stored references survive. + const resolvedTiles = useMemo( + () => + new Map( + (dashboard?.tiles ?? []).map(tile => { + const config = resolveConfigReferences( + tile.config, + referenceVariableValues, + ); + return [tile.id, config === tile.config ? tile : { ...tile, config }]; + }), + ), + [dashboard?.tiles, referenceVariableValues], + ); + // Kept apart from `resolvedTiles` so a tile's list only changes with its config + const referenceVariableNamesByTileId = useMemo( + () => + new Map( + (dashboard?.tiles ?? []).map(tile => [ + tile.id, + getConfigReferenceVariables(tile.config), + ]), + ), + [dashboard?.tiles], + ); + + const tableConnections = useMemo(() => { + const tc: TableConnection[] = []; + + for (const { config } of resolvedTiles.values()) { + if (!isBuilderSavedChartConfig(config)) continue; + const source = sources?.find(v => v.id === config.source); + if (!source || source.disabled) continue; + // TODO: will need to update this when we allow for multiple metrics per chart + const firstSelect = config.select[0]; + const metricType = + typeof firstSelect !== 'string' ? firstSelect?.metricType : undefined; + const tableName = getMetricTableName(source, metricType); + if (!tableName) continue; + tc.push({ + ...tcFromSource(source), + tableName, + }); + } + + return tc; + }, [resolvedTiles, sources]); const dashboardReady = !!dashboard?.id && @@ -2406,10 +2476,10 @@ function DBDashboardPage({ // The filter bar is hidden in kiosk mode, so a click would add conditions // the viewer can't see or remove. if (isKioskMode) return handlers; - for (const tile of dashboard?.tiles ?? []) { + for (const tile of resolvedTiles.values()) { const sourceId = 'source' in tile.config ? tile.config.source : undefined; const targetIds = getAdhocFilterTargetsForTile( - filters, + resolvedFilters, tile.config, sourceId, ).map(filter => filter.id); @@ -2420,19 +2490,23 @@ function DBDashboardPage({ } } return handlers; - }, [isKioskMode, dashboard?.tiles, filters, applyAdhocAction]); + }, [isKioskMode, resolvedTiles, resolvedFilters, applyAdhocAction]); const renderTileComponent = useCallback( (chart: Tile) => { + const resolvedChart = resolvedTiles.get(chart.id) ?? chart; // Resolve the tile's source ID so per-source-scoped filters can be // narrowed to only the tiles they target. Builder and RawSQL configs // both carry a `source` field; markdown / other configs don't. const tileSourceId = - 'source' in chart.config ? chart.config.source : undefined; + 'source' in resolvedChart.config + ? resolvedChart.config.source + : undefined; return ( setEditedTile(chart)} readOnly={isKioskMode} @@ -2459,7 +2533,14 @@ function DBDashboardPage({ c => c.id === chart.id, ); if (chartIndex === -1) return; - draft.tiles[chartIndex] = newChart; + // Keep the source as stored, not as resolved for display + draft.tiles[chartIndex] = { + ...newChart, + config: restoreConfigReferences( + newChart.config, + chart.config, + ), + }; }), ); } @@ -2532,6 +2613,8 @@ function DBDashboardPage({ ); }, [ + resolvedTiles, + referenceVariableNamesByTileId, dashboard, searchedTimeRange, isRefreshEnabled, @@ -3224,7 +3307,10 @@ function DBDashboardPage({ // `` return shallow and prevents the tile-grid tree below // from being wrapped in an extra indentation level. const dashboardBody = ( - <> + {title} @@ -3324,7 +3410,7 @@ function DBDashboardPage({ )} {!isKioskMode && ( )} {/* Selection indicator */} @@ -3512,7 +3605,7 @@ function DBDashboardPage({ variables={variables} /> )} - + ); return ( diff --git a/packages/app/src/DashboardFilters.tsx b/packages/app/src/DashboardFilters.tsx index eb7846246..ff17338cf 100644 --- a/packages/app/src/DashboardFilters.tsx +++ b/packages/app/src/DashboardFilters.tsx @@ -5,12 +5,15 @@ import { getFilterVariableName, getPendingFilterValuesVariables, isAdhocFilter, + isDataSourceFilter, isFilterGlobalRequirement, isFilterReferenceableVariable, isFilterRequired, isQueryExpressionFilter, + isReferenceVariableFilter, isStaticListFilter, } from '@hyperdx/common-utils/dist/filters'; +import { ReferenceVariableValues } from '@hyperdx/common-utils/dist/referenceVariables'; import { AdhocFilterCondition, ChartVariable, @@ -25,9 +28,14 @@ import { DashboardFilterLabel, FilterCaution, FilterEffect, + getIncompatibleVariablesTooltip, getPendingVariablesTooltip, } from './components/DashboardFilterLabel'; import { FilterLinkToggle } from './components/FilterLinkToggle'; +import { + ConnectionDashboardFilter, + DataSourceDashboardFilter, +} from './components/ReferenceVariableDashboardFilter'; import { VirtualMultiSelect } from './components/VirtualMultiSelect/VirtualMultiSelect'; import { useDashboardFilterValues } from './hooks/useDashboardFilterValues'; @@ -173,6 +181,16 @@ interface DashboardFilterProps { variables?: ChartVariable[]; /** Required filters with nothing selected, which can block ad hoc filters. */ unsatisfiedRequiredFilters?: DashboardFilter[]; + /** The selected ID of each data source and connection variable, by name. */ + referenceVariableValues?: ReferenceVariableValues; + /** + * The reference variables each filter's fields reference that leave it + * nothing to query, by filter ID. `filters` are otherwise expected with + * their references resolved. + */ + unresolvedReferenceVariablesByFilterId?: ReadonlyMap; + /** The subset of those selecting a source the filter can't use. */ + incompatibleReferenceVariablesByFilterId?: ReadonlyMap; } const DashboardFilters = ({ @@ -184,6 +202,9 @@ const DashboardFilters = ({ onSetAdhocConditions, variables, unsatisfiedRequiredFilters, + referenceVariableValues, + unresolvedReferenceVariablesByFilterId, + incompatibleReferenceVariablesByFilterId, }: DashboardFilterProps) => { // "Link" mode (opt-in, off by default): each dropdown's values are narrowed by // the others' selections. Off by default because contingent value lookups @@ -191,13 +212,22 @@ const DashboardFilters = ({ // on, all of a source's facets are computed in a single groupUniqArrayIf scan. const [linked, setLinked] = useState(false); + // A filter whose data source variable has no selection has nothing to query yet + const queryableFilters = useMemo( + () => + filters.filter( + filter => !unresolvedReferenceVariablesByFilterId?.has(filter.id), + ), + [filters, unresolvedReferenceVariablesByFilterId], + ); + const { data: filterValuesById, erroredFilterIds, filterErrorMessages, isFetching, } = useDashboardFilterValues({ - filters, + filters: queryableFilters, dateRange, variables, // Only narrow by sibling selections when linked. @@ -214,6 +244,39 @@ const DashboardFilters = ({ return ( {filters.map(filter => { + const incompatibleVariables = + incompatibleReferenceVariablesByFilterId?.get(filter.id) ?? []; + const unresolvedVariables = + unresolvedReferenceVariablesByFilterId?.get(filter.id) ?? []; + // Variables with no selection yet, as opposed to an unusable one + const unselectedVariables = unresolvedVariables.filter( + name => !incompatibleVariables.includes(name), + ); + if (isReferenceVariableFilter(filter)) { + const referenceProps = { + value: referenceVariableValues?.get( + getFilterVariableName(filter) ?? '', + ), + onChange: (value: string | undefined) => + onSetFilterValue(filter.id, value ? [value] : []), + effect: getFilterEffect(filter), + requiredTooltip: getRequiredFilterTooltip(filter), + }; + return isDataSourceFilter(filter) ? ( + + ) : ( + + ); + } if (isAdhocFilter(filter)) { return ( ); } @@ -238,21 +303,31 @@ const DashboardFilters = ({ // Fall back to the hook-level fetching state only until this filter's // query has produced an entry; once it has (even with empty values), // honor its own loading flag. - const isLoadingValues = queriedFilterValues - ? queriedFilterValues.isLoading - : isFetching; + const isLoadingValues = + unresolvedVariables.length === 0 && + (queriedFilterValues ? queriedFilterValues.isLoading : isFetching); // Only a queried dropdown has a values query that can await a - // variable's selection. - const pendingVariables = isQueryExpressionFilter(filter) - ? getPendingFilterValuesVariables(filter, variables) - : undefined; + // variable's selection, besides any data source variable it reads from. + const pendingVariables = [ + ...unselectedVariables, + ...(isQueryExpressionFilter(filter) + ? getPendingFilterValuesVariables(filter, variables) + : []), + ]; return ( 0 || + (erroredFilterIds?.has(filter.id) ?? false) + } + errorMessage={ + incompatibleVariables.length > 0 + ? getIncompatibleVariablesTooltip(incompatibleVariables) + : filterErrorMessages?.get(filter.id) + } pendingVariables={pendingVariables} onChange={values => onSetFilterValue(filter.id, values)} values={queriedFilterValues?.values} diff --git a/packages/app/src/__tests__/DBDashboardImportPage.test.tsx b/packages/app/src/__tests__/DBDashboardImportPage.test.tsx index 2bfec3b19..81502709f 100644 --- a/packages/app/src/__tests__/DBDashboardImportPage.test.tsx +++ b/packages/app/src/__tests__/DBDashboardImportPage.test.tsx @@ -6,7 +6,11 @@ import { } from '@hyperdx/common-utils/dist/types'; import { act, fireEvent, screen, waitFor } from '@testing-library/react'; -import { buildMappingFormSchema, Mapping } from '@/DBDashboardImportPage'; +import { + buildMappingFormSchema, + getTemplateVariableReferenceIssues, + Mapping, +} from '@/DBDashboardImportPage'; // Sources/connections the import maps the template's source *names* onto. The // auto-mapping effect in `Mapping` matches by name (case-insensitive), so a @@ -724,3 +728,150 @@ describe('Dashboard import - ad hoc filter sources', () => { expect(issuesFor(['src-logs'])).toBeUndefined(); }); }); + +describe('Dashboard import - data source variables', () => { + const sourceVariableTemplate = DashboardTemplateSchema.parse({ + version: '0.1.0', + name: 'Source Variables', + tiles: [builderTile('tile-line', 'line', '$logs', 0)], + filters: [ + { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + { + id: 'svc', + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + source: '$logs', + }, + { + id: 'adhoc', + type: 'ADHOC', + name: 'Conditions', + sourceType: 'sql', + sources: ['$logs', 'Traces'], + isBroadcastEnabled: true, + isVariableEnabled: true, + }, + ], + }); + + it('keeps references as written without asking for a mapping', async () => { + renderWithMantine(); + + const finish = await screen.findByRole('button', { + name: /finish import/i, + }); + expect(screen.queryByText('$logs')).not.toBeInTheDocument(); + await act(async () => { + fireEvent.click(finish); + }); + + await waitFor(() => expect(mockMutateAsync).toHaveBeenCalledTimes(1)); + const payload = mockMutateAsync.mock.calls[0][0]; + expect(payload.tiles[0].config.source).toBe('$logs'); + expect(payload.filters[1].source).toBe('$logs'); + expect(payload.filters[2].sources).toEqual(['$logs', 'src-traces']); + }); + + it('accepts references to the variables the template declares', () => { + expect(getTemplateVariableReferenceIssues(sourceVariableTemplate)).toEqual( + [], + ); + }); + + it('reports references to variables the template does not declare', () => { + const template = DashboardTemplateSchema.parse({ + version: '0.1.0', + name: 'Undeclared', + tiles: [builderTile('tile-line', 'line', '$traces', 0)], + filters: [ + { + id: 'svc', + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + source: '$traces', + }, + ], + }); + + expect(getTemplateVariableReferenceIssues(template)).toEqual([ + 'Tile "tile-line": "$traces" does not name a data source variable on this dashboard', + 'Filter "Service": "$traces" does not name a data source variable on this dashboard', + ]); + }); +}); + +describe('Dashboard import - connection variables', () => { + const connectionVariableTemplate = DashboardTemplateSchema.parse({ + version: '0.1.0', + name: 'Connection Variables', + tiles: [ + { + id: 'tile-rawsql', + x: 0, + y: 0, + w: 6, + h: 3, + config: { + name: 'tile-rawsql', + displayType: 'table', + configType: 'sql', + connection: '$conn', + sqlTemplate: 'SELECT 1', + }, + }, + ], + filters: [ + { + id: 'conn', + type: 'CONNECTION', + name: 'Cluster', + variableName: 'conn', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + { + id: 'ds', + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + connection: 'Default', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }, + ], + }); + + it('keeps connection references and maps a data source variable connection', async () => { + renderWithMantine(); + + const finish = await screen.findByRole('button', { + name: /finish import/i, + }); + expect(screen.queryByText('$conn')).not.toBeInTheDocument(); + await act(async () => { + fireEvent.click(finish); + }); + + await waitFor(() => expect(mockMutateAsync).toHaveBeenCalledTimes(1)); + const payload = mockMutateAsync.mock.calls[0][0]; + expect(payload.tiles[0].config.connection).toBe('$conn'); + expect(payload.filters[1].connection).toBe('conn-default'); + }); +}); diff --git a/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx b/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx index 008860ab9..f89d1a71f 100644 --- a/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx +++ b/packages/app/src/components/AdhocDashboardFilter/AdhocDashboardFilter.tsx @@ -30,6 +30,7 @@ import { DashboardFilterLabel, FilterCaution, FilterEffect, + getIncompatibleVariablesTooltip, getPendingVariablesTooltip, } from '@/components/DashboardFilterLabel'; import { FilterPill, getFilterOperatorDisplay } from '@/components/FilterPill'; @@ -53,8 +54,17 @@ type AdhocDashboardFilterProps = { variables?: ChartVariable[]; /** Required filters with nothing selected. */ unsatisfiedRequiredFilters?: DashboardFilter[]; + /** + * Unselected data source variables the filter's sources reference. Until + * they have a selection the filter has no sources to suggest keys from. + */ + unresolvedVariables?: string[]; + /** Those of `unresolvedVariables` selecting a source the filter can't use. */ + incompatibleVariables?: string[]; }; +const NO_VARIABLES: string[] = []; + /** A dashboard filter bar control holding one ad hoc filter's conditions. */ export function AdhocDashboardFilter({ filter, @@ -64,6 +74,8 @@ export function AdhocDashboardFilter({ effect, variables, unsatisfiedRequiredFilters, + unresolvedVariables = NO_VARIABLES, + incompatibleVariables = NO_VARIABLES, }: AdhocDashboardFilterProps) { const [isAdding, setIsAdding] = useState(false); const [isExpanded, setIsExpanded] = useState(false); @@ -103,7 +115,13 @@ export function AdhocDashboardFilter({ ? `This filter depends on: ${blockingFilterNames.join(', ')}` : undefined; const disabledReason = dependsOn ?? suggestionsWhere.error; - const isDisabled = !!disabledReason; + const isDisabled = !!disabledReason || unresolvedVariables.length > 0; + const allPendingVariables = [ + ...unresolvedVariables.filter( + name => !incompatibleVariables.includes(name), + ), + ...pendingVariables, + ]; const toggleAdding = () => { if (isDisabled) return; @@ -136,15 +154,18 @@ export function AdhocDashboardFilter({ testId={`dashboard-filter-blocked-${filter.name}`} /> )} - {!isDisabled && pendingVariables.length > 0 && ( + {!disabledReason && allPendingVariables.length > 0 && ( )} - {suggestionsWhere.error && ( + {(suggestionsWhere.error || incompatibleVariables.length > 0) && ( diff --git a/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx b/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx index 3f767a0e3..467830eeb 100644 --- a/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx +++ b/packages/app/src/components/AdhocDashboardFilter/__tests__/AdhocDashboardFilter.test.tsx @@ -151,6 +151,40 @@ describe('AdhocDashboardFilter', () => { ); }); + it('waits for an unselected data source variable its sources reference', async () => { + const onChange = renderFilter([existing], filter, { + unresolvedVariables: ['ds'], + }); + + expect( + screen.getByTestId('dashboard-filter-pending-variable-Conditions'), + ).toBeInTheDocument(); + expect(addButton()).toHaveAttribute('aria-disabled', 'true'); + await userEvent.click(addButton()); + await userEvent.click(screen.getByTestId('adhoc-condition-pill')); + expect(screen.queryByTestId(`${editorId}-key`)).not.toBeInTheDocument(); + + await userEvent.click( + screen.getByRole('button', { name: 'Remove filter' }), + ); + expect(onChange).toHaveBeenCalledWith([]); + }); + + it("reports a data source variable selecting a source it can't use", () => { + renderFilter([existing], filter, { + unresolvedVariables: ['ds'], + incompatibleVariables: ['ds'], + }); + + expect( + screen.getByTestId('dashboard-filter-error-Conditions'), + ).toBeInTheDocument(); + expect( + screen.queryByTestId('dashboard-filter-pending-variable-Conditions'), + ).not.toBeInTheDocument(); + expect(addButton()).toHaveAttribute('aria-disabled', 'true'); + }); + it('edits a condition from its pill', async () => { const onChange = renderFilter([ existing, diff --git a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx index 838e3ec73..9a7942579 100644 --- a/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/PromqlChartEditor.tsx @@ -21,6 +21,7 @@ import { IconCirclePlus } from '@tabler/icons-react'; import { HeatmapModeControl } from '@/components/DBEditTimeChartForm/HeatmapModeControl'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { usePromqlMetricNames } from '@/hooks/usePromqlMetadata'; import { useSource } from '@/source'; @@ -80,7 +81,7 @@ export default function PromqlChartEditor({ ); }, []); - const sourceId = useWatch({ control, name: 'source' }); + const sourceId = useResolvedReference(useWatch({ control, name: 'source' })); const displayType = useWatch({ control, name: 'displayType' }); const { data: source } = useSource({ id: sourceId }); // The form can still hold a non-PromQL source right after switching a tile @@ -107,6 +108,7 @@ export default function PromqlChartEditor({ name="source" data-testid="source-selector" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables /> {displayType === DisplayType.Heatmap && ( diff --git a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx index ea2304d03..895c1685b 100644 --- a/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx +++ b/packages/app/src/components/ChartEditor/RawSqlChartEditor.tsx @@ -9,6 +9,7 @@ import { validateRawSqlChartConfig, validateRawSqlForAlert, } from '@hyperdx/common-utils/dist/core/utils'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; import { ChartVariable, RawSqlChartConfig, @@ -41,6 +42,7 @@ import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from '@/components/SourceSchemaPreview'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { SQLEditorControlled } from '@/components/SQLEditor/SQLEditor'; import { type SQLCompletion } from '@/components/SQLEditor/utils'; import { IS_LOCAL_MODE } from '@/config'; @@ -80,9 +82,14 @@ export function resolveConnectionSourceSync({ sources: { id: string; connection: string }[] | undefined; }): ConnectionSourceSyncResult { if (!sources) return null; + // A data source variable reference isn't bound to a connection here: the + // filter bar decides what it selects, so it neither moves the connection + // nor is cleared by a connection change. + const isSourceReference = parseVariableReference(source) != null; // When the source changes, sync the connection to match. if (source !== prevSource) { + if (isSourceReference) return null; const sourceConnection = sources.find(s => s.id === source)?.connection; if (sourceConnection && sourceConnection !== connection) { return { field: 'connection', value: sourceConnection }; @@ -105,7 +112,7 @@ export function resolveConnectionSourceSync({ // connection change above was itself triggered by the source. if (connection !== prevConnection && prevConnection !== undefined) { const sourceConnection = sources.find(s => s.id === source)?.connection; - if (source && sourceConnection !== connection) { + if (source && !isSourceReference && sourceConnection !== connection) { return { field: 'source', value: '' }; } } @@ -147,8 +154,12 @@ export default function RawSqlChartEditor({ const { data: sources } = useSources(); const displayType = useWatch({ control, name: 'displayType' }); - const connection = useWatch({ control, name: 'connection' }); - const source = useWatch({ control, name: 'source' }); + // Source and connection variable references autocomplete and expand macros + // as the source and connection they currently select. + const storedConnection = useWatch({ control, name: 'connection' }); + const connection = useResolvedReference(storedConnection); + const storedSource = useWatch({ control, name: 'source' }); + const source = useResolvedReference(storedSource); const sqlTemplate = useWatch({ control, name: 'sqlTemplate' }); const chartName = useWatch({ control, name: 'name' }); const sourceObject = sources?.find(s => s.id === source); @@ -196,23 +207,36 @@ export default function RawSqlChartEditor({ }; }, [debouncedRawSqlConfig, isDashboardForm]); - const prevSource = usePrevious(source); + const prevSource = usePrevious(storedSource); const prevConnection = usePrevious(connection); useEffect(() => { const update = resolveConnectionSourceSync({ - source, + source: storedSource, connection, prevSource, prevConnection, sources, }); - if (update?.field === 'connection') { + // A connection variable stays as picked; the tile shows a mismatch + // instead of having its reference replaced + if ( + update?.field === 'connection' && + parseVariableReference(storedConnection) == null + ) { setValue('connection', update.value); } else if (update?.field === 'source') { setValue('source', update.value); } - }, [connection, prevConnection, prevSource, setValue, source, sources]); + }, [ + connection, + storedConnection, + prevConnection, + prevSource, + setValue, + storedSource, + sources, + ]); const placeholderSQl = SQL_PLACEHOLDERS[displayType ?? DisplayType.Table]; @@ -274,6 +298,8 @@ export default function RawSqlChartEditor({ control={control} name="connection" size="xs" + allowConnectionVariables + data-testid="connection-selector" /> @@ -293,7 +319,9 @@ export default function RawSqlChartEditor({ name="source" data-testid="source-selector" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables connectionId={connection} + variableConnection={storedConnection} size="xs" clearable placeholder="None" diff --git a/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts b/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts index 7e979f0a1..57efcda34 100644 --- a/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts +++ b/packages/app/src/components/ChartEditor/__tests__/resolveConnectionSourceSync.test.ts @@ -107,4 +107,28 @@ describe('resolveConnectionSourceSync', () => { }), ).toBeNull(); }); + + it('leaves the connection alone when a data source variable is selected', () => { + expect( + resolveConnectionSourceSync({ + source: '$logs', + connection: 'conn-2', + prevSource: 'src-b', + prevConnection: 'conn-2', + sources, + }), + ).toBeNull(); + }); + + it('keeps a data source variable when the connection changes', () => { + expect( + resolveConnectionSourceSync({ + source: '$logs', + connection: 'conn-2', + prevSource: '$logs', + prevConnection: 'conn-1', + sources, + }), + ).toBeNull(); + }); }); diff --git a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts index 63f4e2ded..24f910d61 100644 --- a/packages/app/src/components/ChartEditor/__tests__/utils.test.ts +++ b/packages/app/src/components/ChartEditor/__tests__/utils.test.ts @@ -19,6 +19,7 @@ import { convertFormStateToSavedChartConfig, convertSavedChartConfigToFormState, getAllowedSourceKinds, + getInterchangeableSourceKind, promqlExpressionPlaceholder, validateChartForm, } from '@/components/ChartEditor/utils'; @@ -2705,3 +2706,86 @@ describe('promqlExpressionPlaceholder', () => { ); }); }); + +describe('data source variable references', () => { + it('saves the reference rather than the source it resolves to', () => { + const form: ChartEditorFormState = { + displayType: DisplayType.Line, + source: '$logs', + series: [seriesItem], + }; + expect(convertFormStateToSavedChartConfig(form, logSource)).toMatchObject({ + source: '$logs', + }); + }); + + it('queries the resolved source for a raw SQL chart', () => { + const form: ChartEditorFormState = { + configType: 'sql', + displayType: DisplayType.Table, + source: '$logs', + connection: 'conn-1', + sqlTemplate: 'SELECT 1', + series: [], + }; + expect(convertFormStateToSavedChartConfig(form, logSource)).toMatchObject({ + source: '$logs', + }); + expect( + convertFormStateToChartConfig(form, dateRange, logSource), + ).toMatchObject({ source: logSource.id }); + }); + + it('saves a reference with no selected source when its kind is known', () => { + const form: ChartEditorFormState = { + displayType: DisplayType.Line, + source: '$logs', + series: [ + { ...seriesItem, metricName: 'cpu', metricType: MetricsDataType.Gauge }, + ], + }; + const saved = convertFormStateToSavedChartConfig( + form, + undefined, + SourceKind.Log, + ); + expect(saved).toMatchObject({ source: '$logs' }); + expect(saved).toMatchObject({ + select: [expect.not.objectContaining({ metricName: 'cpu' })], + }); + }); + + it('validates a reference with no selected source by its kind', () => { + const form: ChartEditorFormState = { + displayType: DisplayType.Line, + source: '$logs', + series: [seriesItem], + }; + expect( + validateChartForm(form, undefined, jest.fn(), { + sourceKind: SourceKind.Log, + }), + ).toEqual([]); + expect( + validateChartForm(form, undefined, jest.fn(), { + missingSourceMessage: 'Select a source for $logs', + }), + ).toEqual([{ path: 'source', message: 'Select a source for $logs' }]); + }); +}); + +describe('getInterchangeableSourceKind', () => { + it.each<[SourceKind[], SourceKind | undefined]>([ + [[SourceKind.Log], SourceKind.Log], + [[SourceKind.Log, SourceKind.Trace], SourceKind.Log], + [[SourceKind.Log, SourceKind.Metric], undefined], + [[SourceKind.Log, SourceKind.Session], undefined], + [[SourceKind.Session, SourceKind.Promql], undefined], + [[], undefined], + ])( + 'returns a stand-in for %p only when charts treat them alike', + (kinds, expected) => { + expect(getInterchangeableSourceKind(kinds)).toBe(expected); + }, + ); +}); diff --git a/packages/app/src/components/ChartEditor/utils.ts b/packages/app/src/components/ChartEditor/utils.ts index 5607dcdaa..3d6babc24 100644 --- a/packages/app/src/components/ChartEditor/utils.ts +++ b/packages/app/src/components/ChartEditor/utils.ts @@ -13,20 +13,23 @@ import { validateRawSqlForAlert, } from '@hyperdx/common-utils/dist/core/utils'; import { - getHeatmapSourceKinds, + getAllowedSourceKinds, isBuilderSavedChartConfig, + isPromqlDisplayType, isPromqlSavedChartConfig, isRawSqlSavedChartConfig, + isStringSelectDisplayType, + toBuilderHeatmapMode, } from '@hyperdx/common-utils/dist/guards'; import { MACRO_SUGGESTIONS } from '@hyperdx/common-utils/dist/macros'; import { QUERY_PARAMS_BY_DISPLAY_TYPE } from '@hyperdx/common-utils/dist/rawSqlParams'; +import { getConfigReferenceVariables } from '@hyperdx/common-utils/dist/referenceVariables'; import { BuilderSavedChartConfig, ChartConfigWithDateRange, ChartVariable, DisplayType, getSampleWeightExpression, - HeatmapMode, isLogSource, isMetricSource, isRangeThresholdType, @@ -83,6 +86,32 @@ export function buildRawSqlCompletions({ ]; } +/** + * Groups kinds that charts treat alike: validation and normalization only ask + * whether a source is a metric source and whether it supports formulas, and + * PromQL sources only serve PromQL charts. + */ +function chartSourceKindClass(kind: SourceKind): string { + if (kind === SourceKind.Promql) return 'promql'; + if (kind === SourceKind.Metric) return 'metric'; + return isFormulaSourceKind(kind) ? 'events' : 'session'; +} + +/** + * A kind that stands for all of `kinds` when charts treat them alike, so a + * chart built for one is valid on the others. Undefined when they differ. + */ +export function getInterchangeableSourceKind( + kinds: readonly SourceKind[], +): SourceKind | undefined { + const [first] = kinds; + if (first == null) return undefined; + const firstClass = chartSourceKindClass(first); + return kinds.every(kind => chartSourceKindClass(kind) === firstClass) + ? first + : undefined; +} + function normalizeChartConfig< C extends Pick< BuilderSavedChartConfig, @@ -98,15 +127,15 @@ function normalizeChartConfig< | 'heatmap' | 'where' >, ->(config: C, source: TSource): C { - const isMetricSource = source.kind === SourceKind.Metric; +>(config: C, sourceKind: SourceKind): C { + const isMetricSource = sourceKind === SourceKind.Metric; // Formulas (HDX-5080) render on metric and event (log/trace) sources, and // only on the display types the formula query paths support (time series / // table / number). Strip them elsewhere so a source or display-type switch // can't persist a config the renderer would reject. The form state keeps // them, so switching back restores the formula rows. const keepFormulas = - isFormulaSourceKind(source.kind) && + isFormulaSourceKind(sourceKind) && (config.formulas?.length ?? 0) > 0 && isFormulaDisplayType(config.displayType); return { @@ -177,70 +206,20 @@ export const isRawSqlDisplayType = ( displayType === DisplayType.Bar || displayType === DisplayType.Number; -/** - * Display types that store `select` as a plain string (column expression) - * rather than a structured `DerivedColumn[]` series array. These types - * don't use the builder series editor and skip series-level validation. - */ -export const isStringSelectDisplayType = ( - displayType: DisplayType | undefined, -): displayType is DisplayType.Search | DisplayType.EventPatterns => - displayType === DisplayType.Search || - displayType === DisplayType.EventPatterns; - -export const isPromqlDisplayType = ( - displayType: DisplayType | undefined, -): displayType is - | DisplayType.Table - | DisplayType.Line - | DisplayType.StackedBar - | DisplayType.StackedLine - | DisplayType.Pie - | DisplayType.Bar - | DisplayType.Number - | DisplayType.Heatmap => - displayType === DisplayType.Table || - displayType === DisplayType.Line || - displayType === DisplayType.StackedBar || - displayType === DisplayType.StackedLine || - displayType === DisplayType.Pie || - displayType === DisplayType.Bar || - displayType === DisplayType.Number || - displayType === DisplayType.Heatmap; - -const NON_PROMQL_SOURCE_KINDS = Object.values(SourceKind).filter( - kind => kind !== SourceKind.Promql, -); - -/** - * Search and event patterns list raw rows out of the source's `from` table. A - * metric source keeps its rows in `metricTables` and leaves `from.tableName` - * empty, so there is nothing for them to read. - */ -const ROW_LISTING_SOURCE_KINDS = NON_PROMQL_SOURCE_KINDS.filter( - kind => kind !== SourceKind.Metric, -); - -/** Source kinds the Data Source picker offers, given the editor mode and the display type. */ -export function getAllowedSourceKinds({ - configType, - displayType, - heatmapMode, -}: { - configType: ChartEditorFormState['configType']; - displayType: DisplayType | undefined; - heatmapMode?: PromqlHeatmapMode; -}): SourceKind[] { - if (configType === 'promql' && isPromqlDisplayType(displayType)) { - return [SourceKind.Promql]; - } - if (displayType === DisplayType.Heatmap) { - return [...getHeatmapSourceKinds(toBuilderHeatmapMode(heatmapMode))]; - } - if (isStringSelectDisplayType(displayType)) { - return ROW_LISTING_SOURCE_KINDS; - } - return NON_PROMQL_SOURCE_KINDS; +/** The variables a chart form's source, or a raw SQL tile's connection, references. */ +export function getFormReferenceVariables( + form: Pick< + ChartEditorFormState, + 'source' | 'connection' | 'configType' | 'displayType' + >, +): string[] { + // Only raw SQL tiles store a connection of their own + const isRawSql = + form.configType === 'sql' && isRawSqlDisplayType(form.displayType); + return getConfigReferenceVariables({ + source: form.source, + connection: isRawSql ? form.connection : undefined, + }); } const isCustomOrderByDisplayType = ( @@ -255,9 +234,23 @@ const isCustomOrderByDisplayType = ( // ChartEditorControls and the server-side surfaces cannot drift. export { isFormulaDisplayType, isFormulaSourceKind }; +// Shared with MCP tile runs, which reject a variable's source selection the +// tile can't use, as the dashboard does. +export { + getAllowedSourceKinds, + isPromqlDisplayType, + isStringSelectDisplayType, + toBuilderHeatmapMode, +}; + +/** + * `sourceKind` stands in for `source` when there is no source to read it from, + * as for a data source variable with no selection. + */ export function convertFormStateToSavedChartConfig( form: ChartEditorFormState, source: TSource | undefined, + sourceKind: SourceKind | undefined = source?.kind, ): SavedChartConfig | undefined { if (form.configType === 'promql' && isPromqlDisplayType(form.displayType)) { const promqlConfig: PromqlSavedChartConfig = { @@ -280,7 +273,7 @@ export function convertFormStateToSavedChartConfig( // 'alert', // TODO: Support alerts on PromQL (HDX-4636) ]), promqlExpression: formPromqlExpressions(form), - source: source?.id ?? form.source ?? '', + source: form.source || (source?.id ?? ''), legendTemplate: form.legendTemplate?.trim() || undefined, heatmap: formPromqlHeatmap(form), }; @@ -331,12 +324,12 @@ export function convertFormStateToSavedChartConfig( heatmap: formBuilderHeatmap(form), select: [], where: form.where ?? '', - source: source?.id ?? form.source ?? '', + source: form.source || (source?.id ?? ''), }; return config; } - if (source) { + if (sourceKind) { // Merge the series and select fields back together, and prevent the series field from being submitted const config: BuilderSavedChartConfig = { ...omit(form, [ @@ -354,10 +347,10 @@ export function convertFormStateToSavedChartConfig( : '' : form.series, where: form.where ?? '', - source: source.id, + source: form.source || (source?.id ?? ''), }; - return normalizeChartConfig(config, source); + return normalizeChartConfig(config, sourceKind); } } @@ -416,7 +409,7 @@ export function convertFormStateToChartConfig( ]), sqlTemplate: form.sqlTemplate ?? '', connection: form.connection ?? '', - source: form.source || undefined, + source: source?.id ?? (form.source || undefined), from: source?.from, implicitColumnExpression: source && (isLogSource(source) || isTraceSource(source)) @@ -489,7 +482,7 @@ export function convertFormStateToChartConfig( : mergedSelect, }; - return structuredClone(normalizeChartConfig(newConfig, source)); + return structuredClone(normalizeChartConfig(newConfig, source.kind)); } } @@ -572,13 +565,6 @@ function formBuilderHeatmap( : { mode: toBuilderHeatmapMode(form.heatmap.mode) }; } -/** A heatmap mode as a builder heatmap's, which has no histogram mode. */ -export function toBuilderHeatmapMode( - mode: PromqlHeatmapMode | undefined, -): HeatmapMode | undefined { - return mode === 'histogram' ? undefined : mode; -} - const DEFAULT_PROMQL_PLACEHOLDER = "rate(http_requests_total{service='api'}[5m])"; @@ -612,6 +598,8 @@ export const validateChartForm = ( setError: UseFormSetError, { requireAlertDisplayName = false, + sourceKind = source?.kind, + missingSourceMessage = 'Source is required', }: { /** * Whether the alert must carry a name. Set for inline alerts, which have @@ -619,6 +607,13 @@ export const validateChartForm = ( * name the alert after whatever the chart happens to be called. */ requireAlertDisplayName?: boolean; + /** + * Stands in for `source` when there is no source to read the kind from, + * as for a data source variable with no selection. + */ + sourceKind?: SourceKind; + /** Replaces the generic error for a chart with no usable source. */ + missingSourceMessage?: string; } = {}, ) => { const errors: { path: Path; message: string }[] = []; @@ -642,9 +637,9 @@ export const validateChartForm = ( if ( !isRawSqlChart && form.displayType !== DisplayType.Markdown && - (!form.source || !source) + (!form.source || !sourceKind) ) { - errors.push({ path: `source`, message: 'Source is required' }); + errors.push({ path: `source`, message: missingSourceMessage }); } // Validate that valueExpressions are specified for each series. @@ -653,7 +648,7 @@ export const validateChartForm = ( if ( !isRawSqlChart && Array.isArray(form.series) && - source?.kind !== SourceKind.Metric && + sourceKind !== SourceKind.Metric && form.displayType !== DisplayType.Markdown && !isStringSelectDisplayType(form.displayType) ) { @@ -669,7 +664,7 @@ export const validateChartForm = ( // Validate metric names for metric sources if ( - source?.kind === SourceKind.Metric && + sourceKind === SourceKind.Metric && Array.isArray(form.series) && form.displayType !== DisplayType.Markdown && form.displayType !== DisplayType.Search && @@ -691,7 +686,7 @@ export const validateChartForm = ( // source kind + display type). if ( !isRawSqlChart && - isFormulaSourceKind(source?.kind) && + isFormulaSourceKind(sourceKind) && isFormulaDisplayType(form.displayType) && Array.isArray(form.formulas) ) { @@ -789,7 +784,7 @@ export const validateChartForm = ( !isRawSqlChart && Array.isArray(form.series) && form.displayType === DisplayType.Number && - !(form.formulas?.length && isFormulaSourceKind(source?.kind)) && + !(form.formulas?.length && isFormulaSourceKind(sourceKind)) && form.series.length > (form.seriesReturnType === 'ratio' ? 2 : 1) ) { errors.push({ diff --git a/packages/app/src/components/ConnectionSelect.tsx b/packages/app/src/components/ConnectionSelect.tsx index 2422377cf..eccaacc5b 100644 --- a/packages/app/src/components/ConnectionSelect.tsx +++ b/packages/app/src/components/ConnectionSelect.tsx @@ -1,35 +1,51 @@ -import { useMemo } from 'react'; -import { UseControllerProps } from 'react-hook-form'; +import { UseControllerProps, useWatch } from 'react-hook-form'; +import { parseVariableReference } from '@hyperdx/common-utils/dist/referenceVariables'; +import { SelectProps } from '@mantine/core'; import { IconServer } from '@tabler/icons-react'; import SelectControlled from '@/components/SelectControlled'; -import { useConnections } from '@/connection'; +import { + useWithConnectionVariableItems, + VARIABLE_ICON, +} from '@/components/sourceSelectUtils'; +import { useConnectionItems } from '@/hooks/useConnectionItems'; export function ConnectionSelectControlled({ size, + allowConnectionVariables = false, + placeholder = 'Connection', + clearable = false, ...props -}: { size?: string } & UseControllerProps) { - const { data } = useConnections(); - - const values = useMemo( - () => - data?.map(d => ({ - value: d.id, - label: d.name, - })), - [data], +}: { + size?: string; + /** Whether to offer the dashboard's connection variables. */ + allowConnectionVariables?: boolean; +} & Pick & + UseControllerProps) { + const selected = useWatch({ control: props.control, name: props.name }); + const connectionItems = useConnectionItems(); + const items = useWithConnectionVariableItems( + connectionItems, + allowConnectionVariables, ); return ( } + placeholder={placeholder} + leftSection={ + parseVariableReference(selected) != null ? ( + VARIABLE_ICON + ) : ( + + ) + } maxDropdownHeight={280} size={size} /> diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx index 4524f411a..7c5d577cd 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartEditorControls.tsx @@ -211,6 +211,7 @@ export function ChartEditorControls({ name="source" data-testid="source-selector" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables onSchemaPreview={() => setIsSourceSchemaPreviewOpen(true)} isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(tableSource)} /> diff --git a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx index 61e1b47af..a061b8811 100644 --- a/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/ChartPreviewPanel.tsx @@ -178,6 +178,10 @@ type ChartPreviewPanelProps = { dbTimeChartConfig?: ChartConfigWithDateRange; /** Required dashboard filters with nothing selected that block this tile. */ missingRequiredFilterNames?: string[]; + /** Whether turning off "Apply filters" would clear the required-filter block. */ + canPreviewWithoutFilters?: boolean; + /** Why the current selections can't be queried, shown instead of the chart. */ + blockedReason?: string; setValue: (name: 'orderBy', value: string) => void; setDisplayType: (displayType: DisplayType) => void; onSubmit: () => void; @@ -197,6 +201,8 @@ export function ChartPreviewPanel({ showGeneratedPromql, dbTimeChartConfig, missingRequiredFilterNames, + canPreviewWithoutFilters = false, + blockedReason, setValue, setDisplayType, onSubmit, @@ -213,8 +219,12 @@ export function ChartPreviewPanel({ const blockingFilterNames = missingRequiredFilterNames ?? []; const isBlockedByRequiredFilters = blockingFilterNames.length > 0 && tabQueriesData(activeTab); + const isBlocked = + blockedReason != null && + !isBlockedByRequiredFilters && + tabQueriesData(activeTab); const queryReady = - !isBlockedByRequiredFilters && !!isQueryReady(queriedConfig); + !isBlockedByRequiredFilters && !isBlocked && !!isQueryReady(queriedConfig); const onTableSortingChange = useCallback( (sortState: SortingState | null) => { @@ -262,13 +272,24 @@ export function ChartPreviewPanel({ <> {isBlockedByRequiredFilters ? ( + ) : isBlocked ? ( + ) : !queryReady && tabQueriesData(activeTab) ? ( = ( + values, + context, + options, +) => + zodChartFormResolver( + getFormReferenceVariables(values).length > 0 + ? { ...values, alert: undefined } + : values, + context, + options, + ); + const ALERT_IGNORES_DASHBOARD_FILTERS = 'Dashboard-level filter and variable selections cannot be applied when an alert is configured.'; @@ -243,7 +276,6 @@ export default function EditTimeChartForm({ isAlertRequired = false, showSaveToDashboard, }: EditTimeChartFormProps) { - const alertsEnabled = enableAlerts ?? dashboardId != null; const formValue: ChartEditorFormState = useMemo( () => convertSavedChartConfigToFormState(chartConfig), [chartConfig], @@ -266,7 +298,7 @@ export default function EditTimeChartForm({ } = useForm({ defaultValues: formValue, values: formValue, - resolver: zodResolver(zSavedChartConfig), + resolver: chartFormResolver, }); const { @@ -346,13 +378,75 @@ export default function EditTimeChartForm({ [configType, displayType, heatmapMode], ); + // The form keeps a data source variable reference as written; everything + // that queries uses the source the variable currently selects. + const sourceVariableName = parseVariableReference(sourceId); + const resolvedSourceId = useResolvedReference(sourceId); + const resolvedConnection = useResolvedReference(connection); + const sourceVariableDeclarations = useSourceVariableDeclarations(); + + const referenceVariableValues = useReferenceVariableValues(); + const referenceVariableNames = useMemo( + () => + getFormReferenceVariables({ + source: sourceId, + connection, + configType, + displayType, + }), + [sourceId, connection, configType, displayType], + ); + const usesReferenceVariable = referenceVariableNames.length > 0; + + // An alert must query one fixed source and connection, not the viewer's + // current selection. + const alertsEnabled = + (enableAlerts ?? dashboardId != null) && !usesReferenceVariable; + // The alert as it will save + const activeAlert = usesReferenceVariable ? undefined : alert; + // A source selection that current mode can't query counts as no source, // so that nothing downstream builds a query from it. const { data: tableSource } = useSource({ - id: sourceId, + id: resolvedSourceId, kinds: allowedSourceKinds, }); + // Saving reads only the source's kind. With no source selected, a variable + // whose kinds charts all treat alike still determines it. + const sourceVariable = sourceVariableDeclarations.find( + variable => variable.name === sourceVariableName, + ); + const sourceKind = useMemo(() => { + if (tableSource) return tableSource.kind; + if (resolvedSourceId != null) return; + const kinds = sourceVariable?.allowedSourceKinds.filter(kind => + allowedSourceKinds.includes(kind), + ); + return kinds && getInterchangeableSourceKind(kinds); + }, [tableSource, resolvedSourceId, sourceVariable, allowedSourceKinds]); + + // Why a `$name` source gave no usable source kind + const missingSourceMessage = + sourceVariableName == null + ? undefined + : sourceVariable == null + ? `This dashboard has no data source variable named $${sourceVariableName}` + : resolvedSourceId == null + ? `Select a source for $${sourceVariableName} in the filter bar to save this tile` + : `The source selected for $${sourceVariableName} can't be used with this chart type`; + + // A variable can select a source on another connection than the one a raw + // SQL query runs on, which the dashboard blocks too + const previewBlockedReason = + isRawSqlInput && + usesReferenceVariable && + tableSource != null && + resolvedConnection != null && + tableSource.connection !== resolvedConnection + ? "The selected data source is on a different connection than this tile's query. Select a source on the same connection." + : undefined; + const databaseName = tableSource?.from.databaseName; const tableName = tableSource?.from.tableName; @@ -501,7 +595,7 @@ export default function EditTimeChartForm({ // Alerts ignore dashboard-level filters and variables, // so disable the toggle when an alert is configured. const [applyFilters, setApplyFilters] = useState(true); - const resolvedApplyFilters = applyFilters && alert == null; + const resolvedApplyFilters = applyFilters && activeAlert == null; const dashboardFiltersToggleProps = useMemo< DashboardFiltersToggleProps | undefined @@ -512,10 +606,10 @@ export default function EditTimeChartForm({ : { checked: resolvedApplyFilters, disabledReason: - alert != null ? ALERT_IGNORES_DASHBOARD_FILTERS : undefined, + activeAlert != null ? ALERT_IGNORES_DASHBOARD_FILTERS : undefined, onChange: setApplyFilters, }, - [getDashboardFilters, resolvedApplyFilters, alert], + [getDashboardFilters, resolvedApplyFilters, activeAlert], ); const previewDashboardFilters = useMemo(() => { @@ -534,6 +628,7 @@ export default function EditTimeChartForm({ variables, unsatisfiedRequiredFilters, applySelections: resolvedApplyFilters, + referenceVariableNames, }); }, [ queriedConfig, @@ -541,6 +636,7 @@ export default function EditTimeChartForm({ variables, unsatisfiedRequiredFilters, resolvedApplyFilters, + referenceVariableNames, ]); // Attach the dashboard's filters and variables so that the preview queries @@ -555,17 +651,42 @@ export default function EditTimeChartForm({ }; }, [queriedConfig, previewDashboardFilters]); + const debouncedForm = useDebouncedFormValues(watch, getValues, 300); + + // With no selection for a variable it references the tile has nothing to + // query, so there may be no queried config to compute the block from. + const previewBlockingFilters = useMemo(() => { + if (previewDashboardFilters) return previewDashboardFilters; + if ( + !referenceVariableNames.some(name => !referenceVariableValues.get(name)) + ) + return undefined; + return getPreviewBlockingFilters({ + config: convertFormStateToSavedChartConfig(debouncedForm, tableSource), + sourceId: undefined, + variables, + unsatisfiedRequiredFilters, + applySelections: resolvedApplyFilters, + referenceVariableNames, + }); + }, [ + previewDashboardFilters, + referenceVariableNames, + referenceVariableValues, + debouncedForm, + tableSource, + variables, + unsatisfiedRequiredFilters, + resolvedApplyFilters, + ]); + const dbTimeChartConfig = useMemo( - () => computeDbTimeChartConfig(previewConfig, alert), - [previewConfig, alert], + () => computeDbTimeChartConfig(previewConfig, activeAlert), + [previewConfig, activeAlert], ); - // Casting because `useWatch` returns a deep partial type, but we know that the - // form state is complete due to default values set above. - const watchedForm = useWatch({ control }) as ChartEditorFormState; - const [debouncedForm] = useDebouncedValue(watchedForm, 300); const additionalAlertWarnings = useMemo(() => { - if (alert == null) return []; + if (activeAlert == null) return []; const config = convertFormStateToSavedChartConfig( debouncedForm, tableSource, @@ -574,7 +695,7 @@ export default function EditTimeChartForm({ ? getAlertVariableWarning(config, variables) : undefined; return variableWarning ? [variableWarning] : []; - }, [alert, debouncedForm, tableSource, variables]); + }, [activeAlert, debouncedForm, tableSource, variables]); const [saveToDashboardModalOpen, setSaveToDashboardModalOpen] = useState(false); @@ -584,10 +705,16 @@ export default function EditTimeChartForm({ const errors = validateChartForm(form, tableSource, setError, { // An inline alert has no tile to inherit a name from. requireAlertDisplayName: alertsEnabled && dashboardId == null, + sourceKind, + missingSourceMessage, }); if (errors.length > 0) return { errors, config: null }; - const savedConfig = convertFormStateToSavedChartConfig(form, tableSource); + const savedConfig = convertFormStateToSavedChartConfig( + form, + tableSource, + sourceKind, + ); if (!savedConfig) { console.error( 'convertFormStateToSavedChartConfig returned undefined after validation passed. ' + @@ -621,6 +748,8 @@ export default function EditTimeChartForm({ }, [ tableSource, + sourceKind, + missingSourceMessage, setError, alertsEnabled, dashboardId, @@ -646,11 +775,19 @@ export default function EditTimeChartForm({ return; } - const queriedConfig = convertFormStateToChartConfig( + // A raw SQL tile's connection may be a variable reference; the + // source is already resolved through `tableSource`. + const convertedQueriedConfig = convertFormStateToChartConfig( form, dateRange, tableSource, ); + const queriedConfig = + convertedQueriedConfig && + resolveConfigReferences( + convertedQueriedConfig, + referenceVariableValues, + ); if (config && queriedConfig) { const isRawSqlChart = @@ -670,6 +807,7 @@ export default function EditTimeChartForm({ setQueriedConfigAndSource, tableSource, dateRange, + referenceVariableValues, ], ); @@ -784,7 +922,7 @@ export default function EditTimeChartForm({ const allowedSourceItems = useFilteredSortedSourceItems({ sources, allowedSourceKinds, - connectionId: configType === 'sql' ? connection : undefined, + connectionId: configType === 'sql' ? resolvedConnection : undefined, groupBySection: true, }); @@ -817,6 +955,17 @@ export default function EditTimeChartForm({ // should be filled in. Raw SQL source is optional, so leave it. if (!sourceId && configType === 'sql') return; + // Kept on the same terms the picker offers it + if ( + isSourceVariableReferenceAccepted( + sourceId, + sourceVariableDeclarations, + allowedSourceKinds, + ) + ) { + return; + } + // If the currently selected source is still allowed, keep it. const selected = sources.find(s => s.id === sourceId); if ( @@ -846,6 +995,7 @@ export default function EditTimeChartForm({ setValue, sourceId, sources, + sourceVariableDeclarations, ]); useEffect(() => { @@ -1320,7 +1470,7 @@ export default function EditTimeChartForm({ onOpenDisplaySettings={openDisplaySettings} onSubmit={onSubmit} isDashboardForm={isDashboardForm} - alert={alert} + alert={activeAlert} additionalWarnings={additionalAlertWarnings} alertsEnabled={alertsEnabled} isAlertRequired={isAlertRequired} @@ -1349,7 +1499,7 @@ export default function EditTimeChartForm({ activeTab={activeTab} seriesReturnType={seriesReturnType} ratioMode={ratioMode} - alert={alert} + alert={activeAlert} additionalWarnings={additionalAlertWarnings} alertsEnabled={alertsEnabled} isAlertRequired={isAlertRequired} @@ -1363,6 +1513,18 @@ export default function EditTimeChartForm({ onHeatmapModeChange={onHeatmapModeChange} /> )} + {alert != null && usesReferenceVariable && ( + } + p="xs" + mt="sm" + > + Alerts aren't available on tiles that use a data source or + connection variable. This tile's alert will be removed when + you save. + + )} setValue(name, value)} setDisplayType={type => setValue('displayType', type, { shouldDirty: true }) diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx b/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx index 1b50d0218..878ccf494 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/ChartPreviewPanel.test.tsx @@ -514,6 +514,7 @@ describe('ChartPreviewPanel', () => { queriedConfig: baseBuilderConfig, dbTimeChartConfig: baseBuilderConfig, missingRequiredFilterNames: ['Service', 'Environment'], + canPreviewWithoutFilters: true, }; it('names them instead of querying', () => { @@ -521,7 +522,7 @@ describe('ChartPreviewPanel', () => { expect( screen.getByText( - 'Missing required filters: Service, Environment. Select a value for each required filter, or turn off “Apply filters” to preview this tile without them.', + 'Missing required filters or variables: Service, Environment. Select a value for each required filter, or turn off “Apply filters” to preview this tile without them.', ), ).toBeInTheDocument(); expect(screen.queryByTestId('db-time-chart')).not.toBeInTheDocument(); @@ -531,6 +532,16 @@ describe('ChartPreviewPanel', () => { ).not.toBeInTheDocument(); }); + it('leaves out the "Apply filters" hint when turning it off would not help', () => { + renderPanel({ ...blockedProps, canPreviewWithoutFilters: false }); + + expect( + screen.getByTestId('preview-missing-required-filters'), + ).toHaveTextContent( + /^Missing required filters or variables: Service, Environment\. Select a value for each one to preview this tile\.$/, + ); + }); + it('does not block a markdown tile, which queries nothing', () => { renderPanel({ ...blockedProps, activeTab: 'markdown' }); @@ -544,8 +555,40 @@ describe('ChartPreviewPanel', () => { expect(screen.getByTestId('db-time-chart')).toBeInTheDocument(); expect( - screen.queryByText(/Missing required filters/), + screen.queryByText(/Missing required filters or variables/), ).not.toBeInTheDocument(); }); }); + + describe('when the selections are blocked', () => { + const blockedProps = { + queriedConfig: baseBuilderConfig, + dbTimeChartConfig: baseBuilderConfig, + blockedReason: 'The selected data source is on another connection.', + }; + + it('shows the reason instead of querying', () => { + renderPanel(blockedProps); + + expect(screen.getByTestId('preview-blocked')).toHaveTextContent( + 'The selected data source is on another connection.', + ); + expect(screen.queryByTestId('db-time-chart')).not.toBeInTheDocument(); + }); + + it('shows missing required filters first', () => { + renderPanel({ ...blockedProps, missingRequiredFilterNames: ['Service'] }); + + expect( + screen.getByTestId('preview-missing-required-filters'), + ).toBeInTheDocument(); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); + + it('does not block a markdown tile, which queries nothing', () => { + renderPanel({ ...blockedProps, activeTab: 'markdown' }); + + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); + }); }); diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx index bd9dd337b..8b35f1ada 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/DBEditTimeChartForm.test.tsx @@ -3,6 +3,8 @@ import React from 'react'; import { useController as mockUseController } from 'react-hook-form'; import { AlertThresholdType, + DashboardFilter, + DataSourceDashboardFilter, DisplayType, MetricsDataType, SavedChartConfig, @@ -13,6 +15,7 @@ import { fireEvent, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import DBEditTimeChartForm from '@/components/DBEditTimeChartForm'; +import { ReferenceVariablesProvider } from '@/components/sourceSelectUtils'; import { useSource } from '@/source'; import { DEFAULT_TILE_ALERT } from '@/utils/alerts'; @@ -40,6 +43,8 @@ jest.mock('@/hooks/useFetchMetricMetadata', () => ({ jest.mock('@/hooks/useMetadata', () => ({ useMetadataWithSettings: jest.fn().mockReturnValue({}), + // The raw SQL editor's completions + useMultipleAllFields: jest.fn().mockReturnValue({ data: [] }), useGetKeyValues: jest.fn().mockReturnValue({ data: [ { @@ -188,6 +193,7 @@ jest.mock('../../SourceSelect', () => ({ + ); }, @@ -1585,3 +1591,221 @@ describe('DBEditTimeChartForm - Inline alerts', () => { expect(screen.queryByTestId('remove-alert-button')).not.toBeInTheDocument(); }); }); + +describe('DBEditTimeChartForm - Raw SQL data source variables', () => { + const logsVariable: DataSourceDashboardFilter = { + id: 'logs', + type: 'DATA_SOURCE', + name: 'logs', + variableName: 'logs', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + const rawSqlConfig: SavedChartConfig = { + configType: 'sql', + displayType: DisplayType.Table, + name: 'Raw SQL tile', + source: '$logs', + connection: 'conn-2', + sqlTemplate: 'SELECT count() FROM $__sourceTable', + }; + + const renderWithSelection = (sourceId: string) => + renderWithMantine( + + + + + , + ); + + const logSource = (connection: string) => ({ + id: 'logs-source', + kind: SourceKind.Log, + name: 'Logs', + from: { databaseName: 'default', tableName: 'otel_logs' }, + connection, + timestampValueExpression: 'Timestamp', + }); + + beforeEach(() => { + jest.clearAllMocks(); + }); + + it("blocks the preview when the variable's source is on another connection", async () => { + mockUseSourceData(logSource('conn-1')); + renderWithSelection('logs-source'); + + expect(await screen.findByTestId('preview-blocked')).toHaveTextContent( + "The selected data source is on a different connection than this tile's query.", + ); + }); + + it('blocks only on the unselected variable once filters are not applied', async () => { + const globalFilter: DashboardFilter = { + id: 'service', + type: 'QUERY_EXPRESSION', + name: 'Service', + expression: 'ServiceName', + source: 'logs-source', + minSelections: 1, + isGlobalRequirement: true, + }; + mockUseSourceData(undefined); + renderWithMantine( + + + []} + unsatisfiedRequiredFilters={[logsVariable, globalFilter]} + /> + + , + ); + + expect( + await screen.findByTestId('preview-missing-required-filters'), + ).toHaveTextContent( + /^Missing required filters or variables: logs, Service\. Select a value for each required filter, or turn off “Apply filters” to preview this tile without them\.$/, + ); + + await userEvent.click( + screen.getByRole('switch', { name: 'Apply filters' }), + ); + + expect( + screen.getByTestId('preview-missing-required-filters'), + ).toHaveTextContent( + /^Missing required filters or variables: logs\. Select a value for each one to preview this tile\.$/, + ); + }); + + it("previews when the variable's source is on the tile's connection", async () => { + mockUseSourceData(logSource('conn-2')); + renderWithSelection('logs-source'); + + await screen.findByTestId('chart-run-query-button'); + expect(screen.queryByTestId('preview-blocked')).not.toBeInTheDocument(); + }); +}); + +describe('DBEditTimeChartForm - Alerts on data source variables', () => { + const metricsVariable: DataSourceDashboardFilter = { + id: 'metrics', + type: 'DATA_SOURCE', + name: 'metrics', + variableName: 'metrics', + allowedSourceKinds: [SourceKind.Metric], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }; + + const series = { + aggFn: 'avg' as const, + aggCondition: '', + aggConditionLanguage: 'lucene' as const, + valueExpression: 'Value', + metricType: MetricsDataType.Gauge, + metricName: 'test.metric.gauge', + }; + + const completeAlert = { + ...DEFAULT_TILE_ALERT, + channels: [{ type: 'webhook' as const, webhookId: 'webhook-1' }], + }; + + const renderWithAlert = ( + alert: NonNullable, + onSave: jest.Mock, + ) => + renderWithMantine( + + + + + , + ); + + const removalNotice = /This tile's alert will be removed when you save\./; + + beforeEach(() => { + jest.clearAllMocks(); + mockUseSource.mockImplementation(({ id }: { id?: string }) => ({ + data: + id === 'metric-source' + ? { + id: 'metric-source', + kind: SourceKind.Metric, + name: 'Test Metric Source', + from: { databaseName: 'default', tableName: '' }, + connection: 'default', + timestampValueExpression: 'Timestamp', + metricTables: { gauge: 'metrics.gauge' }, + } + : undefined, + })); + }); + + it('keeps the alert when the source goes to a variable and back', async () => { + const onSave = jest.fn(); + renderWithAlert(completeAlert, onSave); + const sourceSelector = screen.getByTestId('source-selector'); + + await userEvent.selectOptions(sourceSelector, '$metrics'); + expect(screen.getByText(removalNotice)).toBeInTheDocument(); + expect(screen.queryByTestId('alert-button')).not.toBeInTheDocument(); + + await userEvent.selectOptions(sourceSelector, 'metric-source'); + expect(screen.queryByText(removalNotice)).not.toBeInTheDocument(); + await userEvent.click(screen.getByTestId('chart-save-button')); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + expect(onSave.mock.calls[0][0].alert).toMatchObject(completeAlert); + }); + + it('saves without the alert while the source is a variable, even an invalid one', async () => { + const onSave = jest.fn(); + // No webhook picked, so the alert alone would block the save + renderWithAlert(DEFAULT_TILE_ALERT, onSave); + + await userEvent.selectOptions( + screen.getByTestId('source-selector'), + '$metrics', + ); + await userEvent.click(screen.getByTestId('chart-save-button')); + + await waitFor(() => expect(onSave).toHaveBeenCalledTimes(1)); + const saved = onSave.mock.calls[0][0]; + expect(saved.source).toBe('$metrics'); + expect(saved.alert).toBeUndefined(); + }); +}); diff --git a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts index 2aa241098..6635957e5 100644 --- a/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts +++ b/packages/app/src/components/DBEditTimeChartForm/__tests__/utils.test.ts @@ -19,6 +19,7 @@ import { buildSampleEventsConfig, computeDbTimeChartConfig, displayTypeToActiveTab, + getPreviewBlockingFilters, isQueryReady, resolvePreviewVariables, resolveTilePreviewFilters, @@ -696,6 +697,7 @@ describe('resolveTilePreviewFilters', () => { filters: dashboardFilters, variables: [], missingRequiredFilterNames: [], + canPreviewWithoutFilters: false, }); }); @@ -708,6 +710,7 @@ describe('resolveTilePreviewFilters', () => { filters: undefined, variables: [{ name: 'service', values: [] }], missingRequiredFilterNames: [], + canPreviewWithoutFilters: false, }); }); @@ -796,6 +799,107 @@ describe('resolveTilePreviewFilters', () => { }).missingRequiredFilterNames, ).toEqual([]); }); + + it('still blocks on a referenced source variable while the filters are turned off', () => { + const sourceVariable: DashboardFilter = { + id: 'f3', + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'logs', + minSelections: 1, + maxSelections: 1, + }; + const unsatisfiedRequiredFilters = [requiredFilter, sourceVariable]; + + expect( + resolve({ + config: rawSqlWithFiltersMacro, + unsatisfiedRequiredFilters, + applySelections: false, + referenceVariableNames: ['logs'], + }).missingRequiredFilterNames, + ).toEqual(['Logs source']); + expect( + resolve({ unsatisfiedRequiredFilters, applySelections: false }) + .missingRequiredFilterNames, + ).toEqual([]); + }); +}); + +describe('getPreviewBlockingFilters', () => { + const sourceVariable: DashboardFilter = { + id: 'logs', + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'logs', + minSelections: 1, + maxSelections: 1, + }; + const requiredVariable: DashboardFilter = { + id: 'env', + type: 'STATIC_LIST', + name: 'Environment', + options: ['prod'], + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: 'env', + minSelections: 1, + }; + const rawSqlWithVariable: ChartConfigWithDateRange = { + configType: 'sql', + sqlTemplate: "SELECT count() FROM logs WHERE env = '$env'", + connection: 'clickhouse', + dateRange, + }; + + const getBlocking = ( + overrides: Partial[0]> = {}, + ) => + getPreviewBlockingFilters({ + config: rawSqlWithVariable, + sourceId: undefined, + variables: [{ name: 'env', values: [] }], + unsatisfiedRequiredFilters: [sourceVariable, requiredVariable], + applySelections: true, + referenceVariableNames: ['logs'], + ...overrides, + }); + + it('offers turning off the filters when that clears part of the block', () => { + expect(getBlocking()).toEqual({ + missingRequiredFilterNames: ['Logs source', 'Environment'], + canPreviewWithoutFilters: true, + }); + }); + + it('does not offer turning off the filters when only a reference variable blocks', () => { + expect( + getBlocking({ unsatisfiedRequiredFilters: [sourceVariable] }), + ).toEqual({ + missingRequiredFilterNames: ['Logs source'], + canPreviewWithoutFilters: false, + }); + }); + + it('does not offer turning off the filters when they are already off', () => { + expect(getBlocking({ applySelections: false })).toEqual({ + missingRequiredFilterNames: ['Logs source'], + canPreviewWithoutFilters: false, + }); + }); + + it('blocks only on reference variables when no query could be built', () => { + expect(getBlocking({ config: undefined })).toEqual({ + missingRequiredFilterNames: ['Logs source'], + canPreviewWithoutFilters: false, + }); + }); }); describe('withBroadcastFilters', () => { diff --git a/packages/app/src/components/DBEditTimeChartForm/useDebouncedFormValues.ts b/packages/app/src/components/DBEditTimeChartForm/useDebouncedFormValues.ts new file mode 100644 index 000000000..80c504a1c --- /dev/null +++ b/packages/app/src/components/DBEditTimeChartForm/useDebouncedFormValues.ts @@ -0,0 +1,25 @@ +import { useEffect, useState } from 'react'; +import { FieldValues, UseFormGetValues, UseFormWatch } from 'react-hook-form'; +import { useDebouncedCallback } from '@mantine/hooks'; + +/** + * The form's values, updated `delay` ms after the last change. Unlike + * `useWatch({ control })`, which types them as a deep partial, they're typed + * as complete. + * + * Kept out of the form component because the React Compiler skips any + * component that calls `watch`. + */ +export function useDebouncedFormValues( + watch: UseFormWatch, + getValues: UseFormGetValues, + delay: number, +): T { + const [values, setValues] = useState(() => getValues()); + const update = useDebouncedCallback(() => setValues(getValues()), delay); + useEffect(() => { + const subscription = watch(() => update()); + return () => subscription.unsubscribe(); + }, [watch, update]); + return values; +} diff --git a/packages/app/src/components/DBEditTimeChartForm/utils.ts b/packages/app/src/components/DBEditTimeChartForm/utils.ts index d49cc65bc..4ee56423e 100644 --- a/packages/app/src/components/DBEditTimeChartForm/utils.ts +++ b/packages/app/src/components/DBEditTimeChartForm/utils.ts @@ -10,7 +10,7 @@ import { import { isTimeSeriesDisplayType } from '@hyperdx/common-utils/dist/core/utils'; import { configConsumesBroadcastFilters, - getBlockingRequiredFilterNames, + getBlockingRequiredFilters, } from '@hyperdx/common-utils/dist/dashboardFilterValues'; import { getPromqlFilters, @@ -23,11 +23,13 @@ import { isRawSqlSavedChartConfig, } from '@hyperdx/common-utils/dist/guards'; import { substitutePromqlChartConfigTemplates } from '@hyperdx/common-utils/dist/macros'; +import { getReferenceVariableFilters } from '@hyperdx/common-utils/dist/referenceVariables'; import { BroadcastFilter, BuilderChartConfigWithDateRange, ChartAlertBaseSchema, ChartConfigWithDateRange, + ChartConfigWithOptDateRange, ChartConfigWithOptTimestamp, ChartVariable, DashboardFilter, @@ -204,21 +206,97 @@ export function resolvePreviewVariables({ : referenced.map(variable => ({ ...variable, values: [] })); } +/** + * The required filters that block a preview with `applySelections` off: only + * the reference variables the tile can't be queried without. + */ +function getUnappliedPreviewBlockingFilterNames( + unsatisfiedRequiredFilters: DashboardFilter[] | undefined, + referenceVariableNames: readonly string[] | undefined, +): string[] { + const referenced = new Set(referenceVariableNames); + return getReferenceVariableFilters(unsatisfiedRequiredFilters) + .filter(({ name }) => referenced.has(name)) + .map(({ filter }) => filter.name); +} + +export type PreviewBlockingFilters = { + /** Names of the required filters that have nothing selected and block the preview. */ + missingRequiredFilterNames: string[]; + /** Whether turning off "Apply filters" would clear the block. */ + canPreviewWithoutFilters: boolean; +}; + +/** + * The required filters with nothing selected that block a tile preview. + * + * With `applySelections` off, only the reference variables the tile can't be + * queried without still block. `config` is undefined when no query could be + * built, e.g. because a source variable has no selection; the tile then + * consumes no broadcast filters and references no template variables. + */ +export function getPreviewBlockingFilters({ + config, + sourceId, + variables, + unsatisfiedRequiredFilters, + applySelections, + referenceVariableNames, +}: { + config: ChartConfigWithOptDateRange | SavedChartConfig | undefined; + sourceId: string | undefined; + variables: ChartVariable[] | undefined; + unsatisfiedRequiredFilters: DashboardFilter[] | undefined; + applySelections: boolean; + /** The data source and connection variables the tile's stored config references. */ + referenceVariableNames: readonly string[] | undefined; +}): PreviewBlockingFilters { + const unappliedNames = getUnappliedPreviewBlockingFilterNames( + unsatisfiedRequiredFilters, + referenceVariableNames, + ); + if (!applySelections) { + return { + missingRequiredFilterNames: unappliedNames, + canPreviewWithoutFilters: false, + }; + } + + const missingRequiredFilterNames = getBlockingRequiredFilters( + unsatisfiedRequiredFilters ?? [], + { + sourceId, + referenceVariableNames, + referencedVariableNames: + config && variables + ? filterReferencedVariables(config, variables).map(v => v.name) + : undefined, + consumesBroadcastFilters: + config != null && configConsumesBroadcastFilters(config, sourceId), + }, + ).map(filter => filter.name); + return { + missingRequiredFilterNames, + canPreviewWithoutFilters: missingRequiredFilterNames.some( + name => !unappliedNames.includes(name), + ), + }; +} + /** What the dashboard's filter state contributes to a tile preview. */ -export type TilePreviewFilters = { +export type TilePreviewFilters = PreviewBlockingFilters & { /** Broadcast filter conditions to query the preview with, in its query language. */ filters: BroadcastFilter[] | undefined; /** The referenced variables, with or without their selections. */ variables: ChartVariable[] | undefined; - /** Names of the required filters that have nothing selected. */ - missingRequiredFilterNames: string[]; }; /** * Applies the parent dashboard's filter selections to a tile preview. * * With `applySelections` off, the preview runs as an alert would: no broadcast - * filters, empty variable selections, and no required-filter block. + * filters, empty variable selections, and no required-filter block other than + * the reference variables the tile can't be queried without. */ export function resolveTilePreviewFilters({ config, @@ -227,14 +305,25 @@ export function resolveTilePreviewFilters({ variables, unsatisfiedRequiredFilters, applySelections, + referenceVariableNames, }: { config: ChartConfigWithDateRange; sourceId: string | undefined; + /** The data source and connection variables the tile's stored config references. */ + referenceVariableNames?: readonly string[]; filters: BroadcastFilter[] | undefined; variables: ChartVariable[] | undefined; unsatisfiedRequiredFilters: DashboardFilter[] | undefined; applySelections: boolean; }): TilePreviewFilters { + const blocking = getPreviewBlockingFilters({ + config, + sourceId, + variables, + unsatisfiedRequiredFilters, + applySelections, + referenceVariableNames, + }); const previewVariables = resolvePreviewVariables({ config, variables, @@ -242,11 +331,7 @@ export function resolveTilePreviewFilters({ }); if (!applySelections) { - return { - filters: undefined, - variables: previewVariables, - missingRequiredFilterNames: [], - }; + return { ...blocking, filters: undefined, variables: previewVariables }; } // PromQL tiles take only PromQL conditions; `configConsumesBroadcastFilters` @@ -257,16 +342,7 @@ export function resolveTilePreviewFilters({ ? getSqlFilters(filters) : undefined; - return { - filters: previewFilters, - variables: previewVariables, - missingRequiredFilterNames: getBlockingRequiredFilterNames({ - config, - sourceId, - unsatisfiedRequiredFilters, - referencedVariables: previewVariables, - }), - }; + return { ...blocking, filters: previewFilters, variables: previewVariables }; } /** The config with the broadcast filters in its own query language attached. */ diff --git a/packages/app/src/components/DashboardFilterLabel.tsx b/packages/app/src/components/DashboardFilterLabel.tsx index 893e70697..c6a5020e5 100644 --- a/packages/app/src/components/DashboardFilterLabel.tsx +++ b/packages/app/src/components/DashboardFilterLabel.tsx @@ -19,6 +19,16 @@ export const getPendingVariablesTooltip = ( } no selected value.`; }; +/** Explain a filter whose data source variable selects a source it can't use. */ +export const getIncompatibleVariablesTooltip = ( + incompatibleVariables: string[], +): string => { + const names = incompatibleVariables.map(name => `$${name}`).join(', '); + return `This filter can't use the source ${names} ${ + incompatibleVariables.length === 1 ? 'selects' : 'select' + }. Select a different source.`; +}; + /** One of the caution icons a filter's label row can carry, with its tooltip. */ export const FilterCaution = ({ label, diff --git a/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx index 6cf870d08..8eb2c5293 100644 --- a/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/AdhocFilterEditForm.tsx @@ -7,6 +7,11 @@ import { getAdhocFilterSourceKinds, isAdhocFilter, } from '@hyperdx/common-utils/dist/filters'; +import { + isSourceVariableReferenceAccepted, + parseVariableReference, + resolveVariableReference, +} from '@hyperdx/common-utils/dist/referenceVariables'; import { AdhocFilterSourceType, DashboardFilter, @@ -17,6 +22,10 @@ import { IconAlertTriangle } from '@tabler/icons-react'; import SearchWhereInput from '@/components/SearchInput/SearchWhereInput'; import { SourceMultiSelectControlled } from '@/components/SourceMultiSelect'; +import { + useReferenceVariableValues, + useSourceVariableDeclarations, +} from '@/components/sourceSelectUtils'; import { IS_PROMQL_ENABLED } from '@/config'; import { useSources } from '@/source'; @@ -44,6 +53,7 @@ export const AdhocFilterEditForm = ({ otherFilters, }: AdhocFilterEditFormProps) => { const { data: allSources } = useSources(); + const sourceVariables = useSourceVariableDeclarations(); const [sourceType, sourceIds, appliesToSourceIds] = useWatch({ control, name: ['sourceType', 'sources', 'appliesToSourceIds'], @@ -64,14 +74,26 @@ export const AdhocFilterEditForm = ({ ), ); }, [otherFilters, sourceType, sourceIds, appliesToSourceIds]); - const allowedSourceKinds = getAdhocFilterSourceKinds(sourceType); - const tableConnections = useMemo( - () => - (allSources ?? []) - .filter(source => sourceIds?.includes(source.id)) - .map(tcFromSource), - [allSources, sourceIds], + const allowedSourceKinds = useMemo( + () => getAdhocFilterSourceKinds(sourceType), + [sourceType], ); + const referenceVariableValues = useReferenceVariableValues(); + const tableConnections = useMemo(() => { + const resolvedIds = new Set( + sourceIds?.map(id => + resolveVariableReference(id, referenceVariableValues), + ), + ); + // A data source variable can select a source of a kind this filter can't use + return (allSources ?? []) + .filter( + source => + resolvedIds.has(source.id) && + allowedSourceKinds.includes(source.kind), + ) + .map(tcFromSource); + }, [allSources, sourceIds, referenceVariableValues, allowedSourceKinds]); // Kept visible for a saved PromQL filter so its source type can be changed const showSourceType = sourceType === 'promql' || @@ -82,6 +104,13 @@ export const AdhocFilterEditForm = ({ // hold after switching from another filter type. const validateSourceKinds = (ids: string[] | undefined) => { const hasOtherKind = ids?.some(id => { + if (parseVariableReference(id) != null) { + return !isSourceVariableReferenceAccepted( + id, + sourceVariables, + allowedSourceKinds, + ); + } const source = allSources?.find(s => s.id === id); return source && !allowedSourceKinds.includes(source.kind); }); @@ -131,6 +160,7 @@ export const AdhocFilterEditForm = ({ comboboxProps={{ withinPortal: true }} placeholder="Select sources" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables rules={{ validate: (value: string[] | undefined) => !value?.length @@ -173,6 +203,7 @@ export const AdhocFilterEditForm = ({ comboboxProps={{ withinPortal: true }} placeholder="Same as data sources" allowedSourceKinds={allowedSourceKinds} + allowSourceVariables rules={{ validate: validateSourceKinds }} /> diff --git a/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx index f1a384dd6..cb8c5d784 100644 --- a/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/DashboardFilterEditForm.tsx @@ -3,6 +3,7 @@ import { useForm, useWatch } from 'react-hook-form'; import { deriveVariableName, getFilterVariableName, + isReferenceVariableFilterType, } from '@hyperdx/common-utils/dist/filters'; import { ChartVariable, @@ -33,6 +34,7 @@ import { useZIndex } from '@/zIndex'; import { AdhocFilterEditForm } from './AdhocFilterEditForm'; import { MODAL_SIZE } from './constants'; import { CustomInputWrapper } from './CustomInputWrapper'; +import { DataSourceFilterEditForm } from './DataSourceFilterEditForm'; import { FilterFormValues, toFormValues, @@ -41,6 +43,7 @@ import { import { PromqlLabelFilterEditForm } from './PromqlLabelFilterEditForm'; import { QueryExpressionFilterEditForm } from './QueryExpressionFilterEditForm'; import { StaticListFilterEditForm } from './StaticListFilterEditForm'; +import { VariableNameInput } from './VariableNameInput'; const FILTER_TYPE_OPTIONS = [ { @@ -64,6 +67,8 @@ const FILTER_TYPE_OPTIONS = [ }, ] : []), + { value: DashboardFilterType.enum.DATA_SOURCE, label: 'Data source' }, + { value: DashboardFilterType.enum.CONNECTION, label: 'Connection' }, ]; interface DashboardFilterEditFormProps { @@ -184,9 +189,30 @@ export const DashboardFilterEditForm = ({ return variables?.filter(variable => variable.name !== ownName); }, [variables, filter]); + // Ad hoc conditions and reference variables have fixed selection rules. + // Reference variables are always required, so only the global choice is left. + const isReferenceVariable = isReferenceVariableFilterType(formFilterType); + const showSelectionOptions = + showRequiredFilterOptions && + formFilterType !== 'ADHOC' && + !isReferenceVariable; + const showGlobalRequirementOption = + showRequiredFilterOptions && (isReferenceVariable || !!isRequired); + const isNew = !filter; const showTypeInput = !!showVariableOptions; + const globalRequirementCheckbox = ( + + ); + return ( - {formFilterType === 'STATIC_LIST' ? ( + {formFilterType === 'CONNECTION' ? ( + + ) : formFilterType === 'DATA_SOURCE' ? ( + + ) : formFilterType === 'STATIC_LIST' ? ( - {showRequiredFilterOptions && formFilterType !== 'ADHOC' && ( + {showSelectionOptions && ( - {!!isRequired && ( - - - + {showGlobalRequirementOption && ( + {globalRequirementCheckbox} )} )} + {isReferenceVariable && showGlobalRequirementOption && ( + + + {globalRequirementCheckbox} + + )} {formState.errors.root && ( sources?.find(s => s.id === id)?.name) + .map(id => getObjectName(id, sources)) .filter((name): name is string => !!name) .join(', '); } @@ -63,19 +68,20 @@ function getSourceNames( function getValuesAttribute( filter: DashboardFilter, sources?: { id: string; name: string }[], + connections?: { id: string; name: string }[], ): DashboardFilterAttribute { switch (filter.type) { case 'QUERY_EXPRESSION': return { icon: , tooltip: 'Source the dropdown values are queried from', - label: sources?.find(s => s.id === filter.source)?.name ?? '', + label: getObjectName(filter.source, sources) ?? '', }; case 'PROMETHEUS_LABEL': return { icon: , tooltip: 'PromQL source and label the dropdown values come from', - label: [sources?.find(s => s.id === filter.source)?.name, filter.label] + label: [getObjectName(filter.source, sources), filter.label] .filter(Boolean) .join(' · '), }; @@ -98,6 +104,25 @@ function getValuesAttribute( tooltip: 'The dropdown values come from a SQL query', label: 'SQL query', }; + case 'DATA_SOURCE': + return { + icon: , + tooltip: + 'Kinds of sources offered, and the connection they are limited to', + label: [ + filter.allowedSourceKinds + .map(kind => SOURCE_KIND_LABELS[kind]) + .join(', '), + filter.connection && getObjectName(filter.connection, connections), + ] + .filter(Boolean) + .join(' · '), + }; + case 'CONNECTION': + return { + icon: , + label: 'Connections', + }; default: filter satisfies never; // exhaustive check return { icon: , label: '' }; @@ -129,6 +154,7 @@ export const DashboardFiltersList = ({ onAddNew, }: DashboardFiltersListProps) => { const { data: sources } = useSources(); + const { data: connections } = useConnections(); return ( {filters.map(filter => { - const attributes = [getValuesAttribute(filter, sources)]; + const attributes = [getValuesAttribute(filter, sources, connections)]; const broadcastTarget = getBroadcastTargetDisplay(filter, sources); if (!hideAppliesTo && broadcastTarget != null) { diff --git a/packages/app/src/components/DashboardFiltersModal/DataSourceFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/DataSourceFilterEditForm.tsx new file mode 100644 index 000000000..b92e553a1 --- /dev/null +++ b/packages/app/src/components/DashboardFiltersModal/DataSourceFilterEditForm.tsx @@ -0,0 +1,100 @@ +import { Controller, useFormState, useWatch } from 'react-hook-form'; +import { DashboardFilter, SourceKind } from '@hyperdx/common-utils/dist/types'; +import { Alert, Group, MultiSelect } from '@mantine/core'; +import { IconAlertTriangle } from '@tabler/icons-react'; + +import { getInterchangeableSourceKind } from '@/components/ChartEditor/utils'; +import { ConnectionSelectControlled } from '@/components/ConnectionSelect'; +import { SOURCE_KIND_LABELS } from '@/components/Sources/SourceForm/constants'; +import { SOURCE_KIND_ICONS } from '@/components/sourceSelectUtils'; +import { IS_PROMQL_ENABLED } from '@/config'; + +import { CustomInputWrapper } from './CustomInputWrapper'; +import { FilterFormControl } from './filterFormState'; +import { VariableNameInput } from './VariableNameInput'; + +const SOURCE_KIND_OPTIONS = Object.values(SourceKind) + .filter(kind => IS_PROMQL_ENABLED || kind !== SourceKind.Promql) + .map(kind => ({ value: kind, label: SOURCE_KIND_LABELS[kind] })); + +interface DataSourceFilterEditFormProps { + control: FilterFormControl; + /** Filters other than the one being edited, used to keep variable names unique. */ + otherFilters: DashboardFilter[]; +} + +/** Form for editing a variable whose value is a source. */ +export const DataSourceFilterEditForm = ({ + control, + otherFilters, +}: DataSourceFilterEditFormProps) => { + const { errors } = useFormState({ control }); + const allowedSourceKinds = useWatch({ control, name: 'allowedSourceKinds' }); + const hasMixedKinds = + (allowedSourceKinds?.length ?? 0) > 1 && + getInterchangeableSourceKind(allowedSourceKinds) == null; + + return ( + <> + + + (value?.length ?? 0) > 0 || 'Select at least one source kind', + }} + render={({ field: { onChange, value } }) => ( + ( + + {SOURCE_KIND_ICONS[option.value]} + {option.label} + + )} + /> + )} + /> + + + + + + + {hasMixedKinds && ( + } + data-testid="filter-mixed-source-kinds-warning" + > + These kinds support different chart options, such as metrics and + formulas. A tile built while one kind is selected may not load when + the variable is switched to another, and a new tile can't be + saved until a source is selected. + + )} + + + + ); +}; diff --git a/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx index bb3d90a8f..32092ff43 100644 --- a/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/PromqlLabelFilterEditForm.tsx @@ -8,6 +8,7 @@ import { import { AutocompleteControlled } from '@/components/InputControlled'; import PromQLEditor from '@/components/PromQLEditor/PromQLEditor'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { usePromqlLabelNames, usePromqlMetricNames, @@ -42,7 +43,7 @@ export const PromqlLabelFilterEditForm = ({ // Only a PromQL source can answer the label lookup; the form may briefly hold // another kind while the user switches types. - const sourceId = useWatch({ control, name: 'source' }); + const sourceId = useResolvedReference(useWatch({ control, name: 'source' })); const source = sources?.find(s => s.id === sourceId); const promqlSource = source && isPromqlSource(source) ? source : undefined; const { data: labelNames } = usePromqlLabelNames(promqlSource?.id); @@ -64,6 +65,7 @@ export const PromqlLabelFilterEditForm = ({ }} comboboxProps={{ withinPortal: true }} allowedSourceKinds={[SourceKind.Promql]} + allowSourceVariables /> diff --git a/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx b/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx index 8d88a40b0..a806135d4 100644 --- a/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx +++ b/packages/app/src/components/DashboardFiltersModal/QueryExpressionFilterEditForm.tsx @@ -27,6 +27,7 @@ import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from '@/components/SourceSchemaPreview'; import { SourceSelectControlled } from '@/components/SourceSelect'; +import { useResolvedReference } from '@/components/sourceSelectUtils'; import { SQLInlineEditorControlled } from '@/components/SQLEditor/SQLInlineEditor'; import { useSource } from '@/source'; import { getMetricTableName } from '@/utils'; @@ -60,7 +61,11 @@ export const QueryExpressionFilterEditForm = ({ showVariableOptions, }: QueryExpressionFilterEditFormProps) => { const sourceId = useWatch({ control, name: 'source' }); - const { data: source } = useSource({ id: sourceId }); + // A data source variable can select a source of a kind this filter can't use + const { data: source } = useSource({ + id: useResolvedReference(sourceId), + kinds: QUERY_EXPRESSION_FILTER_SOURCE_KINDS, + }); const metricType = useWatch({ control, name: 'sourceMetricType' }); const tableName = source && getMetricTableName(source, metricType); @@ -137,6 +142,7 @@ export const QueryExpressionFilterEditForm = ({ isSchemaPreviewEnabled={isSourceSchemaPreviewEnabled(source)} disabled={!!presetSource} allowedSourceKinds={QUERY_EXPRESSION_FILTER_SOURCE_KINDS} + allowSourceVariables /> diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx b/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx index 91d55296f..04b1d99c6 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/DashboardFiltersModal.test.tsx @@ -12,6 +12,7 @@ import { FilterFormControl } from '@/components/DashboardFiltersModal/filterForm jest.mock('@/useConfirm', () => ({ useConfirm: () => jest.fn() })); jest.mock('@/source', () => ({ useSources: () => ({ data: [] }) })); +jest.mock('@/connection', () => ({ useConnections: () => ({ data: [] }) })); // Mantine's Combobox calls scrollIntoView when its dropdown opens; jsdom lacks it. window.HTMLElement.prototype.scrollIntoView = jest.fn(); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/DataSourceFilterEditForm.test.tsx b/packages/app/src/components/DashboardFiltersModal/__tests__/DataSourceFilterEditForm.test.tsx new file mode 100644 index 000000000..6df2ba9be --- /dev/null +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/DataSourceFilterEditForm.test.tsx @@ -0,0 +1,84 @@ +import { useForm } from 'react-hook-form'; +import { SourceKind } from '@hyperdx/common-utils/dist/types'; +import { screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; + +import { DataSourceFilterEditForm } from '@/components/DashboardFiltersModal/DataSourceFilterEditForm'; +import { + FilterFormValues, + toFormValues, + toSavedFilter, +} from '@/components/DashboardFiltersModal/filterFormState'; + +jest.mock('@/connection', () => ({ + useConnections: () => ({ data: [{ id: 'conn-1', name: 'Primary' }] }), +})); + +function Harness({ + allowedSourceKinds, + connection, + onSave, +}: { + allowedSourceKinds: SourceKind[]; + connection?: string; + onSave?: (values: FilterFormValues) => void; +}) { + const { control, getValues } = useForm({ + defaultValues: { + ...toFormValues(), + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds, + connection, + }, + }); + return ( + <> + + + + ); +} + +const warning = () => screen.queryByTestId('filter-mixed-source-kinds-warning'); + +describe('DataSourceFilterEditForm', () => { + it('warns when the kinds support different chart options', () => { + renderWithMantine( + , + ); + expect(warning()).toBeInTheDocument(); + }); + + it('does not warn for kinds that charts treat alike', () => { + renderWithMantine( + , + ); + expect(warning()).not.toBeInTheDocument(); + }); + + it('saves no connection once the connection is cleared', async () => { + const onSave = jest.fn(); + renderWithMantine( + , + ); + + const input = screen.getByTestId('filter-data-source-connection-input'); + expect(input).toHaveValue('Primary'); + const clearButton = input.parentElement?.querySelector('button'); + if (!clearButton) throw new Error('Expected a clear button'); + await userEvent.click(clearButton); + expect(input).toHaveValue(''); + await userEvent.click(screen.getByRole('button', { name: 'Save' })); + + expect(toSavedFilter(onSave.mock.calls[0][0])).toMatchObject({ + connection: undefined, + }); + }); +}); diff --git a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts index 63e0497c8..172959493 100644 --- a/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts +++ b/packages/app/src/components/DashboardFiltersModal/__tests__/filterFormState.test.ts @@ -1,4 +1,4 @@ -import { DashboardFilter } from '@hyperdx/common-utils/dist/types'; +import { DashboardFilter, SourceKind } from '@hyperdx/common-utils/dist/types'; import { FilterFormValues, @@ -318,6 +318,74 @@ describe('toSavedFilter', () => { ).toThrow(); }); + it('saves a data source filter as single-select and required', () => { + const saved = toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + isRequired: false, + isSingleSelect: false, + expression: 'ignored', + source: 'ignored', + }), + ); + + expect(saved).toEqual({ + id: expect.any(String), + type: 'DATA_SOURCE', + name: 'Logs source', + variableName: 'Logs_source', + allowedSourceKinds: [SourceKind.Log], + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }); + expect(toFormValues(saved).allowedSourceKinds).toEqual([SourceKind.Log]); + }); + + it('saves a data source filter limited to a connection variable', () => { + expect( + toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Logs source', + allowedSourceKinds: [SourceKind.Log], + connection: '$conn', + }), + ), + ).toMatchObject({ connection: '$conn' }); + }); + + it('saves a connection filter as single-select and required', () => { + const saved = toSavedFilter( + formValues({ + type: 'CONNECTION', + name: 'Cluster', + isSingleSelect: false, + source: 'ignored', + }), + ); + + expect(saved).toEqual({ + id: expect.any(String), + type: 'CONNECTION', + name: 'Cluster', + variableName: 'Cluster', + minSelections: 1, + maxSelections: 1, + isBroadcastEnabled: false, + isVariableEnabled: true, + }); + }); + + it('rejects a data source filter without source kinds', () => { + expect(() => + toSavedFilter(formValues({ type: 'DATA_SOURCE', name: 'Source' })), + ).toThrow(); + }); + it('rejects values the schema cannot accept', () => { expect(() => toSavedFilter(formValues({ type: 'STATIC_LIST', options: [] })), @@ -325,9 +393,15 @@ describe('toSavedFilter', () => { }); }); -/** The minimum a form needs to save, per filter type the form supports. */ +/** + * The minimum a form needs to save, per filter type with configurable + * selection limits. + */ const byType: Record< - Exclude, + Exclude< + DashboardFilter['type'], + 'ADHOC' | 'SQL_QUERY' | 'DATA_SOURCE' | 'CONNECTION' + >, Partial > = { QUERY_EXPRESSION: { @@ -432,6 +506,36 @@ describe('isGlobalRequirement', () => { ).not.toHaveProperty('isGlobalRequirement'); }, ); + + // Reference variables are always required, so the form has no "Required" + // checkbox for them to gate the requirement's scope. + it('round-trips a dashboard-wide data source requirement without isRequired', () => { + const saved = toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Source', + allowedSourceKinds: [SourceKind.Log], + isRequired: false, + isGlobalRequirement: true, + }), + ); + + expect(saved).toMatchObject({ isGlobalRequirement: true }); + expect(toFormValues(saved).isGlobalRequirement).toBe(true); + }); + + it('emits no key for a data source filter that blocks only its own tiles', () => { + expect( + toSavedFilter( + formValues({ + type: 'DATA_SOURCE', + name: 'Source', + allowedSourceKinds: [SourceKind.Log], + isGlobalRequirement: false, + }), + ), + ).not.toHaveProperty('isGlobalRequirement'); + }); }); describe('maxSelections', () => { diff --git a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts index 7b681fe2f..caa45a695 100644 --- a/packages/app/src/components/DashboardFiltersModal/filterFormState.ts +++ b/packages/app/src/components/DashboardFiltersModal/filterFormState.ts @@ -5,11 +5,13 @@ import { isFilterGlobalRequirement, isFilterRequired, isFilterVariableEnabled, + isReferenceVariableFilterType, } from '@hyperdx/common-utils/dist/filters'; import { AdhocDashboardFilter, DashboardFilter, DashboardFilterSchema, + DataSourceDashboardFilter, PromqlLabelDashboardFilter, QueryExpressionDashboardFilter, StaticListDashboardFilter, @@ -53,7 +55,8 @@ export type FilterFormValues = { | 'isGlobalRequirement' | 'maxSelections' > & - Pick; + Pick & + Pick; export type FilterFormControl = Control; @@ -65,6 +68,7 @@ export const toFormValues = ( const staticList = filter?.type === 'STATIC_LIST' ? filter : undefined; const promqlLabel = filter?.type === 'PROMETHEUS_LABEL' ? filter : undefined; const adhoc = filter?.type === 'ADHOC' ? filter : undefined; + const dataSource = filter?.type === 'DATA_SOURCE' ? filter : undefined; return { id: filter?.id ?? crypto.randomUUID(), @@ -100,6 +104,10 @@ export const toFormValues = ( // ADHOC fields sourceType: adhoc?.sourceType ?? 'sql', sources: adhoc?.sources ?? [], + + // DATA_SOURCE fields + allowedSourceKinds: dataSource?.allowedSourceKinds ?? [], + connection: dataSource?.connection, }; }; @@ -140,6 +148,28 @@ export const toSavedFilter = (values: FilterFormValues): DashboardFilter => { }); } + // Reference variables are always single-select and required, so only the + // global requirement checkbox is consulted + if (isReferenceVariableFilterType(values.type)) { + return DashboardFilterSchema.parse({ + id: values.id, + type: values.type, + name: values.name, + ...(values.type === 'DATA_SOURCE' + ? { + allowedSourceKinds: values.allowedSourceKinds, + connection: values.connection || undefined, + } + : {}), + minSelections: 1, + maxSelections: 1, + ...(isGlobalRequirement ? { isGlobalRequirement: true } : {}), + isBroadcastEnabled: false, + isVariableEnabled: true, + variableName: getFilterVariableName(values), + }); + } + const appliesTo = values.appliesToSourceIds?.filter(id => !!id?.length); const trimmedWhere = values.where?.trim() ?? ''; const whereFields = { diff --git a/packages/app/src/components/ReferenceVariableDashboardFilter.tsx b/packages/app/src/components/ReferenceVariableDashboardFilter.tsx new file mode 100644 index 000000000..0f163c5f1 --- /dev/null +++ b/packages/app/src/components/ReferenceVariableDashboardFilter.tsx @@ -0,0 +1,188 @@ +import { useCallback, useMemo } from 'react'; +import { isSourceOfferedByVariable } from '@hyperdx/common-utils/dist/referenceVariables'; +import { + ConnectionDashboardFilter as ConnectionFilter, + DataSourceDashboardFilter as DataSourceFilter, + TSource, +} from '@hyperdx/common-utils/dist/types'; +import { + Center, + CheckIcon, + ComboboxItem, + Group, + Select, + Stack, + Text, +} from '@mantine/core'; +import { IconServer, IconStack } from '@tabler/icons-react'; + +import { isValueInSelectData } from '@/components/SelectControlled'; +import { + getSourceOptionIcon, + sourceSelectFilter, + SourceSelectGroup, + useFilteredSortedSourceItems, + useSourceKindMap, +} from '@/components/sourceSelectUtils'; +import { useConnectionItems } from '@/hooks/useConnectionItems'; +import { useSources } from '@/source'; + +import { + DashboardFilterLabel, + FilterCaution, + FilterEffect, + getPendingVariablesTooltip, +} from './DashboardFilterLabel'; + +import sourceSelectStyles from '@styles/SourceSelectControlled.module.scss'; + +type ReferenceVariableFilterProps = { + value: string | undefined; + onChange: (id: string | undefined) => void; + effect: FilterEffect; + requiredTooltip: string; +}; + +/** + * The filter bar control shared by data source and connection variables: a + * single picker over the IDs the variable can select. + */ +function ReferenceVariableSelect({ + name, + items, + value, + onChange, + effect, + requiredTooltip, + pendingVariables, + placeholder, + renderIcon, +}: ReferenceVariableFilterProps & { + name: string; + items: ComboboxItem[] | SourceSelectGroup[]; + pendingVariables?: string[]; + placeholder: string; + renderIcon: (value: string | null) => React.ReactNode; +}) { + // A selection that is no longer offered (deleted, disabled, or no longer + // allowed by the variable) shows as empty, so it reads as unselected. + const isOffered = useMemo( + () => isValueInSelectData(items, value), + [items, value], + ); + const selected = value && isOffered ? value : null; + + const renderOption = useCallback( + ({ option, checked }: { option: ComboboxItem; checked?: boolean }) => ( + + {checked ? ( +
+ +
+ ) : ( + renderIcon(option.value) + )} + {option.label} +
+ ), + [renderIcon], + ); + + return ( + + + {selected == null && ( + + )} + {!!pendingVariables?.length && ( + + )} + +