utils.tsx 12 KB

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