dashboardImport.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. import {Client} from 'sentry/api';
  2. import {getQuerySymbol} from 'sentry/components/metrics/querySymbol';
  3. import type {Organization} from 'sentry/types';
  4. import type {MetricMeta, MRI} from 'sentry/types/metrics';
  5. import {convertToDashboardWidget} from 'sentry/utils/metrics/dashboard';
  6. import {hasMetricsNewInputs} from 'sentry/utils/metrics/features';
  7. import type {MetricsQuery} from 'sentry/utils/metrics/types';
  8. import {MetricDisplayType} from 'sentry/utils/metrics/types';
  9. import type {Widget} from 'sentry/views/dashboards/types';
  10. // import types
  11. export type ImportDashboard = {
  12. description: string;
  13. title: string;
  14. widgets: ImportWidget[];
  15. };
  16. export type ImportWidget = {
  17. definition: WidgetDefinition;
  18. id: number;
  19. };
  20. type WidgetDefinition = {
  21. query: string;
  22. title: string;
  23. type: string;
  24. widgets: ImportWidget[];
  25. legend_columns?: ('avg' | 'max' | 'min' | 'sum' | 'value')[];
  26. requests?: Request[];
  27. };
  28. type Request = {
  29. display_type: 'area' | 'bars' | 'line';
  30. formulas: Formula[];
  31. queries: {
  32. data_source: string;
  33. name: string;
  34. query: string;
  35. }[];
  36. response_format: 'note' | 'timeseries';
  37. style?: {
  38. line_type: 'dotted' | 'solid';
  39. };
  40. };
  41. type Formula = {
  42. formula: string;
  43. alias?: string;
  44. };
  45. type MetricWidgetReport = {
  46. errors: string[];
  47. id: number;
  48. outcome: ImportOutcome;
  49. title: string;
  50. }[];
  51. type ImportOutcome = 'success' | 'warning' | 'error';
  52. export type ParseResult = {
  53. description: string;
  54. report: MetricWidgetReport;
  55. title: string;
  56. widgets: Widget[];
  57. };
  58. export async function parseDashboard(
  59. dashboard: ImportDashboard,
  60. availableMetrics: MetricMeta[],
  61. organization: Organization
  62. ): Promise<ParseResult> {
  63. const metricsNewInputs = hasMetricsNewInputs(organization);
  64. const {widgets = []} = dashboard;
  65. const flatWidgets = widgets.flatMap(widget => {
  66. if (widget.definition.type === 'group') {
  67. return widget.definition.widgets;
  68. }
  69. return [widget];
  70. });
  71. const results = await Promise.all(
  72. flatWidgets.map(widget => {
  73. const parser = new WidgetParser(
  74. widget,
  75. availableMetrics,
  76. organization.slug,
  77. metricsNewInputs
  78. );
  79. return parser.parse();
  80. })
  81. );
  82. return {
  83. title: dashboard.title,
  84. description: dashboard.description,
  85. widgets: results.map(r => r.widget).filter(Boolean) as Widget[],
  86. report: results.flatMap(r => r.report),
  87. };
  88. }
  89. const SUPPORTED_COLUMNS = new Set(['avg', 'max', 'min', 'sum', 'value']);
  90. const SUPPORTED_WIDGET_TYPES = new Set(['timeseries']);
  91. const METRIC_SUFFIX_TO_AGGREGATION = {
  92. avg: 'avg',
  93. max: 'max',
  94. min: 'min',
  95. sum: 'sum',
  96. count: 'count',
  97. '50percentile': 'p50',
  98. '75percentile': 'p75',
  99. '90percentile': 'p90',
  100. '95percentile': 'p95',
  101. '99percentile': 'p99',
  102. };
  103. export class WidgetParser {
  104. private errors: string[] = [];
  105. private api = new Client();
  106. private importedWidget: ImportWidget;
  107. private availableMetrics: MetricMeta[];
  108. private orgSlug: string;
  109. private metricsNewInputs: boolean;
  110. constructor(
  111. importedWidget: ImportWidget,
  112. availableMetrics: MetricMeta[],
  113. orgSlug: string,
  114. metricsNewInputs: boolean
  115. ) {
  116. this.importedWidget = importedWidget;
  117. this.availableMetrics = availableMetrics;
  118. this.orgSlug = orgSlug;
  119. this.metricsNewInputs = metricsNewInputs;
  120. }
  121. // Parsing functions
  122. public async parse() {
  123. const {
  124. id,
  125. definition: {title, type: widgetType},
  126. } = this.importedWidget;
  127. try {
  128. if (!SUPPORTED_WIDGET_TYPES.has(widgetType)) {
  129. throw new Error(`widget - unsupported type ${widgetType}`);
  130. }
  131. const widget = await this.parseWidget();
  132. if (!widget || !widget.queries.length) {
  133. throw new Error('widget - no parseable queries found');
  134. }
  135. const outcome: ImportOutcome = this.errors.length ? 'warning' : 'success';
  136. return {
  137. report: {
  138. id,
  139. title,
  140. errors: this.errors,
  141. outcome,
  142. },
  143. widget,
  144. };
  145. } catch (e) {
  146. return {
  147. report: {
  148. id,
  149. title,
  150. errors: [e.message, ...this.errors],
  151. outcome: 'error' as const,
  152. },
  153. widget: null,
  154. };
  155. }
  156. }
  157. private async parseWidget() {
  158. this.parseLegendColumns();
  159. const {title, requests = []} = this.importedWidget.definition as WidgetDefinition;
  160. const parsedRequests = requests.map(r => this.parseRequest(r));
  161. const parsedQueries = parsedRequests.flatMap(request => request.queries);
  162. const metricsQueries = await Promise.all(
  163. parsedQueries.map(async query => {
  164. const mapped = await this.mapToMetricsQuery(query);
  165. return {
  166. ...mapped,
  167. };
  168. })
  169. );
  170. const nonEmptyQueries = metricsQueries.filter(query => query.mri) as MetricsQuery[];
  171. if (!nonEmptyQueries.length) {
  172. return null;
  173. }
  174. const metricsEquations = parsedRequests
  175. .flatMap(request => request.equations)
  176. .map(equation => this.mapToMetricsEquation(equation.formula));
  177. return convertToDashboardWidget(
  178. [...nonEmptyQueries, ...metricsEquations],
  179. parsedRequests[0].displayType,
  180. title
  181. );
  182. }
  183. private parseLegendColumns() {
  184. (this.importedWidget.definition?.legend_columns ?? []).forEach(column => {
  185. if (!SUPPORTED_COLUMNS.has(column)) {
  186. this.errors.push(`widget - unsupported column: ${column}`);
  187. }
  188. });
  189. }
  190. private parseRequest(request: Request) {
  191. const {queries, formulas = [], response_format, display_type} = request;
  192. const parsedQueries = queries
  193. .map(query => this.parseQuery(query))
  194. .sort((a, b) => a!.name.localeCompare(b!.name));
  195. if (response_format !== 'timeseries') {
  196. this.errors.push(
  197. `widget.request.response_format - unsupported: ${response_format}`
  198. );
  199. }
  200. const equationFormulas = formulas.filter(f =>
  201. // indicates a more complex formula and not just a reference to a query
  202. f.formula.trim().includes(' ')
  203. );
  204. const parsedEquations = this.parseEquations(parsedQueries, equationFormulas);
  205. const displayType = this.parseDisplayType(display_type);
  206. this.parseStyle(request.style);
  207. return {
  208. displayType,
  209. queries: parsedQueries,
  210. equations: parsedEquations,
  211. };
  212. }
  213. // swaps query names with query symbols in formulas eg. query1 + $query0 => $b + $a
  214. private parseEquations(queries: any[], formulas: Formula[]) {
  215. const queryNames = queries.map(q => q.name);
  216. const queryNameMap = queries.reduce((acc, query, index) => {
  217. acc[query.name] = getQuerySymbol(index, this.metricsNewInputs);
  218. return acc;
  219. }, {});
  220. const equations = formulas.map(formula => {
  221. const {formula: formulaString, alias} = formula;
  222. const mapped = queryNames.reduce((acc, queryName) => {
  223. return acc.replaceAll(queryName, `$${queryNameMap[queryName]}`);
  224. }, formulaString);
  225. return {
  226. formula: mapped,
  227. alias,
  228. };
  229. });
  230. return equations;
  231. }
  232. private parseDisplayType(displayType: string) {
  233. switch (displayType) {
  234. case 'area':
  235. return MetricDisplayType.AREA;
  236. case 'bars':
  237. return MetricDisplayType.BAR;
  238. case 'line':
  239. return MetricDisplayType.LINE;
  240. default:
  241. this.errors.push(
  242. `widget.request.display_type - unsupported: ${displayType}, assuming line`
  243. );
  244. return MetricDisplayType.LINE;
  245. }
  246. }
  247. private parseStyle(style?: Request['style']) {
  248. if (style?.line_type === 'dotted') {
  249. this.errors.push(
  250. `widget.request.style - unsupported line type: ${style.line_type}`
  251. );
  252. }
  253. }
  254. private parseQuery(query: {name: string; query: string}) {
  255. return {...this.parseQueryString(query.query), name: query.name};
  256. }
  257. private parseQueryString(str: string) {
  258. const aggregationMatch = str.match(/^(sum|avg|max|min):/);
  259. let aggregation = aggregationMatch ? aggregationMatch[1] : undefined;
  260. const metricNameMatch = str.match(/:(\S*){/);
  261. let metric = metricNameMatch ? metricNameMatch[1] : undefined;
  262. if (metric?.includes('.')) {
  263. const lastIndex = metric.lastIndexOf('.');
  264. const metricName = metric.slice(0, lastIndex);
  265. const aggregationSuffix = metric.slice(lastIndex + 1);
  266. if (METRIC_SUFFIX_TO_AGGREGATION[aggregationSuffix]) {
  267. aggregation = METRIC_SUFFIX_TO_AGGREGATION[aggregationSuffix];
  268. metric = metricName;
  269. }
  270. }
  271. const filtersMatch = str.match(/{([^}]*)}/);
  272. const filters = filtersMatch ? this.parseFilters(filtersMatch[1]) : [];
  273. const groupByMatch = str.match(/by {([^}]*)}/);
  274. const groupBy = groupByMatch ? this.parseGroupByValues(groupByMatch[1]) : [];
  275. const appliedFunctionMatch = str.match(/\.(\w+)\(\)/);
  276. const appliedFunction = appliedFunctionMatch ? appliedFunctionMatch[1] : undefined;
  277. if (!aggregation) {
  278. this.errors.push(
  279. `widget.request.query - could not parse aggregation: ${str}, assuming sum`
  280. );
  281. aggregation = 'sum';
  282. }
  283. if (!metric) {
  284. this.errors.push(
  285. `widget.request.query - could not parse name: ${str}, assuming ${metric}`
  286. );
  287. metric = 'sentry.event_manager.save';
  288. }
  289. // TODO: check which other functions are supported
  290. if (appliedFunction) {
  291. if (appliedFunction === 'as_count') {
  292. aggregation = 'sum';
  293. this.errors.push(
  294. `widget.request.query - unsupported function ${appliedFunction}, assuming sum`
  295. );
  296. } else {
  297. this.errors.push(
  298. `widget.request.query - unsupported function ${appliedFunction}`
  299. );
  300. }
  301. }
  302. return {
  303. aggregation,
  304. metric,
  305. filters,
  306. groupBy,
  307. appliedFunction,
  308. };
  309. }
  310. // Helper functions
  311. private parseFilters(filtersString) {
  312. const filters: any[] = [];
  313. const pairs = filtersString.split(',');
  314. for (const pair of pairs) {
  315. const [key, value] = pair.split(':');
  316. if (!key || !value) {
  317. continue;
  318. }
  319. if (value.includes('*')) {
  320. const stripped = value.replace(/\*/g, '');
  321. this.errors.push(
  322. `widget.request.query.filter - unsupported value: ${value}, using ${stripped}`
  323. );
  324. if (stripped) {
  325. filters.push({key: key.trim(), value: stripped.trim()});
  326. }
  327. continue;
  328. }
  329. filters.push({key: key.trim(), value: value.trim()});
  330. }
  331. return filters;
  332. }
  333. private parseGroupByValues(groupByString) {
  334. return groupByString.split(',').map(value => value.trim());
  335. }
  336. // Mapping functions
  337. private async mapToMetricsQuery(widget): Promise<MetricsQuery | null> {
  338. const {metric, aggregation, filters} = widget;
  339. // @ts-expect-error name is actually defined on MetricMeta
  340. const metricMeta = this.availableMetrics.find(m => m.name === metric);
  341. if (!metricMeta) {
  342. this.errors.push(`widget.request.query - metric not found: ${metric}`);
  343. return null;
  344. }
  345. const availableTags = await this.fetchAvailableTags(metricMeta.mri);
  346. const query = this.constructMetricQueryFilter(filters, availableTags);
  347. const groupBy = this.constructMetricGroupBy(widget.groupBy, availableTags);
  348. return {
  349. mri: metricMeta.mri,
  350. aggregation,
  351. query,
  352. groupBy,
  353. };
  354. }
  355. private mapToMetricsEquation(formula: string) {
  356. return {
  357. type: 'formula',
  358. formula,
  359. };
  360. }
  361. private async fetchAvailableTags(mri: MRI) {
  362. const tagsRes = await this.api.requestPromise(
  363. `/organizations/${this.orgSlug}/metrics/tags/`,
  364. {
  365. query: {
  366. metric: mri,
  367. useCase: 'custom',
  368. },
  369. }
  370. );
  371. return (tagsRes ?? []).map(tag => tag.key);
  372. }
  373. private constructMetricQueryFilter(
  374. filters: {key: string; value: string}[],
  375. availableTags: string[]
  376. ) {
  377. const queryFilters = filters.map(filter => {
  378. const {key, value} = filter;
  379. if (!availableTags.includes(key)) {
  380. this.errors.push(`widget.request.query - unsupported filter: ${key}`);
  381. return null;
  382. }
  383. return `${key}:${value}`;
  384. });
  385. return queryFilters.filter(Boolean).join(' ');
  386. }
  387. private constructMetricGroupBy(groupBy: string[], availableTags: string[]): string[] {
  388. return groupBy.filter(group => {
  389. if (!availableTags.includes(group)) {
  390. this.errors.push(`widget.request.query - unsupported group by: ${group}`);
  391. return false;
  392. }
  393. return true;
  394. });
  395. }
  396. }