parseMetricWidgetsQueryParam.tsx 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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. name === 'total'
  97. ) {
  98. return {name, order};
  99. }
  100. return {name: undefined, order};
  101. }
  102. function isValidId(n: number | undefined): n is number {
  103. return n !== undefined && Number.isInteger(n) && n >= 0;
  104. }
  105. function parseQueryType(
  106. widget: Record<string, unknown>,
  107. key: string
  108. ): MetricExpressionType | undefined {
  109. const value = widget[key];
  110. return typeof value === 'number' && Object.values(MetricExpressionType).includes(value)
  111. ? value
  112. : undefined;
  113. }
  114. function parseQueryWidget(
  115. widget: Record<string, unknown>,
  116. baseWidgetParams: BaseWidgetParams
  117. ): MetricsQueryWidget | null {
  118. const mri = getMRIParam(widget);
  119. // If we cannot retrieve an MRI, there is nothing to display
  120. if (!mri) {
  121. return null;
  122. }
  123. return {
  124. mri,
  125. op: parseStringParam(widget, 'op') ?? getDefaultAggregate(mri),
  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(
  172. queryParam?: string,
  173. defaultMRI?: MRI
  174. ): MetricsWidget[] {
  175. let currentWidgets: unknown = undefined;
  176. try {
  177. currentWidgets = JSON.parse(queryParam || '');
  178. } catch (_) {
  179. currentWidgets = [];
  180. }
  181. // It has to be an array and non-empty
  182. if (!Array.isArray(currentWidgets)) {
  183. currentWidgets = [];
  184. }
  185. const queries: MetricsQueryWidget[] = [];
  186. const usedQueryIds = new Set<number>();
  187. const queryIndicesWithoutId = new Set<number>();
  188. const formulas: MetricsEquationWidget[] = [];
  189. const usedFormulaIds = new Set<number>();
  190. const formulaIndicesWithoutId = new Set<number>();
  191. (currentWidgets as unknown[]).forEach((widget: unknown) => {
  192. if (!isRecord(widget)) {
  193. return;
  194. }
  195. const type = parseQueryType(widget, 'type') ?? MetricExpressionType.QUERY;
  196. const id = parseQueryId(widget, 'id');
  197. if (
  198. type === MetricExpressionType.QUERY ? usedQueryIds.has(id) : usedFormulaIds.has(id)
  199. ) {
  200. // We drop widgets with duplicate ids
  201. return;
  202. }
  203. if (id !== NO_QUERY_ID) {
  204. if (type === MetricExpressionType.QUERY) {
  205. usedQueryIds.add(id);
  206. } else {
  207. usedFormulaIds.add(id);
  208. }
  209. }
  210. const displayType = parseStringParam(widget, 'displayType');
  211. const baseWidgetParams: BaseWidgetParams = {
  212. type,
  213. id: !isValidId(id) ? NO_QUERY_ID : id,
  214. displayType: isMetricDisplayType(displayType)
  215. ? displayType
  216. : MetricDisplayType.LINE,
  217. focusedSeries: parseArrayParam(widget, 'focusedSeries', parseFocusedSeries),
  218. sort: parseSortParam(widget, 'sort'),
  219. isHidden: parseBooleanParam(widget, 'isHidden') ?? false,
  220. overlays: widget.overlays
  221. ? parseArrayParam(widget, 'overlays', entry => entry as MetricChartOverlayType)
  222. : [MetricChartOverlayType.SAMPLES],
  223. };
  224. switch (type) {
  225. case MetricExpressionType.QUERY: {
  226. const query = parseQueryWidget(widget, baseWidgetParams);
  227. if (!query) {
  228. break;
  229. }
  230. queries.push(query);
  231. if (query.id === NO_QUERY_ID) {
  232. queryIndicesWithoutId.add(queries.length - 1);
  233. }
  234. break;
  235. }
  236. case MetricExpressionType.EQUATION: {
  237. const formula = parseFormulaWidget(widget, baseWidgetParams);
  238. if (!formula) {
  239. break;
  240. }
  241. formulas.push(formula);
  242. if (formula.id === NO_QUERY_ID) {
  243. formulaIndicesWithoutId.add(formulas.length - 1);
  244. }
  245. break;
  246. }
  247. default:
  248. break;
  249. }
  250. });
  251. // Iterate over the widgets without an id and assign them a unique one
  252. if (queries.length === 0) {
  253. const mri = defaultMRI || emptyMetricsQueryWidget.mri;
  254. queries.push({
  255. ...emptyMetricsQueryWidget,
  256. mri,
  257. op: getDefaultAggregate(mri),
  258. });
  259. }
  260. // We can reset the id if there is only one widget
  261. if (queries.length === 1) {
  262. queries[0].id = 0;
  263. }
  264. if (formulas.length === 1) {
  265. formulas[0].id = 0;
  266. }
  267. return [
  268. ...fillIds(queries, queryIndicesWithoutId, usedQueryIds),
  269. ...fillIds(formulas, formulaIndicesWithoutId, usedFormulaIds),
  270. ];
  271. }