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