utils.tsx 16 KB

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