utils.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. import cloneDeep from 'lodash/cloneDeep';
  2. import isEqual from 'lodash/isEqual';
  3. import trimStart from 'lodash/trimStart';
  4. import type {FieldValue} from 'sentry/components/forms/types';
  5. import {t} from 'sentry/locale';
  6. import type {SelectValue} from 'sentry/types/core';
  7. import type {TagCollection} from 'sentry/types/group';
  8. import type {OrganizationSummary} from 'sentry/types/organization';
  9. import {
  10. aggregateFunctionOutputType,
  11. aggregateOutputType,
  12. AGGREGATIONS,
  13. getEquationAliasIndex,
  14. isEquation,
  15. isEquationAlias,
  16. isLegalYAxisType,
  17. type QueryFieldValue,
  18. SPAN_OP_BREAKDOWN_FIELDS,
  19. stripDerivedMetricsPrefix,
  20. stripEquationPrefix,
  21. } from 'sentry/utils/discover/fields';
  22. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  23. import type {MeasurementCollection} from 'sentry/utils/measurements/measurements';
  24. import type {Widget, WidgetQuery} from 'sentry/views/dashboards/types';
  25. import {DisplayType, WidgetType} from 'sentry/views/dashboards/types';
  26. import {
  27. appendFieldIfUnknown,
  28. type FieldValueOption,
  29. } from 'sentry/views/discover/table/queryField';
  30. import {FieldValueKind} from 'sentry/views/discover/table/types';
  31. import {generateFieldOptions} from 'sentry/views/discover/utils';
  32. import {IssueSortOptions} from 'sentry/views/issueList/utils';
  33. import type {FlatValidationError, ValidationError} from '../utils';
  34. import {getNumEquations} from '../utils';
  35. import {DISABLED_SORT, TAG_SORT_DENY_LIST} from './releaseWidget/fields';
  36. // Used in the widget builder to limit the number of lines plotted in the chart
  37. export const DEFAULT_RESULTS_LIMIT = 5;
  38. const RESULTS_LIMIT = 10;
  39. // Both dashboards and widgets use the 'new' keyword when creating
  40. export const NEW_DASHBOARD_ID = 'new';
  41. export enum DataSet {
  42. EVENTS = 'events',
  43. ISSUES = 'issues',
  44. RELEASES = 'releases',
  45. METRICS = 'metrics',
  46. ERRORS = 'error-events',
  47. TRANSACTIONS = 'transaction-like',
  48. }
  49. export enum SortDirection {
  50. HIGH_TO_LOW = 'high_to_low',
  51. LOW_TO_HIGH = 'low_to_high',
  52. }
  53. export const sortDirections = {
  54. [SortDirection.HIGH_TO_LOW]: t('High to low'),
  55. [SortDirection.LOW_TO_HIGH]: t('Low to high'),
  56. };
  57. export const displayTypes = {
  58. [DisplayType.AREA]: t('Area Chart'),
  59. [DisplayType.BAR]: t('Bar Chart'),
  60. [DisplayType.LINE]: t('Line Chart'),
  61. [DisplayType.TABLE]: t('Table'),
  62. [DisplayType.BIG_NUMBER]: t('Big Number'),
  63. };
  64. export function getDiscoverDatasetFromWidgetType(widgetType: WidgetType) {
  65. switch (widgetType) {
  66. case WidgetType.TRANSACTIONS:
  67. return DiscoverDatasets.METRICS_ENHANCED;
  68. case WidgetType.ERRORS:
  69. return DiscoverDatasets.ERRORS;
  70. default:
  71. return undefined;
  72. }
  73. }
  74. export function mapErrors(
  75. data: ValidationError,
  76. update: FlatValidationError
  77. ): FlatValidationError {
  78. Object.keys(data).forEach((key: string) => {
  79. const value = data[key];
  80. if (typeof value === 'string') {
  81. update[key] = value;
  82. return;
  83. }
  84. // Recurse into nested objects.
  85. if (Array.isArray(value) && typeof value[0] === 'string') {
  86. update[key] = value[0];
  87. return;
  88. }
  89. if (Array.isArray(value) && typeof value[0] === 'object') {
  90. update[key] = (value as ValidationError[]).map(item => mapErrors(item, {}));
  91. } else {
  92. update[key] = mapErrors(value as ValidationError, {});
  93. }
  94. });
  95. return update;
  96. }
  97. export const generateOrderOptions = ({
  98. aggregates,
  99. columns,
  100. widgetType,
  101. }: {
  102. aggregates: string[];
  103. columns: string[];
  104. widgetType: WidgetType;
  105. }): SelectValue<string>[] => {
  106. const isRelease = widgetType === WidgetType.RELEASE;
  107. const options: SelectValue<string>[] = [];
  108. let equations = 0;
  109. (isRelease
  110. ? [...aggregates.map(stripDerivedMetricsPrefix), ...columns]
  111. : [...aggregates, ...columns]
  112. )
  113. .filter(field => !!field)
  114. .filter(field => !DISABLED_SORT.includes(field))
  115. .filter(field => (isRelease ? !TAG_SORT_DENY_LIST.includes(field) : true))
  116. .forEach(field => {
  117. let alias;
  118. const label = stripEquationPrefix(field);
  119. // Equations are referenced via a standard alias following this pattern
  120. if (isEquation(field)) {
  121. alias = `equation[${equations}]`;
  122. equations += 1;
  123. }
  124. options.push({label, value: alias ?? field});
  125. });
  126. return options;
  127. };
  128. export function normalizeQueries({
  129. displayType,
  130. queries,
  131. widgetType,
  132. }: {
  133. displayType: DisplayType;
  134. queries: Widget['queries'];
  135. widgetType?: Widget['widgetType'];
  136. }): Widget['queries'] {
  137. const isTimeseriesChart = getIsTimeseriesChart(displayType);
  138. const isTabularChart = [DisplayType.TABLE, DisplayType.TOP_N].includes(displayType);
  139. queries = cloneDeep(queries);
  140. if ([DisplayType.TABLE, DisplayType.BIG_NUMBER].includes(displayType)) {
  141. // Some display types may only support at most 1 query.
  142. queries = queries.slice(0, 1);
  143. } else if (isTimeseriesChart) {
  144. // Timeseries charts supports at most 3 queries.
  145. queries = queries.slice(0, 3);
  146. }
  147. queries = queries.map(query => {
  148. const {fields = [], columns} = query;
  149. if (isTabularChart) {
  150. // If the groupBy field has values, port everything over to the columnEditCollect field.
  151. query.fields = [...new Set([...fields, ...columns])];
  152. } else {
  153. // If columnEditCollect has field values , port everything over to the groupBy field.
  154. query.fields = fields.filter(field => !columns.includes(field));
  155. }
  156. if (
  157. getIsTimeseriesChart(displayType) &&
  158. !query.columns.filter(column => !!column).length
  159. ) {
  160. // The orderby is only applicable for timeseries charts when there's a
  161. // grouping selected, if all fields are empty then we also reset the orderby
  162. query.orderby = '';
  163. return query;
  164. }
  165. const queryOrderBy =
  166. widgetType === WidgetType.RELEASE
  167. ? stripDerivedMetricsPrefix(queries[0].orderby)
  168. : queries[0].orderby;
  169. const rawOrderBy = trimStart(queryOrderBy, '-');
  170. const resetOrderBy =
  171. // Raw Equation from Top N only applies to timeseries
  172. (isTabularChart && isEquation(rawOrderBy)) ||
  173. // Not contained as tag, field, or function
  174. (!isEquation(rawOrderBy) &&
  175. !isEquationAlias(rawOrderBy) &&
  176. ![...query.columns, ...query.aggregates].includes(rawOrderBy)) ||
  177. // Equation alias and not contained
  178. (isEquationAlias(rawOrderBy) &&
  179. getEquationAliasIndex(rawOrderBy) >
  180. getNumEquations([...query.columns, ...query.aggregates]) - 1);
  181. const orderBy =
  182. (!resetOrderBy && trimStart(queryOrderBy, '-')) ||
  183. (widgetType === WidgetType.ISSUE
  184. ? queryOrderBy ?? IssueSortOptions.DATE
  185. : generateOrderOptions({
  186. widgetType: widgetType ?? WidgetType.DISCOVER,
  187. columns: queries[0].columns,
  188. aggregates: queries[0].aggregates,
  189. })[0]?.value);
  190. if (!orderBy) {
  191. query.orderby = '';
  192. return query;
  193. }
  194. // A widget should be descending if:
  195. // - There is no orderby, so we're defaulting to desc
  196. // - Not an issues widget since issues doesn't support descending and
  197. // the original ordering was descending
  198. const isDescending =
  199. !query.orderby || (widgetType !== WidgetType.ISSUE && queryOrderBy.startsWith('-'));
  200. query.orderby = isDescending ? `-${String(orderBy)}` : String(orderBy);
  201. return query;
  202. });
  203. if (isTabularChart) {
  204. return queries;
  205. }
  206. // Filter out non-aggregate fields
  207. queries = queries.map(query => {
  208. let aggregates = query.aggregates;
  209. if (isTimeseriesChart) {
  210. // Filter out fields that will not generate numeric output types
  211. aggregates = aggregates.filter(aggregate =>
  212. isLegalYAxisType(aggregateOutputType(aggregate))
  213. );
  214. }
  215. if (isTimeseriesChart && aggregates.length && aggregates.length > 3) {
  216. // Timeseries charts supports at most 3 fields.
  217. aggregates = aggregates.slice(0, 3);
  218. }
  219. return {
  220. ...query,
  221. fields: aggregates.length ? aggregates : ['count()'],
  222. columns: query.columns ? query.columns : [],
  223. aggregates: aggregates.length ? aggregates : ['count()'],
  224. };
  225. });
  226. if (isTimeseriesChart) {
  227. // For timeseries widget, all queries must share identical set of fields.
  228. const referenceAggregates = [...queries[0].aggregates];
  229. queryLoop: for (const query of queries) {
  230. if (referenceAggregates.length >= 3) {
  231. break;
  232. }
  233. if (isEqual(referenceAggregates, query.aggregates)) {
  234. continue;
  235. }
  236. for (const aggregate of query.aggregates) {
  237. if (referenceAggregates.length >= 3) {
  238. break queryLoop;
  239. }
  240. if (!referenceAggregates.includes(aggregate)) {
  241. referenceAggregates.push(aggregate);
  242. }
  243. }
  244. }
  245. queries = queries.map(query => {
  246. return {
  247. ...query,
  248. columns: query.columns ? query.columns : [],
  249. aggregates: referenceAggregates,
  250. fields: referenceAggregates,
  251. };
  252. });
  253. }
  254. if (DisplayType.BIG_NUMBER === displayType) {
  255. // For world map chart, cap fields of the queries to only one field.
  256. queries = queries.map(query => {
  257. return {
  258. ...query,
  259. fields: query.aggregates.slice(0, 1),
  260. aggregates: query.aggregates.slice(0, 1),
  261. orderby: '',
  262. columns: [],
  263. };
  264. });
  265. }
  266. return queries;
  267. }
  268. export function getParsedDefaultWidgetQuery(query = ''): WidgetQuery | undefined {
  269. // "any" was needed here because it doesn't pass in getsentry
  270. const urlSeachParams = new URLSearchParams(query) as any;
  271. const parsedQuery = Object.fromEntries(urlSeachParams.entries());
  272. if (!Object.keys(parsedQuery).length) {
  273. return undefined;
  274. }
  275. const columns = parsedQuery.columns ? getFields(parsedQuery.columns) : [];
  276. const aggregates = parsedQuery.aggregates ? getFields(parsedQuery.aggregates) : [];
  277. const fields = [...columns, ...aggregates];
  278. return {
  279. ...parsedQuery,
  280. fields,
  281. columns,
  282. aggregates,
  283. } as WidgetQuery;
  284. }
  285. export function getFields(fieldsString: string): string[] {
  286. // Use a negative lookahead to avoid splitting on commas inside equation fields
  287. return fieldsString.split(/,(?![^(]*\))/g);
  288. }
  289. export function getAmendedFieldOptions({
  290. measurements,
  291. organization,
  292. tags,
  293. }: {
  294. measurements: MeasurementCollection;
  295. organization: OrganizationSummary;
  296. tags: TagCollection;
  297. }) {
  298. return generateFieldOptions({
  299. organization,
  300. tagKeys: Object.values(tags).map(({key}) => key),
  301. measurementKeys: Object.values(measurements).map(({key}) => key),
  302. spanOperationBreakdownKeys: SPAN_OP_BREAKDOWN_FIELDS,
  303. });
  304. }
  305. // Extract metric names from aggregation functions present in the widget queries
  306. export function getMetricFields(queries: WidgetQuery[]) {
  307. return queries.reduce<string[]>((acc, query) => {
  308. for (const field of [...query.aggregates, ...query.columns]) {
  309. const fieldParameter = /\(([^)]*)\)/.exec(field)?.[1];
  310. if (fieldParameter && !acc.includes(fieldParameter)) {
  311. acc.push(fieldParameter);
  312. }
  313. }
  314. return acc;
  315. }, []);
  316. }
  317. // Used to limit the number of results of the "filter your results" fields dropdown
  318. export const MAX_SEARCH_ITEMS = 5;
  319. // Used to set the max height of the smartSearchBar menu
  320. export const MAX_MENU_HEIGHT = 250;
  321. // Any function/field choice for Big Number widgets is legal since the
  322. // data source is from an endpoint that is not timeseries-based.
  323. // The function/field choice for World Map widget will need to be numeric-like.
  324. // Column builder for Table widget is already handled above.
  325. export function doNotValidateYAxis(displayType: DisplayType) {
  326. return displayType === DisplayType.BIG_NUMBER;
  327. }
  328. export function filterPrimaryOptions({
  329. option,
  330. widgetType,
  331. displayType,
  332. }: {
  333. displayType: DisplayType;
  334. option: FieldValueOption;
  335. widgetType?: WidgetType;
  336. }) {
  337. if (widgetType === WidgetType.RELEASE) {
  338. if (displayType === DisplayType.TABLE) {
  339. return [
  340. FieldValueKind.FUNCTION,
  341. FieldValueKind.FIELD,
  342. FieldValueKind.NUMERIC_METRICS,
  343. ].includes(option.value.kind);
  344. }
  345. if (displayType === DisplayType.TOP_N) {
  346. return option.value.kind === FieldValueKind.TAG;
  347. }
  348. }
  349. // Only validate function names for timeseries widgets and
  350. // world map widgets.
  351. if (!doNotValidateYAxis(displayType) && option.value.kind === FieldValueKind.FUNCTION) {
  352. const primaryOutput = aggregateFunctionOutputType(option.value.meta.name, undefined);
  353. if (primaryOutput) {
  354. // If a function returns a specific type, then validate it.
  355. return isLegalYAxisType(primaryOutput);
  356. }
  357. }
  358. return [FieldValueKind.FUNCTION, FieldValueKind.NUMERIC_METRICS].includes(
  359. option.value.kind
  360. );
  361. }
  362. export function getResultsLimit(numQueries: number, numYAxes: number) {
  363. if (numQueries === 0 || numYAxes === 0) {
  364. return DEFAULT_RESULTS_LIMIT;
  365. }
  366. return Math.floor(RESULTS_LIMIT / (numQueries * numYAxes));
  367. }
  368. export function getIsTimeseriesChart(displayType: DisplayType) {
  369. return [DisplayType.LINE, DisplayType.AREA, DisplayType.BAR].includes(displayType);
  370. }
  371. // Handle adding functions to the field options
  372. // Field and equations are already compatible
  373. export function getFieldOptionFormat(
  374. field: QueryFieldValue
  375. ): [string, FieldValueOption] | null {
  376. if (field.kind === 'function') {
  377. // Show the ellipsis if there are parameters that actually have values
  378. const ellipsis =
  379. field.function.slice(1).map(Boolean).filter(Boolean).length > 0 ? '\u2026' : '';
  380. const functionName = field.alias || field.function[0];
  381. return [
  382. `function:${functionName}`,
  383. {
  384. label: `${functionName}(${ellipsis})`,
  385. value: {
  386. kind: FieldValueKind.FUNCTION,
  387. meta: {
  388. name: functionName,
  389. parameters: AGGREGATIONS[field.function[0]].parameters.map(param => ({
  390. ...param,
  391. columnTypes: props => {
  392. // HACK: Forcibly allow the parameter if it's already set, this allows
  393. // us to render the option even if it's not compatible with the dataset.
  394. if (props.name === field.function[1]) {
  395. return true;
  396. }
  397. // default behavior
  398. if (typeof param.columnTypes === 'function') {
  399. return param.columnTypes(props);
  400. }
  401. return param.columnTypes;
  402. },
  403. })),
  404. },
  405. },
  406. },
  407. ];
  408. }
  409. return null;
  410. }
  411. /**
  412. * Adds the incompatible functions (i.e. functions that aren't already
  413. * in the field options) to the field options. This updates fieldOptions
  414. * in place and returns the keys that were added for extra validation/filtering
  415. *
  416. * The function depends on the consistent structure of field definition for
  417. * functions where the first element is the function name and the second
  418. * element is the first argument to the function, which is a field/tag.
  419. */
  420. export function addIncompatibleFunctions(
  421. fields: QueryFieldValue[],
  422. fieldOptions: Record<string, SelectValue<FieldValue>>
  423. ): Set<string> {
  424. const injectedFieldKeys: Set<string> = new Set();
  425. fields.forEach(field => {
  426. // Inject functions that aren't compatible with the current dataset
  427. if (field.kind === 'function') {
  428. const functionName = field.alias || field.function[0];
  429. if (!(`function:${functionName}` in fieldOptions)) {
  430. const formattedField = getFieldOptionFormat(field);
  431. if (formattedField) {
  432. const [key, value] = formattedField;
  433. fieldOptions[key] = value;
  434. injectedFieldKeys.add(key);
  435. // If the function needs to be injected, inject the parameter as a tag
  436. // as well if it isn't already an option
  437. if (
  438. field.function[1] &&
  439. !fieldOptions[`field:${field.function[1]}`] &&
  440. !fieldOptions[`tag:${field.function[1]}`]
  441. ) {
  442. fieldOptions = appendFieldIfUnknown(fieldOptions, {
  443. kind: FieldValueKind.TAG,
  444. meta: {
  445. dataType: 'string',
  446. name: field.function[1],
  447. unknown: true,
  448. },
  449. });
  450. }
  451. }
  452. }
  453. }
  454. });
  455. return injectedFieldKeys;
  456. }