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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions .changeset/source-variable-text-references.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@hyperdx/common-utils': minor
'@hyperdx/app': minor
'@hyperdx/api': minor
---

feat: Reference DATA_SOURCE and CONNECTION dashboard variables in text
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ jest.mock('@/mcp/tools/dashboards/variables', () => {
return {
...actual,
getReferenceTargets: () =>
Promise.resolve({ sources: [], connectionIds: new Set() }),
Promise.resolve({ sources: [], connections: [] }),
};
});

Expand Down
186 changes: 157 additions & 29 deletions packages/api/src/mcp/__tests__/dashboards/variables.test.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
import { SourceKind } from '@hyperdx/common-utils/dist/types';
import { substituteVariables } from '@hyperdx/common-utils/dist/variables';
import { fromAny } from '@total-typescript/shoehorn';
import mongoose from 'mongoose';

import {
type McpVariableValues,
type ReferenceTargets,
resolveDashboardVariables,
resolveTileVariableReferences,
withResolvedFilterVariableNames,
} from '@/mcp/tools/dashboards/variables';
import type { ExternalDashboard } from '@/routers/external-api/v2/utils/dashboards';
import type {
ExternalDashboardFilterWithId,
ExternalDashboardTileWithId,
} from '@/utils/zod';

const sourceId = new mongoose.Types.ObjectId().toString();

const NO_TARGETS: ReferenceTargets = { sources: [], connections: [] };

function filter(
overrides: Partial<ExternalDashboardFilterWithId> = {},
): ExternalDashboardFilterWithId {
Expand Down Expand Up @@ -58,31 +63,42 @@ describe('resolveDashboardVariables', () => {
// $__conditionalAll as macros, so a tile using one against a dashboard
// that declares nothing fails with a message about the variable rather
// than leaking macro text into ClickHouse.
expect(resolveDashboardVariables(undefined, undefined)).toEqual({
expect(resolveDashboardVariables({}, undefined, NO_TARGETS)).toEqual({
variables: [],
});
expect(resolveDashboardVariables([], undefined)).toEqual({
expect(
resolveDashboardVariables({ filters: [] }, undefined, NO_TARGETS),
).toEqual({
variables: [],
});
});

it('declares nothing for a broadcast-only filter', () => {
expect(resolveDashboardVariables([filter()], undefined)).toEqual({
expect(
resolveDashboardVariables({ filters: [filter()] }, undefined, NO_TARGETS),
).toEqual({
variables: [],
});
});

it('defaults every declared variable to an empty selection', () => {
expect(resolveDashboardVariables([variableFilter], undefined)).toEqual({
expect(
resolveDashboardVariables(
{ filters: [variableFilter] },
undefined,
NO_TARGETS,
),
).toEqual({
variables: [{ name: 'service', expression: 'ServiceName', values: [] }],
});
});

it('applies a supplied selection', () => {
expect(
resolveDashboardVariables(
[variableFilter],
{ filters: [variableFilter] },
[{ name: 'service', values: ['checkout'] }],
NO_TARGETS,
),
).toEqual({
variables: [
Expand All @@ -101,8 +117,9 @@ describe('resolveDashboardVariables', () => {
});

const resolved = resolveDashboardVariables(
[variableFilter, env],
{ filters: [variableFilter, env] },
[{ name: 'service', values: ['checkout'] }],
NO_TARGETS,
);

expect(resolved).toEqual({
Expand All @@ -115,8 +132,9 @@ describe('resolveDashboardVariables', () => {

it('rejects a name the dashboard does not declare', () => {
const resolved = resolveDashboardVariables(
[variableFilter],
{ filters: [variableFilter] },
[{ name: 'tenant', values: ['acme'] }],
NO_TARGETS,
);

expect(resolved).toHaveProperty('error');
Expand All @@ -127,8 +145,9 @@ describe('resolveDashboardVariables', () => {

it('lists (none) when the dashboard declares no variables at all', () => {
const resolved = resolveDashboardVariables(
[filter()],
{ filters: [filter()] },
[{ name: 'service', values: ['checkout'] }],
NO_TARGETS,
);

if (!('error' in resolved)) throw new Error('expected an error');
Expand All @@ -137,8 +156,9 @@ describe('resolveDashboardVariables', () => {

it('rejects several values for a single-select variable', () => {
const resolved = resolveDashboardVariables(
[staticFilter({ maxSelections: 1 })],
{ filters: [staticFilter({ maxSelections: 1 })] },
[{ name: 'env', values: ['prod', 'staging'] }],
NO_TARGETS,
);

if (!('error' in resolved)) throw new Error('expected an error');
Expand All @@ -149,8 +169,9 @@ describe('resolveDashboardVariables', () => {
it('applies one value to a single-select variable', () => {
expect(
resolveDashboardVariables(
[staticFilter({ maxSelections: 1 })],
{ filters: [staticFilter({ maxSelections: 1 })] },
[{ name: 'env', values: ['prod'] }],
NO_TARGETS,
),
).toEqual({
variables: [
Expand All @@ -165,16 +186,23 @@ describe('resolveDashboardVariables', () => {
});

it('declares a variable for a static filter', () => {
expect(resolveDashboardVariables([staticFilter()], undefined)).toEqual({
expect(
resolveDashboardVariables(
{ filters: [staticFilter()] },
undefined,
NO_TARGETS,
),
).toEqual({
variables: [{ name: 'env', expression: undefined, values: [] }],
});
});

it('applies a selection within a static filter options', () => {
expect(
resolveDashboardVariables(
[staticFilter()],
{ filters: [staticFilter()] },
[{ name: 'env', values: ['prod', 'dev'] }],
NO_TARGETS,
),
).toEqual({
variables: [
Expand All @@ -186,8 +214,9 @@ describe('resolveDashboardVariables', () => {
it('accepts an empty selection for a static filter', () => {
expect(
resolveDashboardVariables(
[staticFilter()],
{ filters: [staticFilter()] },
[{ name: 'env', values: [] }],
NO_TARGETS,
),
).toEqual({
variables: [{ name: 'env', expression: undefined, values: [] }],
Expand All @@ -196,8 +225,9 @@ describe('resolveDashboardVariables', () => {

it('rejects a value outside a static filter options', () => {
const resolved = resolveDashboardVariables(
[staticFilter()],
{ filters: [staticFilter()] },
[{ name: 'env', values: ['prod', 'prod-2'] }],
NO_TARGETS,
);

if (!('error' in resolved)) throw new Error('expected an error');
Expand All @@ -215,11 +245,12 @@ describe('resolveDashboardVariables', () => {
});

const resolved = resolveDashboardVariables(
[staticFilter(), tier],
{ filters: [staticFilter(), tier] },
[
{ name: 'env', values: ['nope'] },
{ name: 'tier', values: ['enterprise'] },
],
NO_TARGETS,
);

if (!('error' in resolved)) throw new Error('expected an error');
Expand All @@ -230,8 +261,9 @@ describe('resolveDashboardVariables', () => {
it('leaves query-expression variables unconstrained', () => {
expect(
resolveDashboardVariables(
[variableFilter],
{ filters: [variableFilter] },
[{ name: 'service', values: ['anything-at-all'] }],
NO_TARGETS,
),
).toEqual({
variables: [
Expand All @@ -247,8 +279,9 @@ describe('resolveDashboardVariables', () => {
it('truncates the options preview in the error', () => {
const options = Array.from({ length: 25 }, (_, i) => `opt${i}`);
const resolved = resolveDashboardVariables(
[staticFilter({ options })],
{ filters: [staticFilter({ options })] },
[{ name: 'env', values: ['nope'] }],
NO_TARGETS,
);

if (!('error' in resolved)) throw new Error('expected an error');
Expand All @@ -260,8 +293,9 @@ describe('resolveDashboardVariables', () => {
const shadowed = staticFilter({ variableName: 'service' });
expect(
resolveDashboardVariables(
[variableFilter, shadowed],
{ filters: [variableFilter, shadowed] },
[{ name: 'service', values: ['not-an-option'] }],
NO_TARGETS,
),
).toEqual({
variables: [
Expand All @@ -276,11 +310,12 @@ describe('resolveDashboardVariables', () => {

it('lets the last entry win on a repeated name', () => {
const resolved = resolveDashboardVariables(
[variableFilter],
{ filters: [variableFilter] },
[
{ name: 'service', values: ['a'] },
{ name: 'service', values: ['b'] },
],
NO_TARGETS,
);

expect(resolved).toEqual({
Expand Down Expand Up @@ -330,6 +365,14 @@ describe('withResolvedFilterVariableNames', () => {
});
});

const target = (id: string, kind: SourceKind, connection: string) => ({
id,
kind,
connection,
name: `${kind} source`,
from: { databaseName: 'default', tableName: `${kind}_table` },
});

describe('resolveTileVariableReferences', () => {
const objectId = () => new mongoose.Types.ObjectId().toString();
const connectionId = objectId();
Expand All @@ -341,17 +384,16 @@ describe('resolveTileVariableReferences', () => {
const otherConnectionLogSourceId = objectId();
const targets: ReferenceTargets = {
sources: [
{ id: traceSourceId, kind: SourceKind.Trace, connection: connectionId },
{ id: logSourceId, kind: SourceKind.Log, connection: connectionId },
{ id: metricSourceId, kind: SourceKind.Metric, connection: connectionId },
{ id: promqlSourceId, kind: SourceKind.Promql, connection: connectionId },
{
id: otherConnectionLogSourceId,
kind: SourceKind.Log,
connection: otherConnectionId,
},
target(traceSourceId, SourceKind.Trace, connectionId),
target(logSourceId, SourceKind.Log, connectionId),
target(metricSourceId, SourceKind.Metric, connectionId),
target(promqlSourceId, SourceKind.Promql, connectionId),
target(otherConnectionLogSourceId, SourceKind.Log, otherConnectionId),
],
connections: [
{ id: connectionId, name: 'Main' },
{ id: otherConnectionId, name: 'Other' },
],
connectionIds: new Set([connectionId, otherConnectionId]),
};

const referenceVariableFields = {
Expand Down Expand Up @@ -608,3 +650,89 @@ describe('resolveTileVariableReferences', () => {
});
});
});

describe('resolveDashboardVariables with data source and connection variables', () => {
const objectId = () => new mongoose.Types.ObjectId().toString();
const connectionId = objectId();
const logSourceId = objectId();
const traceSourceId = objectId();
const targets: ReferenceTargets = {
sources: [
target(logSourceId, SourceKind.Log, connectionId),
target(traceSourceId, SourceKind.Trace, connectionId),
],
connections: [{ id: connectionId, name: 'Main' }],
};
const filters: ExternalDashboardFilterWithId[] = [
{
id: objectId(),
type: 'DATA_SOURCE',
name: 'Source',
variableName: 'src',
allowedSourceKinds: [SourceKind.Log],
minSelections: 1,
maxSelections: 1,
isBroadcastEnabled: false,
isVariableEnabled: true,
},
{
id: objectId(),
type: 'CONNECTION',
name: 'Connection',
variableName: 'conn',
minSelections: 1,
maxSelections: 1,
isBroadcastEnabled: false,
isVariableEnabled: true,
},
];

const expand = (
variableValues: McpVariableValues | undefined,
savedFilterValues: ExternalDashboard['savedFilterValues'] = undefined,
) => {
const resolved = resolveDashboardVariables(
{ filters, savedFilterValues },
variableValues,
targets,
);
if ('error' in resolved) throw new Error(resolved.error);
return substituteVariables('SELECT ${conn.name} FROM $src', {
variables: resolved.variables,
inputLanguage: 'sql',
});
};

it('expands text references to the selected source and connection', () => {
expect(
expand([
{ name: 'src', values: [logSourceId] },
{ name: 'conn', values: [connectionId] },
]),
).toBe("SELECT 'Main' FROM `default`.`log_table`");
});

it('falls back to the saved selection', () => {
expect(
expand(undefined, [
{ type: 'variable', name: 'src', values: [logSourceId] },
]),
).toBe('SELECT FROM `default`.`log_table`');
});

it('expands a selection the variable would not offer to nothing', () => {
expect(expand([{ name: 'src', values: [traceSourceId] }])).toBe(
'SELECT FROM ',
);
});

it('still rejects an unknown variable name', () => {
expect(
resolveDashboardVariables(
{ filters, savedFilterValues: undefined },
[{ name: 'nope', values: ['x'] }],
targets,
),
).toEqual({ error: expect.stringContaining('nope') });
});
});
Loading
Loading