parseMetricWidgetsQueryParam.tsx 8.1 KB

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