utils.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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 ([DisplayType.TABLE, DisplayType.BIG_NUMBER].includes(displayType)) {
  122. // Some display types may only support at most 1 query.
  123. queries = queries.slice(0, 1);
  124. } else if (isTimeseriesChart) {
  125. // Timeseries charts supports at most 3 queries.
  126. queries = queries.slice(0, 3);
  127. }
  128. queries = queries.map(query => {
  129. const {fields = [], columns} = query;
  130. if (isTabularChart) {
  131. // If the groupBy field has values, port everything over to the columnEditCollect field.
  132. query.fields = [...new Set([...fields, ...columns])];
  133. } else {
  134. // If columnEditCollect has field values , port everything over to the groupBy field.
  135. query.fields = fields.filter(field => !columns.includes(field));
  136. }
  137. if (
  138. getIsTimeseriesChart(displayType) &&
  139. !query.columns.filter(column => !!column).length
  140. ) {
  141. // The orderby is only applicable for timeseries charts when there's a
  142. // grouping selected, if all fields are empty then we also reset the orderby
  143. query.orderby = '';
  144. return query;
  145. }
  146. const queryOrderBy =
  147. widgetType === WidgetType.RELEASE
  148. ? stripDerivedMetricsPrefix(queries[0].orderby)
  149. : queries[0].orderby;
  150. const rawOrderBy = trimStart(queryOrderBy, '-');
  151. const resetOrderBy =
  152. // Raw Equation from Top N only applies to timeseries
  153. (isTabularChart && isEquation(rawOrderBy)) ||
  154. // Not contained as tag, field, or function
  155. (!isEquation(rawOrderBy) &&
  156. !isEquationAlias(rawOrderBy) &&
  157. ![...query.columns, ...query.aggregates].includes(rawOrderBy)) ||
  158. // Equation alias and not contained
  159. (isEquationAlias(rawOrderBy) &&
  160. getEquationAliasIndex(rawOrderBy) >
  161. getNumEquations([...query.columns, ...query.aggregates]) - 1);
  162. const orderBy =
  163. (!resetOrderBy && trimStart(queryOrderBy, '-')) ||
  164. (widgetType === WidgetType.ISSUE
  165. ? queryOrderBy ?? IssueSortOptions.DATE
  166. : generateOrderOptions({
  167. widgetType: widgetType ?? WidgetType.DISCOVER,
  168. columns: queries[0].columns,
  169. aggregates: queries[0].aggregates,
  170. })[0]?.value);
  171. if (!orderBy) {
  172. query.orderby = '';
  173. return query;
  174. }
  175. // A widget should be descending if:
  176. // - There is no orderby, so we're defaulting to desc
  177. // - Not an issues widget since issues doesn't support descending and
  178. // the original ordering was descending
  179. const isDescending =
  180. !query.orderby || (widgetType !== WidgetType.ISSUE && queryOrderBy.startsWith('-'));
  181. query.orderby = isDescending ? `-${String(orderBy)}` : String(orderBy);
  182. return query;
  183. });
  184. if (isTabularChart) {
  185. return queries;
  186. }
  187. // Filter out non-aggregate fields
  188. queries = queries.map(query => {
  189. let aggregates = query.aggregates;
  190. if (isTimeseriesChart) {
  191. // Filter out fields that will not generate numeric output types
  192. aggregates = aggregates.filter(aggregate =>
  193. isLegalYAxisType(aggregateOutputType(aggregate))
  194. );
  195. }
  196. if (isTimeseriesChart && aggregates.length && aggregates.length > 3) {
  197. // Timeseries charts supports at most 3 fields.
  198. aggregates = aggregates.slice(0, 3);
  199. }
  200. return {
  201. ...query,
  202. fields: aggregates.length ? aggregates : ['count()'],
  203. columns: query.columns ? query.columns : [],
  204. aggregates: aggregates.length ? aggregates : ['count()'],
  205. };
  206. });
  207. if (isTimeseriesChart) {
  208. // For timeseries widget, all queries must share identical set of fields.
  209. const referenceAggregates = [...queries[0].aggregates];
  210. queryLoop: for (const query of queries) {
  211. if (referenceAggregates.length >= 3) {
  212. break;
  213. }
  214. if (isEqual(referenceAggregates, query.aggregates)) {
  215. continue;
  216. }
  217. for (const aggregate of query.aggregates) {
  218. if (referenceAggregates.length >= 3) {
  219. break queryLoop;
  220. }
  221. if (!referenceAggregates.includes(aggregate)) {
  222. referenceAggregates.push(aggregate);
  223. }
  224. }
  225. }
  226. queries = queries.map(query => {
  227. return {
  228. ...query,
  229. columns: query.columns ? query.columns : [],
  230. aggregates: referenceAggregates,
  231. fields: referenceAggregates,
  232. };
  233. });
  234. }
  235. if (DisplayType.BIG_NUMBER === displayType) {
  236. // For world map chart, cap fields of the queries to only one field.
  237. queries = queries.map(query => {
  238. return {
  239. ...query,
  240. fields: query.aggregates.slice(0, 1),
  241. aggregates: query.aggregates.slice(0, 1),
  242. orderby: '',
  243. columns: [],
  244. };
  245. });
  246. }
  247. return queries;
  248. }
  249. export function getParsedDefaultWidgetQuery(query = ''): WidgetQuery | undefined {
  250. // "any" was needed here because it doesn't pass in getsentry
  251. const urlSeachParams = new URLSearchParams(query) as any;
  252. const parsedQuery = Object.fromEntries(urlSeachParams.entries());
  253. if (!Object.keys(parsedQuery).length) {
  254. return undefined;
  255. }
  256. const columns = parsedQuery.columns ? getFields(parsedQuery.columns) : [];
  257. const aggregates = parsedQuery.aggregates ? getFields(parsedQuery.aggregates) : [];
  258. const fields = [...columns, ...aggregates];
  259. return {
  260. ...parsedQuery,
  261. fields,
  262. columns,
  263. aggregates,
  264. } as WidgetQuery;
  265. }
  266. export function getFields(fieldsString: string): string[] {
  267. // Use a negative lookahead to avoid splitting on commas inside equation fields
  268. return fieldsString.split(/,(?![^(]*\))/g);
  269. }
  270. export function getAmendedFieldOptions({
  271. measurements,
  272. organization,
  273. tags,
  274. }: {
  275. measurements: MeasurementCollection;
  276. organization: OrganizationSummary;
  277. tags: TagCollection;
  278. }) {
  279. return generateFieldOptions({
  280. organization,
  281. tagKeys: Object.values(tags).map(({key}) => key),
  282. measurementKeys: Object.values(measurements).map(({key}) => key),
  283. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  284. });
  285. }
  286. // Extract metric names from aggregation functions present in the widget queries
  287. export function getMetricFields(queries: WidgetQuery[]) {
  288. return queries.reduce<string[]>((acc, query) => {
  289. for (const field of [...query.aggregates, ...query.columns]) {
  290. const fieldParameter = /\(([^)]*)\)/.exec(field)?.[1];
  291. if (fieldParameter && !acc.includes(fieldParameter)) {
  292. acc.push(fieldParameter);
  293. }
  294. }
  295. return acc;
  296. }, []);
  297. }
  298. // Used to limit the number of results of the "filter your results" fields dropdown
  299. export const MAX_SEARCH_ITEMS = 5;
  300. // Used to set the max height of the smartSearchBar menu
  301. export const MAX_MENU_HEIGHT = 250;
  302. // Any function/field choice for Big Number widgets is legal since the
  303. // data source is from an endpoint that is not timeseries-based.
  304. // The function/field choice for World Map widget will need to be numeric-like.
  305. // Column builder for Table widget is already handled above.
  306. export function doNotValidateYAxis(displayType: DisplayType) {
  307. return displayType === DisplayType.BIG_NUMBER;
  308. }
  309. export function filterPrimaryOptions({
  310. option,
  311. widgetType,
  312. displayType,
  313. }: {
  314. displayType: DisplayType;
  315. option: FieldValueOption;
  316. widgetType?: WidgetType;
  317. }) {
  318. if (widgetType === WidgetType.RELEASE) {
  319. if (displayType === DisplayType.TABLE) {
  320. return [
  321. FieldValueKind.FUNCTION,
  322. FieldValueKind.FIELD,
  323. FieldValueKind.NUMERIC_METRICS,
  324. ].includes(option.value.kind);
  325. }
  326. if (displayType === DisplayType.TOP_N) {
  327. return option.value.kind === FieldValueKind.TAG;
  328. }
  329. }
  330. // Only validate function names for timeseries widgets and
  331. // world map widgets.
  332. if (!doNotValidateYAxis(displayType) && option.value.kind === FieldValueKind.FUNCTION) {
  333. const primaryOutput = aggregateFunctionOutputType(option.value.meta.name, undefined);
  334. if (primaryOutput) {
  335. // If a function returns a specific type, then validate it.
  336. return isLegalYAxisType(primaryOutput);
  337. }
  338. }
  339. return [FieldValueKind.FUNCTION, FieldValueKind.NUMERIC_METRICS].includes(
  340. option.value.kind
  341. );
  342. }
  343. export function getResultsLimit(numQueries: number, numYAxes: number) {
  344. if (numQueries === 0 || numYAxes === 0) {
  345. return DEFAULT_RESULTS_LIMIT;
  346. }
  347. return Math.floor(RESULTS_LIMIT / (numQueries * numYAxes));
  348. }
  349. export function getIsTimeseriesChart(displayType: DisplayType) {
  350. return [DisplayType.LINE, DisplayType.AREA, DisplayType.BAR].includes(displayType);
  351. }