parseMetricWidgetsQueryParam.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. import type {MetricAggregation} from 'sentry/types/metrics';
  2. import {getDefaultAggregation, isMetricsAggregation} 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 (name && (name === 'name' || isMetricsAggregation(name))) {
  87. return {name, order};
  88. }
  89. return {name: undefined, order};
  90. }
  91. function isValidId(n: number | undefined): n is number {
  92. return n !== undefined && Number.isInteger(n) && n >= 0;
  93. }
  94. function parseQueryType(
  95. widget: Record<string, unknown>,
  96. key: string
  97. ): MetricExpressionType | undefined {
  98. const value = widget[key];
  99. return typeof value === 'number' && Object.values(MetricExpressionType).includes(value)
  100. ? value
  101. : undefined;
  102. }
  103. function parseAggregation(
  104. widget: Record<string, unknown>
  105. ): MetricAggregation | undefined {
  106. const aggregation =
  107. parseStringParam(widget, 'aggregation') ?? parseStringParam(widget, 'op');
  108. if (!aggregation) {
  109. return undefined;
  110. }
  111. return aggregation as MetricAggregation;
  112. }
  113. function parseQueryWidget(
  114. widget: Record<string, unknown>,
  115. baseWidgetParams: BaseWidgetParams
  116. ): MetricsQueryWidget | null {
  117. const mri = getMRIParam(widget);
  118. // If we cannot retrieve an MRI, there is nothing to display
  119. if (!mri) {
  120. return null;
  121. }
  122. return {
  123. mri,
  124. aggregation: parseAggregation(widget) ?? getDefaultAggregation(mri),
  125. condition: parseNumberParam(widget, 'condition'),
  126. query: parseStringParam(widget, 'query') ?? '',
  127. groupBy: parseArrayParam(widget, 'groupBy', entry =>
  128. typeof entry === 'string' ? entry : undefined
  129. ),
  130. powerUserMode: parseBooleanParam(widget, 'powerUserMode') ?? false,
  131. ...baseWidgetParams,
  132. type: MetricExpressionType.QUERY,
  133. };
  134. }
  135. function parseFormulaWidget(
  136. widget: Record<string, unknown>,
  137. baseWidgetParams: BaseWidgetParams
  138. ): MetricsEquationWidget | null {
  139. const formula = parseStringParam(widget, 'formula');
  140. // If we cannot retrieve a formula, there is nothing to display
  141. if (formula === undefined) {
  142. return null;
  143. }
  144. return {
  145. formula,
  146. ...baseWidgetParams,
  147. type: MetricExpressionType.EQUATION,
  148. };
  149. }
  150. function parseQueryId(widget: Record<string, unknown>, key: string): number {
  151. const value = parseNumberParam(widget, key);
  152. return isValidId(value) ? value : NO_QUERY_ID;
  153. }
  154. function fillIds(
  155. entries: MetricsWidget[],
  156. indicesWithoutId: Set<number>,
  157. usedIds: Set<number>
  158. ): MetricsWidget[] {
  159. if (indicesWithoutId.size > 0) {
  160. const generateId = getUniqueQueryIdGenerator(usedIds);
  161. for (const index of indicesWithoutId) {
  162. const widget = entries[index];
  163. if (!widget) {
  164. continue;
  165. }
  166. widget.id = generateId.next().value;
  167. }
  168. }
  169. return entries;
  170. }
  171. export function parseMetricWidgetsQueryParam(queryParam?: string): MetricsWidget[] {
  172. let currentWidgets: unknown = undefined;
  173. try {
  174. currentWidgets = JSON.parse(queryParam || '');
  175. } catch (_) {
  176. currentWidgets = [];
  177. }
  178. // It has to be an array and non-empty
  179. if (!Array.isArray(currentWidgets)) {
  180. currentWidgets = [];
  181. }
  182. const queries: MetricsQueryWidget[] = [];
  183. const usedQueryIds = new Set<number>();
  184. const queryIndicesWithoutId = new Set<number>();
  185. const formulas: MetricsEquationWidget[] = [];
  186. const usedFormulaIds = new Set<number>();
  187. const formulaIndicesWithoutId = new Set<number>();
  188. (currentWidgets as unknown[]).forEach((widget: unknown) => {
  189. if (!isRecord(widget)) {
  190. return;
  191. }
  192. const type = parseQueryType(widget, 'type') ?? MetricExpressionType.QUERY;
  193. const id = parseQueryId(widget, 'id');
  194. if (
  195. type === MetricExpressionType.QUERY ? usedQueryIds.has(id) : usedFormulaIds.has(id)
  196. ) {
  197. // We drop widgets with duplicate ids
  198. return;
  199. }
  200. if (id !== NO_QUERY_ID) {
  201. if (type === MetricExpressionType.QUERY) {
  202. usedQueryIds.add(id);
  203. } else {
  204. usedFormulaIds.add(id);
  205. }
  206. }
  207. const displayType = parseStringParam(widget, 'displayType');
  208. const baseWidgetParams: BaseWidgetParams = {
  209. type,
  210. id: !isValidId(id) ? NO_QUERY_ID : id,
  211. displayType: isMetricDisplayType(displayType)
  212. ? displayType
  213. : MetricDisplayType.LINE,
  214. focusedSeries: parseArrayParam(widget, 'focusedSeries', parseFocusedSeries),
  215. sort: parseSortParam(widget, 'sort'),
  216. isHidden: parseBooleanParam(widget, 'isHidden') ?? false,
  217. overlays: widget.overlays
  218. ? parseArrayParam(widget, 'overlays', entry => entry as MetricChartOverlayType)
  219. : [MetricChartOverlayType.SAMPLES],
  220. };
  221. switch (type) {
  222. case MetricExpressionType.QUERY: {
  223. const query = parseQueryWidget(widget, baseWidgetParams);
  224. if (!query) {
  225. break;
  226. }
  227. queries.push(query);
  228. if (query.id === NO_QUERY_ID) {
  229. queryIndicesWithoutId.add(queries.length - 1);
  230. }
  231. break;
  232. }
  233. case MetricExpressionType.EQUATION: {
  234. const formula = parseFormulaWidget(widget, baseWidgetParams);
  235. if (!formula) {
  236. break;
  237. }
  238. formulas.push(formula);
  239. if (formula.id === NO_QUERY_ID) {
  240. formulaIndicesWithoutId.add(formulas.length - 1);
  241. }
  242. break;
  243. }
  244. default:
  245. break;
  246. }
  247. });
  248. // We can reset the id if there is only one widget
  249. if (queries.length === 1) {
  250. queries[0].id = 0;
  251. }
  252. if (formulas.length === 1) {
  253. formulas[0].id = 0;
  254. }
  255. return [
  256. ...fillIds(queries, queryIndicesWithoutId, usedQueryIds),
  257. ...fillIds(formulas, formulaIndicesWithoutId, usedFormulaIds),
  258. ];
  259. }