utils.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. import {useMemo} from 'react';
  2. import type {MRI} from 'sentry/types/metrics';
  3. import {unescapeMetricsFormula} from 'sentry/utils/metrics';
  4. import {NO_QUERY_ID} from 'sentry/utils/metrics/constants';
  5. import {formatMRIField, MRIToField, parseField} from 'sentry/utils/metrics/mri';
  6. import {MetricDisplayType, MetricExpressionType} from 'sentry/utils/metrics/types';
  7. import type {MetricsQueryApiQueryParams} from 'sentry/utils/metrics/useMetricsQuery';
  8. import type {
  9. DashboardMetricsEquation,
  10. DashboardMetricsExpression,
  11. DashboardMetricsQuery,
  12. } from 'sentry/views/dashboards/metrics/types';
  13. import {
  14. type DashboardFilters,
  15. DisplayType,
  16. type Widget,
  17. type WidgetQuery,
  18. WidgetType,
  19. } from 'sentry/views/dashboards/types';
  20. import {getEquationSymbol} from 'sentry/views/metrics/equationSymbol';
  21. import {getQuerySymbol} from 'sentry/views/metrics/querySymbol';
  22. import {getUniqueQueryIdGenerator} from 'sentry/views/metrics/utils/uniqueQueryId';
  23. function extendQuery(query = '', dashboardFilters?: DashboardFilters) {
  24. if (!dashboardFilters?.release?.length) {
  25. return query;
  26. }
  27. const releaseQuery = getReleaseQuery(dashboardFilters);
  28. return `${query} ${releaseQuery}`.trim();
  29. }
  30. function getReleaseQuery(dashboardFilters: DashboardFilters) {
  31. const {release} = dashboardFilters;
  32. if (!release?.length) {
  33. return '';
  34. }
  35. if (release.length === 1) {
  36. return `release:${release[0]}`;
  37. }
  38. return `release:[${release.join(',')}]`;
  39. }
  40. export function isMetricsEquation(
  41. query: DashboardMetricsExpression
  42. ): query is DashboardMetricsEquation {
  43. return query.type === MetricExpressionType.EQUATION;
  44. }
  45. function getExpressionIdFromWidgetQuery(query: WidgetQuery): number {
  46. let id = query.name && Number(query.name);
  47. if (typeof id !== 'number' || Number.isNaN(id) || id < 0 || !Number.isInteger(id)) {
  48. id = NO_QUERY_ID;
  49. }
  50. return id;
  51. }
  52. function fillMissingExpressionIds(
  53. expressions: (DashboardMetricsExpression | null)[],
  54. indizesWithoutId: number[],
  55. usedIds: Set<number>
  56. ): (DashboardMetricsExpression | null)[] {
  57. if (indizesWithoutId.length > 0) {
  58. const generateId = getUniqueQueryIdGenerator(usedIds);
  59. for (const index of indizesWithoutId) {
  60. const expression = expressions[index];
  61. if (!expression) {
  62. continue;
  63. }
  64. expression.id = generateId.next().value;
  65. }
  66. }
  67. return expressions;
  68. }
  69. export function getMetricQueries(
  70. widget: Widget,
  71. dashboardFilters?: DashboardFilters
  72. ): DashboardMetricsQuery[] {
  73. const usedIds = new Set<number>();
  74. const indizesWithoutId: number[] = [];
  75. const queries = widget.queries.map((query, index): DashboardMetricsQuery | null => {
  76. if (query.aggregates[0].startsWith('equation|')) {
  77. return null;
  78. }
  79. const id = getExpressionIdFromWidgetQuery(query);
  80. if (id === NO_QUERY_ID) {
  81. indizesWithoutId.push(index);
  82. } else {
  83. usedIds.add(id);
  84. }
  85. const parsed = parseField(query.aggregates[0]) || {mri: '' as MRI, op: ''};
  86. const orderBy = query.orderby ? query.orderby : undefined;
  87. return {
  88. id: id,
  89. type: MetricExpressionType.QUERY,
  90. mri: parsed.mri,
  91. op: parsed.op,
  92. query: extendQuery(query.conditions, dashboardFilters),
  93. groupBy: query.columns,
  94. orderBy: orderBy === 'asc' || orderBy === 'desc' ? orderBy : undefined,
  95. isHidden: !!query.isHidden,
  96. alias: query.fieldAliases?.[0],
  97. };
  98. });
  99. return fillMissingExpressionIds(queries, indizesWithoutId, usedIds).filter(
  100. (query): query is DashboardMetricsQuery => query !== null
  101. );
  102. }
  103. export function getMetricEquations(widget: Widget): DashboardMetricsEquation[] {
  104. const usedIds = new Set<number>();
  105. const indicesWithoutId: number[] = [];
  106. const equations = widget.queries.map(
  107. (query, index): DashboardMetricsEquation | null => {
  108. if (!query.aggregates[0].startsWith('equation|')) {
  109. return null;
  110. }
  111. const id = getExpressionIdFromWidgetQuery(query);
  112. if (id === NO_QUERY_ID) {
  113. indicesWithoutId.push(index);
  114. } else {
  115. usedIds.add(id);
  116. }
  117. return {
  118. id: id,
  119. type: MetricExpressionType.EQUATION,
  120. formula: query.aggregates[0].slice(9),
  121. isHidden: !!query.isHidden,
  122. alias: query.fieldAliases?.[0],
  123. } satisfies DashboardMetricsEquation;
  124. }
  125. );
  126. return fillMissingExpressionIds(equations, indicesWithoutId, usedIds).filter(
  127. (query): query is DashboardMetricsEquation => query !== null
  128. );
  129. }
  130. export function getMetricExpressions(
  131. widget: Widget,
  132. dashboardFilters?: DashboardFilters
  133. ): DashboardMetricsExpression[] {
  134. return [...getMetricQueries(widget, dashboardFilters), ...getMetricEquations(widget)];
  135. }
  136. export function useGenerateExpressionId(expressions: DashboardMetricsExpression[]) {
  137. return useMemo(() => {
  138. const usedIds = new Set<number>(expressions.map(e => e.id));
  139. return () => getUniqueQueryIdGenerator(usedIds).next().value;
  140. }, [expressions]);
  141. }
  142. export function expressionsToApiQueries(
  143. expressions: DashboardMetricsExpression[]
  144. ): MetricsQueryApiQueryParams[] {
  145. return expressions
  146. .filter(e => !(e.type === MetricExpressionType.EQUATION && e.isHidden))
  147. .map(e =>
  148. isMetricsEquation(e)
  149. ? {
  150. alias: e.alias,
  151. formula: e.formula,
  152. name: getEquationSymbol(e.id),
  153. }
  154. : {...e, name: getQuerySymbol(e.id), isQueryOnly: e.isHidden}
  155. );
  156. }
  157. export function toMetricDisplayType(displayType: unknown): MetricDisplayType {
  158. if (Object.values(MetricDisplayType).includes(displayType as MetricDisplayType)) {
  159. return displayType as MetricDisplayType;
  160. }
  161. return MetricDisplayType.LINE;
  162. }
  163. function getWidgetQuery(metricsQuery: DashboardMetricsQuery): WidgetQuery {
  164. const field = MRIToField(metricsQuery.mri, metricsQuery.op);
  165. return {
  166. name: `${metricsQuery.id}`,
  167. aggregates: [field],
  168. columns: metricsQuery.groupBy ?? [],
  169. fields: [field],
  170. conditions: metricsQuery.query ?? '',
  171. orderby: metricsQuery.orderBy ?? '',
  172. isHidden: metricsQuery.isHidden,
  173. fieldAliases: metricsQuery.alias ? [metricsQuery.alias] : [],
  174. };
  175. }
  176. function getWidgetEquation(metricsEquation: DashboardMetricsEquation): WidgetQuery {
  177. return {
  178. name: `${metricsEquation.id}`,
  179. aggregates: [`equation|${metricsEquation.formula}`],
  180. columns: [],
  181. fields: [`equation|${metricsEquation.formula}`],
  182. isHidden: metricsEquation.isHidden,
  183. fieldAliases: metricsEquation.alias ? [metricsEquation.alias] : [],
  184. // Not used for equations
  185. conditions: '',
  186. orderby: '',
  187. };
  188. }
  189. export function expressionsToWidget(
  190. expressions: DashboardMetricsExpression[],
  191. title: string,
  192. displayType: DisplayType,
  193. interval = '5m'
  194. ): Widget {
  195. return {
  196. title,
  197. interval,
  198. displayType: displayType,
  199. widgetType: WidgetType.METRICS,
  200. limit: 10,
  201. queries: expressions.map(e => {
  202. if (isMetricsEquation(e)) {
  203. return getWidgetEquation(e);
  204. }
  205. return getWidgetQuery(e);
  206. }),
  207. };
  208. }
  209. export function getMetricWidgetTitle(queries: DashboardMetricsExpression[]) {
  210. return queries.map(getMetricQueryName).join(', ');
  211. }
  212. export function getMetricQueryName(query: DashboardMetricsExpression): string {
  213. return (
  214. query.alias ??
  215. (isMetricsEquation(query)
  216. ? unescapeMetricsFormula(query.formula)
  217. : formatMRIField(MRIToField(query.mri, query.op)))
  218. );
  219. }
  220. export function defaultMetricWidget(): Widget {
  221. return expressionsToWidget(
  222. [
  223. {
  224. id: 0,
  225. type: MetricExpressionType.QUERY,
  226. mri: 'd:transactions/duration@millisecond',
  227. op: 'avg',
  228. query: '',
  229. orderBy: 'desc',
  230. isHidden: false,
  231. },
  232. ],
  233. '',
  234. DisplayType.LINE
  235. );
  236. }
  237. export function filterQueriesByDisplayType(
  238. queries: DashboardMetricsQuery[],
  239. displayType: DisplayType
  240. ) {
  241. // Big number can display only one query
  242. if (displayType === DisplayType.BIG_NUMBER) {
  243. return queries.slice(0, 1);
  244. }
  245. return queries;
  246. }
  247. export function filterEquationsByDisplayType(
  248. equations: DashboardMetricsEquation[],
  249. displayType: DisplayType
  250. ) {
  251. // Big number can display only one query
  252. if (displayType === DisplayType.BIG_NUMBER) {
  253. return [];
  254. }
  255. return equations;
  256. }