parseMetricWidgetsQueryParam.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. import type {MetricAggregation} from 'sentry/types/metrics';
  2. import {getDefaultAggregation} from 'sentry/utils/metrics';
  3. import {DEFAULT_SORT_STATE, NO_QUERY_ID} from 'sentry/utils/metrics/constants';
  4. import {isMRI} from 'sentry/utils/metrics/mri';
  5. import {
  6. type BaseWidgetParams,
  7. type FocusedMetricsSeries,
  8. MetricChartOverlayType,
  9. MetricDisplayType,
  10. MetricExpressionType,
  11. type MetricsEquationWidget,
  12. type MetricsQueryWidget,
  13. type MetricsWidget,
  14. type SortState,
  15. } from 'sentry/utils/metrics/types';
  16. import {getUniqueQueryIdGenerator} from 'sentry/views/metrics/utils/uniqueQueryId';
  17. function isRecord(value: unknown): value is Record<string, unknown> {
  18. return typeof value === 'object' && value !== null && !Array.isArray(value);
  19. }
  20. function isMetricDisplayType(value: unknown): value is MetricDisplayType {
  21. return Object.values(MetricDisplayType).includes(value as MetricDisplayType);
  22. }
  23. function getMRIParam(widget: Record<string, unknown>) {
  24. return 'mri' in widget && isMRI(widget.mri) ? widget.mri : undefined;
  25. }
  26. function parseStringParam(
  27. widget: Record<string, unknown>,
  28. key: string
  29. ): string | undefined {
  30. const value = widget[key];
  31. return typeof value === 'string' ? value : undefined;
  32. }
  33. function parseNumberParam(
  34. widget: Record<string, unknown>,
  35. key: string
  36. ): number | undefined {
  37. const value = widget[key];
  38. return typeof value === 'number' && !Number.isNaN(value) ? value : undefined;
  39. }
  40. function parseBooleanParam(
  41. widget: Record<string, unknown>,
  42. key: string
  43. ): boolean | undefined {
  44. const value = widget[key];
  45. return typeof value === 'boolean' ? value : undefined;
  46. }
  47. function parseArrayParam<T extends Exclude<any, undefined>>(
  48. widget: object,
  49. key: string,
  50. entryParser: (entry: unknown) => T | undefined
  51. ): T[] {
  52. if (!(key in widget)) {
  53. return [];
  54. }
  55. // allow single values instead of arrays
  56. if (!Array.isArray(widget[key])) {
  57. const entry = entryParser(widget[key]);
  58. return entry === undefined ? [] : [entry];
  59. }
  60. return widget[key].map(entryParser).filter((entry): entry is T => entry !== undefined);
  61. }
  62. function parseFocusedSeries(series: any): FocusedMetricsSeries | undefined {
  63. if (!isRecord(series)) {
  64. return undefined;
  65. }
  66. const id = parseStringParam(series, 'id');
  67. const groupBy =
  68. 'groupBy' in series && isRecord(series.groupBy)
  69. ? (series.groupBy as Record<string, string>)
  70. : undefined;
  71. if (!id) {
  72. return undefined;
  73. }
  74. return {id, groupBy};
  75. }
  76. function parseSortParam(widget: Record<string, unknown>, key: string): SortState {
  77. const sort = widget[key];
  78. if (!isRecord(sort)) {
  79. return DEFAULT_SORT_STATE;
  80. }
  81. const name = parseStringParam(sort, 'name');
  82. const order =
  83. 'order' in sort && (sort.order === 'desc' || sort.order === 'asc')
  84. ? sort.order
  85. : DEFAULT_SORT_STATE.order;
  86. if (
  87. name === 'name' ||
  88. name === 'avg' ||
  89. name === 'min' ||
  90. name === 'max' ||
  91. name === 'sum' ||
  92. name === 'total'
  93. ) {
  94. return {name, order};
  95. }
  96. return {name: undefined, order};
  97. }
  98. function isValidId(n: number | undefined): n is number {
  99. return n !== undefined && Number.isInteger(n) && n >= 0;
  100. }
  101. function parseQueryType(
  102. widget: Record<string, unknown>,
  103. key: string
  104. ): MetricExpressionType | undefined {
  105. const value = widget[key];
  106. return typeof value === 'number' && Object.values(MetricExpressionType).includes(value)
  107. ? value
  108. : undefined;
  109. }
  110. function parseAggregation(
  111. widget: Record<string, unknown>
  112. ): MetricAggregation | undefined {
  113. const aggregation =
  114. parseStringParam(widget, 'aggregation') ?? parseStringParam(widget, 'op');
  115. if (!aggregation) {
  116. return undefined;
  117. }
  118. return aggregation as MetricAggregation;
  119. }
  120. function parseQueryWidget(
  121. widget: Record<string, unknown>,
  122. baseWidgetParams: BaseWidgetParams
  123. ): MetricsQueryWidget | null {
  124. const mri = getMRIParam(widget);
  125. // If we cannot retrieve an MRI, there is nothing to display
  126. if (!mri) {
  127. return null;
  128. }
  129. return {
  130. mri,
  131. aggregation: parseAggregation(widget) ?? getDefaultAggregation(mri),
  132. condition: parseNumberParam(widget, 'condition'),
  133. query: parseStringParam(widget, 'query') ?? '',
  134. groupBy: parseArrayParam(widget, 'groupBy', entry =>
  135. typeof entry === 'string' ? entry : undefined
  136. ),
  137. powerUserMode: parseBooleanParam(widget, 'powerUserMode') ?? false,
  138. ...baseWidgetParams,
  139. type: MetricExpressionType.QUERY,
  140. };
  141. }
  142. function parseFormulaWidget(
  143. widget: Record<string, unknown>,
  144. baseWidgetParams: BaseWidgetParams
  145. ): MetricsEquationWidget | null {
  146. const formula = parseStringParam(widget, 'formula');
  147. // If we cannot retrieve a formula, there is nothing to display
  148. if (formula === undefined) {
  149. return null;
  150. }
  151. return {
  152. formula,
  153. ...baseWidgetParams,
  154. type: MetricExpressionType.EQUATION,
  155. };
  156. }
  157. function parseQueryId(widget: Record<string, unknown>, key: string): number {
  158. const value = parseNumberParam(widget, key);
  159. return isValidId(value) ? value : NO_QUERY_ID;
  160. }
  161. function fillIds(
  162. entries: MetricsWidget[],
  163. indicesWithoutId: Set<number>,
  164. usedIds: Set<number>
  165. ): MetricsWidget[] {
  166. if (indicesWithoutId.size > 0) {
  167. const generateId = getUniqueQueryIdGenerator(usedIds);
  168. for (const index of indicesWithoutId) {
  169. const widget = entries[index];
  170. if (!widget) {
  171. continue;
  172. }
  173. widget.id = generateId.next().value;
  174. }
  175. }
  176. return entries;
  177. }
  178. export function parseMetricWidgetsQueryParam(queryParam?: string): MetricsWidget[] {
  179. let currentWidgets: unknown = undefined;
  180. try {
  181. currentWidgets = JSON.parse(queryParam || '');
  182. } catch (_) {
  183. currentWidgets = [];
  184. }
  185. // It has to be an array and non-empty
  186. if (!Array.isArray(currentWidgets)) {
  187. currentWidgets = [];
  188. }
  189. const queries: MetricsQueryWidget[] = [];
  190. const usedQueryIds = new Set<number>();
  191. const queryIndicesWithoutId = new Set<number>();
  192. const formulas: MetricsEquationWidget[] = [];
  193. const usedFormulaIds = new Set<number>();
  194. const formulaIndicesWithoutId = new Set<number>();
  195. (currentWidgets as unknown[]).forEach((widget: unknown) => {
  196. if (!isRecord(widget)) {
  197. return;
  198. }
  199. const type = parseQueryType(widget, 'type') ?? MetricExpressionType.QUERY;
  200. const id = parseQueryId(widget, 'id');
  201. if (
  202. type === MetricExpressionType.QUERY ? usedQueryIds.has(id) : usedFormulaIds.has(id)
  203. ) {
  204. // We drop widgets with duplicate ids
  205. return;
  206. }
  207. if (id !== NO_QUERY_ID) {
  208. if (type === MetricExpressionType.QUERY) {
  209. usedQueryIds.add(id);
  210. } else {
  211. usedFormulaIds.add(id);
  212. }
  213. }
  214. const displayType = parseStringParam(widget, 'displayType');
  215. const baseWidgetParams: BaseWidgetParams = {
  216. type,
  217. id: !isValidId(id) ? NO_QUERY_ID : id,
  218. displayType: isMetricDisplayType(displayType)
  219. ? displayType
  220. : MetricDisplayType.LINE,
  221. focusedSeries: parseArrayParam(widget, 'focusedSeries', parseFocusedSeries),
  222. sort: parseSortParam(widget, 'sort'),
  223. isHidden: parseBooleanParam(widget, 'isHidden') ?? false,
  224. overlays: widget.overlays
  225. ? parseArrayParam(widget, 'overlays', entry => entry as MetricChartOverlayType)
  226. : [MetricChartOverlayType.SAMPLES],
  227. };
  228. switch (type) {
  229. case MetricExpressionType.QUERY: {
  230. const query = parseQueryWidget(widget, baseWidgetParams);
  231. if (!query) {
  232. break;
  233. }
  234. queries.push(query);
  235. if (query.id === NO_QUERY_ID) {
  236. queryIndicesWithoutId.add(queries.length - 1);
  237. }
  238. break;
  239. }
  240. case MetricExpressionType.EQUATION: {
  241. const formula = parseFormulaWidget(widget, baseWidgetParams);
  242. if (!formula) {
  243. break;
  244. }
  245. formulas.push(formula);
  246. if (formula.id === NO_QUERY_ID) {
  247. formulaIndicesWithoutId.add(formulas.length - 1);
  248. }
  249. break;
  250. }
  251. default:
  252. break;
  253. }
  254. });
  255. // We can reset the id if there is only one widget
  256. if (queries.length === 1) {
  257. queries[0].id = 0;
  258. }
  259. if (formulas.length === 1) {
  260. formulas[0].id = 0;
  261. }
  262. return [
  263. ...fillIds(queries, queryIndicesWithoutId, usedQueryIds),
  264. ...fillIds(formulas, formulaIndicesWithoutId, usedFormulaIds),
  265. ];
  266. }