utils.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. import cloneDeep from 'lodash/cloneDeep';
  2. import isEqual from 'lodash/isEqual';
  3. import trimStart from 'lodash/trimStart';
  4. import {t} from 'sentry/locale';
  5. import {OrganizationSummary, SelectValue, TagCollection} from 'sentry/types';
  6. import {
  7. aggregateFunctionOutputType,
  8. aggregateOutputType,
  9. getEquationAliasIndex,
  10. isEquation,
  11. isEquationAlias,
  12. isLegalYAxisType,
  13. SPAN_OP_BREAKDOWN_FIELDS,
  14. stripDerivedMetricsPrefix,
  15. stripEquationPrefix,
  16. } from 'sentry/utils/discover/fields';
  17. import {MeasurementCollection} from 'sentry/utils/measurements/measurements';
  18. import {
  19. DisplayType,
  20. Widget,
  21. WidgetQuery,
  22. WidgetType,
  23. } from 'sentry/views/dashboards/types';
  24. import {FieldValueOption} from 'sentry/views/discover/table/queryField';
  25. import {FieldValueKind} from 'sentry/views/discover/table/types';
  26. import {generateFieldOptions} from 'sentry/views/discover/utils';
  27. import {IssueSortOptions} from 'sentry/views/issueList/utils';
  28. import {FlatValidationError, getNumEquations, ValidationError} from '../utils';
  29. import {DISABLED_SORT, TAG_SORT_DENY_LIST} from './releaseWidget/fields';
  30. // Used in the widget builder to limit the number of lines plotted in the chart
  31. export const DEFAULT_RESULTS_LIMIT = 5;
  32. const RESULTS_LIMIT = 10;
  33. // Both dashboards and widgets use the 'new' keyword when creating
  34. export const NEW_DASHBOARD_ID = 'new';
  35. export enum DataSet {
  36. EVENTS = 'events',
  37. ISSUES = 'issues',
  38. RELEASES = 'releases',
  39. }
  40. export enum SortDirection {
  41. HIGH_TO_LOW = 'high_to_low',
  42. LOW_TO_HIGH = 'low_to_high',
  43. }
  44. export const sortDirections = {
  45. [SortDirection.HIGH_TO_LOW]: t('High to low'),
  46. [SortDirection.LOW_TO_HIGH]: t('Low to high'),
  47. };
  48. export const displayTypes = {
  49. [DisplayType.AREA]: t('Area Chart'),
  50. [DisplayType.BAR]: t('Bar Chart'),
  51. [DisplayType.LINE]: t('Line Chart'),
  52. [DisplayType.TABLE]: t('Table'),
  53. [DisplayType.BIG_NUMBER]: t('Big Number'),
  54. };
  55. export function mapErrors(
  56. data: ValidationError,
  57. update: FlatValidationError
  58. ): FlatValidationError {
  59. Object.keys(data).forEach((key: string) => {
  60. const value = data[key];
  61. if (typeof value === 'string') {
  62. update[key] = value;
  63. return;
  64. }
  65. // Recurse into nested objects.
  66. if (Array.isArray(value) && typeof value[0] === 'string') {
  67. update[key] = value[0];
  68. return;
  69. }
  70. if (Array.isArray(value) && typeof value[0] === 'object') {
  71. update[key] = (value as ValidationError[]).map(item => mapErrors(item, {}));
  72. } else {
  73. update[key] = mapErrors(value as ValidationError, {});
  74. }
  75. });
  76. return update;
  77. }
  78. export const generateOrderOptions = ({
  79. aggregates,
  80. columns,
  81. widgetType,
  82. }: {
  83. aggregates: string[];
  84. columns: string[];
  85. widgetType: WidgetType;
  86. }): SelectValue<string>[] => {
  87. const isRelease = widgetType === WidgetType.RELEASE;
  88. const options: SelectValue<string>[] = [];
  89. let equations = 0;
  90. (isRelease
  91. ? [...aggregates.map(stripDerivedMetricsPrefix), ...columns]
  92. : [...aggregates, ...columns]
  93. )
  94. .filter(field => !!field)
  95. .filter(field => !DISABLED_SORT.includes(field))
  96. .filter(field => (isRelease ? !TAG_SORT_DENY_LIST.includes(field) : true))
  97. .forEach(field => {
  98. let alias;
  99. const label = stripEquationPrefix(field);
  100. // Equations are referenced via a standard alias following this pattern
  101. if (isEquation(field)) {
  102. alias = `equation[${equations}]`;
  103. equations += 1;
  104. }
  105. options.push({label, value: alias ?? field});
  106. });
  107. return options;
  108. };
  109. export function normalizeQueries({
  110. displayType,
  111. queries,
  112. widgetType,
  113. }: {
  114. displayType: DisplayType;
  115. queries: Widget['queries'];
  116. widgetType?: Widget['widgetType'];
  117. }): Widget['queries'] {
  118. const isTimeseriesChart = getIsTimeseriesChart(displayType);
  119. const isTabularChart = [DisplayType.TABLE, DisplayType.TOP_N].includes(displayType);
  120. queries = cloneDeep(queries);
  121. if (
  122. [DisplayType.TABLE, DisplayType.WORLD_MAP, DisplayType.BIG_NUMBER].includes(
  123. displayType
  124. )
  125. ) {
  126. // Some display types may only support at most 1 query.
  127. queries = queries.slice(0, 1);
  128. } else if (isTimeseriesChart) {
  129. // Timeseries charts supports at most 3 queries.
  130. queries = queries.slice(0, 3);
  131. }
  132. queries = queries.map(query => {
  133. const {fields = [], columns} = query;
  134. if (isTabularChart) {
  135. // If the groupBy field has values, port everything over to the columnEditCollect field.
  136. query.fields = [...new Set([...fields, ...columns])];
  137. } else {
  138. // If columnEditCollect has field values , port everything over to the groupBy field.
  139. query.fields = fields.filter(field => !columns.includes(field));
  140. }
  141. if (
  142. getIsTimeseriesChart(displayType) &&
  143. !query.columns.filter(column => !!column).length
  144. ) {
  145. // The orderby is only applicable for timeseries charts when there's a
  146. // grouping selected, if all fields are empty then we also reset the orderby
  147. query.orderby = '';
  148. return query;
  149. }
  150. const queryOrderBy =
  151. widgetType === WidgetType.RELEASE
  152. ? stripDerivedMetricsPrefix(queries[0].orderby)
  153. : queries[0].orderby;
  154. const rawOrderBy = trimStart(queryOrderBy, '-');
  155. const resetOrderBy =
  156. // Raw Equation from Top N only applies to timeseries
  157. (isTabularChart && isEquation(rawOrderBy)) ||
  158. // Not contained as tag, field, or function
  159. (!isEquation(rawOrderBy) &&
  160. !isEquationAlias(rawOrderBy) &&
  161. ![...query.columns, ...query.aggregates].includes(rawOrderBy)) ||
  162. // Equation alias and not contained
  163. (isEquationAlias(rawOrderBy) &&
  164. getEquationAliasIndex(rawOrderBy) >
  165. getNumEquations([...query.columns, ...query.aggregates]) - 1);
  166. const orderBy =
  167. (!resetOrderBy && trimStart(queryOrderBy, '-')) ||
  168. (widgetType === WidgetType.ISSUE
  169. ? queryOrderBy ?? IssueSortOptions.DATE
  170. : generateOrderOptions({
  171. widgetType: widgetType ?? WidgetType.DISCOVER,
  172. columns: queries[0].columns,
  173. aggregates: queries[0].aggregates,
  174. })[0]?.value);
  175. if (!orderBy) {
  176. query.orderby = '';
  177. return query;
  178. }
  179. // A widget should be descending if:
  180. // - There is no orderby, so we're defaulting to desc
  181. // - Not an issues widget since issues doesn't support descending and
  182. // the original ordering was descending
  183. const isDescending =
  184. !query.orderby || (widgetType !== WidgetType.ISSUE && queryOrderBy.startsWith('-'));
  185. query.orderby = isDescending ? `-${String(orderBy)}` : String(orderBy);
  186. return query;
  187. });
  188. if (isTabularChart) {
  189. return queries;
  190. }
  191. // Filter out non-aggregate fields
  192. queries = queries.map(query => {
  193. let aggregates = query.aggregates;
  194. if (isTimeseriesChart || displayType === DisplayType.WORLD_MAP) {
  195. // Filter out fields that will not generate numeric output types
  196. aggregates = aggregates.filter(aggregate =>
  197. isLegalYAxisType(aggregateOutputType(aggregate))
  198. );
  199. }
  200. if (isTimeseriesChart && aggregates.length && aggregates.length > 3) {
  201. // Timeseries charts supports at most 3 fields.
  202. aggregates = aggregates.slice(0, 3);
  203. }
  204. return {
  205. ...query,
  206. fields: aggregates.length ? aggregates : ['count()'],
  207. columns: query.columns ? query.columns : [],
  208. aggregates: aggregates.length ? aggregates : ['count()'],
  209. };
  210. });
  211. if (isTimeseriesChart) {
  212. // For timeseries widget, all queries must share identical set of fields.
  213. const referenceAggregates = [...queries[0].aggregates];
  214. queryLoop: for (const query of queries) {
  215. if (referenceAggregates.length >= 3) {
  216. break;
  217. }
  218. if (isEqual(referenceAggregates, query.aggregates)) {
  219. continue;
  220. }
  221. for (const aggregate of query.aggregates) {
  222. if (referenceAggregates.length >= 3) {
  223. break queryLoop;
  224. }
  225. if (!referenceAggregates.includes(aggregate)) {
  226. referenceAggregates.push(aggregate);
  227. }
  228. }
  229. }
  230. queries = queries.map(query => {
  231. return {
  232. ...query,
  233. columns: query.columns ? query.columns : [],
  234. aggregates: referenceAggregates,
  235. fields: referenceAggregates,
  236. };
  237. });
  238. }
  239. if ([DisplayType.WORLD_MAP, DisplayType.BIG_NUMBER].includes(displayType)) {
  240. // For world map chart, cap fields of the queries to only one field.
  241. queries = queries.map(query => {
  242. return {
  243. ...query,
  244. fields: query.aggregates.slice(0, 1),
  245. aggregates: query.aggregates.slice(0, 1),
  246. orderby: '',
  247. columns: [],
  248. };
  249. });
  250. }
  251. return queries;
  252. }
  253. export function getParsedDefaultWidgetQuery(query = ''): WidgetQuery | undefined {
  254. // "any" was needed here because it doesn't pass in getsentry
  255. const urlSeachParams = new URLSearchParams(query) as any;
  256. const parsedQuery = Object.fromEntries(urlSeachParams.entries());
  257. if (!Object.keys(parsedQuery).length) {
  258. return undefined;
  259. }
  260. const columns = parsedQuery.columns ? getFields(parsedQuery.columns) : [];
  261. const aggregates = parsedQuery.aggregates ? getFields(parsedQuery.aggregates) : [];
  262. const fields = [...columns, ...aggregates];
  263. return {
  264. ...parsedQuery,
  265. fields,
  266. columns,
  267. aggregates,
  268. } as WidgetQuery;
  269. }
  270. export function getFields(fieldsString: string): string[] {
  271. // Use a negative lookahead to avoid splitting on commas inside equation fields
  272. return fieldsString.split(/,(?![^(]*\))/g);
  273. }
  274. export function getAmendedFieldOptions({
  275. measurements,
  276. organization,
  277. tags,
  278. }: {
  279. measurements: MeasurementCollection;
  280. organization: OrganizationSummary;
  281. tags: TagCollection;
  282. }) {
  283. return generateFieldOptions({
  284. organization,
  285. tagKeys: Object.values(tags).map(({key}) => key),
  286. measurementKeys: Object.values(measurements).map(({key}) => key),
  287. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  288. });
  289. }
  290. // Extract metric names from aggregation functions present in the widget queries
  291. export function getMetricFields(queries: WidgetQuery[]) {
  292. return queries.reduce<string[]>((acc, query) => {
  293. for (const field of [...query.aggregates, ...query.columns]) {
  294. const fieldParameter = /\(([^)]*)\)/.exec(field)?.[1];
  295. if (fieldParameter && !acc.includes(fieldParameter)) {
  296. acc.push(fieldParameter);
  297. }
  298. }
  299. return acc;
  300. }, []);
  301. }
  302. // Used to limit the number of results of the "filter your results" fields dropdown
  303. export const MAX_SEARCH_ITEMS = 5;
  304. // Used to set the max height of the smartSearchBar menu
  305. export const MAX_MENU_HEIGHT = 250;
  306. // Any function/field choice for Big Number widgets is legal since the
  307. // data source is from an endpoint that is not timeseries-based.
  308. // The function/field choice for World Map widget will need to be numeric-like.
  309. // Column builder for Table widget is already handled above.
  310. export function doNotValidateYAxis(displayType: DisplayType) {
  311. return displayType === DisplayType.BIG_NUMBER;
  312. }
  313. export function filterPrimaryOptions({
  314. option,
  315. widgetType,
  316. displayType,
  317. }: {
  318. displayType: DisplayType;
  319. option: FieldValueOption;
  320. widgetType?: WidgetType;
  321. }) {
  322. if (widgetType === WidgetType.RELEASE) {
  323. if (displayType === DisplayType.TABLE) {
  324. return [
  325. FieldValueKind.FUNCTION,
  326. FieldValueKind.FIELD,
  327. FieldValueKind.NUMERIC_METRICS,
  328. ].includes(option.value.kind);
  329. }
  330. if (displayType === DisplayType.TOP_N) {
  331. return option.value.kind === FieldValueKind.TAG;
  332. }
  333. }
  334. // Only validate function names for timeseries widgets and
  335. // world map widgets.
  336. if (!doNotValidateYAxis(displayType) && option.value.kind === FieldValueKind.FUNCTION) {
  337. const primaryOutput = aggregateFunctionOutputType(option.value.meta.name, undefined);
  338. if (primaryOutput) {
  339. // If a function returns a specific type, then validate it.
  340. return isLegalYAxisType(primaryOutput);
  341. }
  342. }
  343. return [FieldValueKind.FUNCTION, FieldValueKind.NUMERIC_METRICS].includes(
  344. option.value.kind
  345. );
  346. }
  347. export function getResultsLimit(numQueries: number, numYAxes: number) {
  348. if (numQueries === 0 || numYAxes === 0) {
  349. return DEFAULT_RESULTS_LIMIT;
  350. }
  351. return Math.floor(RESULTS_LIMIT / (numQueries * numYAxes));
  352. }
  353. export function getIsTimeseriesChart(displayType: DisplayType) {
  354. return [DisplayType.LINE, DisplayType.AREA, DisplayType.BAR].includes(displayType);
  355. }