utils.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. import {browserHistory} from 'react-router';
  2. import {Location, Query} from 'history';
  3. import cloneDeep from 'lodash/cloneDeep';
  4. import isEmpty from 'lodash/isEmpty';
  5. import isEqual from 'lodash/isEqual';
  6. import pick from 'lodash/pick';
  7. import trimStart from 'lodash/trimStart';
  8. import * as qs from 'query-string';
  9. import WidgetArea from 'sentry-images/dashboard/widget-area.svg';
  10. import WidgetBar from 'sentry-images/dashboard/widget-bar.svg';
  11. import WidgetBigNumber from 'sentry-images/dashboard/widget-big-number.svg';
  12. import WidgetLine from 'sentry-images/dashboard/widget-line-1.svg';
  13. import WidgetTable from 'sentry-images/dashboard/widget-table.svg';
  14. import {parseArithmetic} from 'sentry/components/arithmeticInput/parser';
  15. import {
  16. Fidelity,
  17. getDiffInMinutes,
  18. getInterval,
  19. SIX_HOURS,
  20. TWENTY_FOUR_HOURS,
  21. } from 'sentry/components/charts/utils';
  22. import {normalizeDateTimeString} from 'sentry/components/organizations/pageFilters/parse';
  23. import {parseSearch, Token} from 'sentry/components/searchSyntax/parser';
  24. import {Organization, PageFilters} from 'sentry/types';
  25. import {defined} from 'sentry/utils';
  26. import {getUtcDateString, parsePeriodToHours} from 'sentry/utils/dates';
  27. import {TableDataWithTitle} from 'sentry/utils/discover/discoverQuery';
  28. import EventView from 'sentry/utils/discover/eventView';
  29. import {DURATION_UNITS} from 'sentry/utils/discover/fieldRenderers';
  30. import {
  31. getAggregateAlias,
  32. getAggregateArg,
  33. getColumnsAndAggregates,
  34. isEquation,
  35. isMeasurement,
  36. RATE_UNIT_MULTIPLIERS,
  37. RateUnits,
  38. stripEquationPrefix,
  39. } from 'sentry/utils/discover/fields';
  40. import {DiscoverDatasets, DisplayModes} from 'sentry/utils/discover/types';
  41. import {getMeasurements} from 'sentry/utils/measurements/measurements';
  42. import {decodeList} from 'sentry/utils/queryString';
  43. import theme from 'sentry/utils/theme';
  44. import {
  45. DashboardDetails,
  46. DashboardFilterKeys,
  47. DashboardFilters,
  48. DisplayType,
  49. Widget,
  50. WidgetQuery,
  51. WidgetType,
  52. } from 'sentry/views/dashboards/types';
  53. import {
  54. ThresholdMaxKeys,
  55. ThresholdsConfig,
  56. } from './widgetBuilder/buildSteps/thresholdsStep/thresholdsStep';
  57. export type ValidationError = {
  58. [key: string]: string | string[] | ValidationError[] | ValidationError;
  59. };
  60. export type FlatValidationError = {
  61. [key: string]: string | FlatValidationError[] | FlatValidationError;
  62. };
  63. export function cloneDashboard(dashboard: DashboardDetails): DashboardDetails {
  64. return cloneDeep(dashboard);
  65. }
  66. export function eventViewFromWidget(
  67. title: string,
  68. query: WidgetQuery,
  69. selection: PageFilters
  70. ): EventView {
  71. const {start, end, period: statsPeriod} = selection.datetime;
  72. const {projects, environments} = selection;
  73. // World Map requires an additional column (geo.country_code) to display in discover when navigating from the widget
  74. const fields = [...query.columns, ...query.aggregates];
  75. const conditions = query.conditions;
  76. const {orderby} = query;
  77. // Need to convert orderby to aggregate alias because eventView still uses aggregate alias format
  78. const aggregateAliasOrderBy = orderby
  79. ? `${orderby.startsWith('-') ? '-' : ''}${getAggregateAlias(trimStart(orderby, '-'))}`
  80. : orderby;
  81. return EventView.fromSavedQuery({
  82. id: undefined,
  83. name: title,
  84. version: 2,
  85. fields,
  86. query: conditions,
  87. orderby: aggregateAliasOrderBy,
  88. projects,
  89. range: statsPeriod ?? undefined,
  90. start: start ? getUtcDateString(start) : undefined,
  91. end: end ? getUtcDateString(end) : undefined,
  92. environment: environments,
  93. });
  94. }
  95. export function getThresholdUnitSelectOptions(
  96. dataType: string
  97. ): {label: string; value: string}[] {
  98. if (dataType === 'duration') {
  99. return Object.keys(DURATION_UNITS)
  100. .map(unit => ({label: unit, value: unit}))
  101. .slice(2);
  102. }
  103. if (dataType === 'rate') {
  104. return Object.values(RateUnits).map(unit => ({
  105. label: `/${unit.split('/')[1]}`,
  106. value: unit,
  107. }));
  108. }
  109. return [];
  110. }
  111. export function hasThresholdMaxValue(thresholdsConfig: ThresholdsConfig): boolean {
  112. return Object.keys(thresholdsConfig.max_values).length > 0;
  113. }
  114. function normalizeUnit(value: number, unit: string, dataType: string): number {
  115. const multiplier =
  116. dataType === 'rate'
  117. ? RATE_UNIT_MULTIPLIERS[unit]
  118. : dataType === 'duration'
  119. ? DURATION_UNITS[unit]
  120. : 1;
  121. return value * multiplier;
  122. }
  123. export function getWidgetIndicatorColor(
  124. thresholds: ThresholdsConfig,
  125. tableData: TableDataWithTitle[]
  126. ): string {
  127. const tableMeta = {...tableData[0].meta};
  128. const fields = Object.keys(tableMeta);
  129. const field = fields[0];
  130. const dataType = tableMeta[field];
  131. const dataUnit = tableMeta.units?.[field];
  132. const data = Number(tableData[0].data[0][field]);
  133. const normalizedData = dataUnit ? normalizeUnit(data, dataUnit, dataType) : data;
  134. const {max_values} = thresholds;
  135. const greenMax = max_values[ThresholdMaxKeys.MAX_1];
  136. const normalizedGreenMax =
  137. thresholds.unit && greenMax
  138. ? normalizeUnit(greenMax, thresholds.unit, dataType)
  139. : greenMax;
  140. if (normalizedGreenMax && normalizedData <= normalizedGreenMax) {
  141. return theme.green300;
  142. }
  143. const yellowMax = max_values[ThresholdMaxKeys.MAX_2];
  144. const normalizedYellowMax =
  145. thresholds.unit && yellowMax
  146. ? normalizeUnit(yellowMax, thresholds.unit, dataType)
  147. : yellowMax;
  148. if (normalizedYellowMax && normalizedData <= normalizedYellowMax) {
  149. return theme.yellow300;
  150. }
  151. return theme.red300;
  152. }
  153. function coerceStringToArray(value?: string | string[] | null) {
  154. return typeof value === 'string' ? [value] : value;
  155. }
  156. export function constructWidgetFromQuery(query?: Query): Widget | undefined {
  157. if (query) {
  158. const queryNames = coerceStringToArray(query.queryNames);
  159. const queryConditions = coerceStringToArray(query.queryConditions);
  160. const queryFields = coerceStringToArray(query.queryFields);
  161. const queries: WidgetQuery[] = [];
  162. if (
  163. queryConditions &&
  164. queryNames &&
  165. queryFields &&
  166. typeof query.queryOrderby === 'string'
  167. ) {
  168. const {columns, aggregates} = getColumnsAndAggregates(queryFields);
  169. queryConditions.forEach((condition, index) => {
  170. queries.push({
  171. name: queryNames[index],
  172. conditions: condition,
  173. fields: queryFields,
  174. columns,
  175. aggregates,
  176. orderby: query.queryOrderby as string,
  177. });
  178. });
  179. }
  180. if (query.title && query.displayType && query.interval && queries.length > 0) {
  181. const newWidget: Widget = {
  182. ...(pick(query, ['title', 'displayType', 'interval']) as {
  183. displayType: DisplayType;
  184. interval: string;
  185. title: string;
  186. }),
  187. widgetType: WidgetType.DISCOVER,
  188. queries,
  189. };
  190. return newWidget;
  191. }
  192. }
  193. return undefined;
  194. }
  195. export function miniWidget(displayType: DisplayType): string {
  196. switch (displayType) {
  197. case DisplayType.BAR:
  198. return WidgetBar;
  199. case DisplayType.AREA:
  200. case DisplayType.TOP_N:
  201. return WidgetArea;
  202. case DisplayType.BIG_NUMBER:
  203. return WidgetBigNumber;
  204. case DisplayType.TABLE:
  205. return WidgetTable;
  206. case DisplayType.LINE:
  207. default:
  208. return WidgetLine;
  209. }
  210. }
  211. export function getWidgetInterval(
  212. displayType: DisplayType,
  213. datetimeObj: Partial<PageFilters['datetime']>,
  214. widgetInterval?: string,
  215. fidelity?: Fidelity
  216. ): string {
  217. // Don't fetch more than 66 bins as we're plotting on a small area.
  218. const MAX_BIN_COUNT = 66;
  219. // Bars charts are daily totals to aligned with discover. It also makes them
  220. // usefully different from line/area charts until we expose the interval control, or remove it.
  221. let interval = displayType === 'bar' ? '1d' : widgetInterval;
  222. if (!interval) {
  223. // Default to 5 minutes
  224. interval = '5m';
  225. }
  226. const desiredPeriod = parsePeriodToHours(interval);
  227. const selectedRange = getDiffInMinutes(datetimeObj);
  228. if (fidelity) {
  229. // Primarily to support lower fidelity for Release Health widgets
  230. // the sort on releases and hit the metrics API endpoint.
  231. interval = getInterval(datetimeObj, fidelity);
  232. if (selectedRange > SIX_HOURS && selectedRange <= TWENTY_FOUR_HOURS) {
  233. interval = '1h';
  234. }
  235. return displayType === 'bar' ? '1d' : interval;
  236. }
  237. // selectedRange is in minutes, desiredPeriod is in hours
  238. // convert desiredPeriod to minutes
  239. if (selectedRange / (desiredPeriod * 60) > MAX_BIN_COUNT) {
  240. const highInterval = getInterval(datetimeObj, 'high');
  241. // Only return high fidelity interval if desired interval is higher fidelity
  242. if (desiredPeriod < parsePeriodToHours(highInterval)) {
  243. return highInterval;
  244. }
  245. }
  246. return interval;
  247. }
  248. export function getFieldsFromEquations(fields: string[]): string[] {
  249. // Gather all fields and functions used in equations and prepend them to the provided fields
  250. const termsSet: Set<string> = new Set();
  251. fields.filter(isEquation).forEach(field => {
  252. const parsed = parseArithmetic(stripEquationPrefix(field)).tc;
  253. parsed.fields.forEach(({term}) => termsSet.add(term as string));
  254. parsed.functions.forEach(({term}) => termsSet.add(term as string));
  255. });
  256. return Array.from(termsSet);
  257. }
  258. export function getWidgetDiscoverUrl(
  259. widget: Widget,
  260. selection: PageFilters,
  261. organization: Organization,
  262. index: number = 0,
  263. isMetricsData: boolean = false
  264. ) {
  265. const eventView = eventViewFromWidget(widget.title, widget.queries[index], selection);
  266. const discoverLocation = eventView.getResultsViewUrlTarget(organization.slug);
  267. // Pull a max of 3 valid Y-Axis from the widget
  268. const yAxisOptions = eventView.getYAxisOptions().map(({value}) => value);
  269. discoverLocation.query.yAxis = [
  270. ...new Set(
  271. widget.queries[0].aggregates.filter(aggregate => yAxisOptions.includes(aggregate))
  272. ),
  273. ].slice(0, 3);
  274. // Visualization specific transforms
  275. switch (widget.displayType) {
  276. case DisplayType.BAR:
  277. discoverLocation.query.display = DisplayModes.BAR;
  278. break;
  279. case DisplayType.TOP_N:
  280. discoverLocation.query.display = DisplayModes.TOP5;
  281. // Last field is used as the yAxis
  282. const aggregates = widget.queries[0].aggregates;
  283. discoverLocation.query.yAxis = aggregates[aggregates.length - 1];
  284. if (aggregates.slice(0, -1).includes(aggregates[aggregates.length - 1])) {
  285. discoverLocation.query.field = aggregates.slice(0, -1);
  286. }
  287. break;
  288. default:
  289. break;
  290. }
  291. // Equation fields need to have their terms explicitly selected as columns in the discover table
  292. const fields = discoverLocation.query.field;
  293. const query = widget.queries[0];
  294. const queryFields = defined(query.fields)
  295. ? query.fields
  296. : [...query.columns, ...query.aggregates];
  297. const equationFields = getFieldsFromEquations(queryFields);
  298. // Updates fields by adding any individual terms from equation fields as a column
  299. equationFields.forEach(term => {
  300. if (Array.isArray(fields) && !fields.includes(term)) {
  301. fields.unshift(term);
  302. }
  303. });
  304. if (isMetricsData) {
  305. discoverLocation.query.fromMetric = 'true';
  306. }
  307. // Construct and return the discover url
  308. const discoverPath = `${discoverLocation.pathname}?${qs.stringify({
  309. ...discoverLocation.query,
  310. })}`;
  311. return discoverPath;
  312. }
  313. export function getWidgetIssueUrl(
  314. widget: Widget,
  315. selection: PageFilters,
  316. organization: Organization
  317. ) {
  318. const {start, end, utc, period} = selection.datetime;
  319. const datetime =
  320. start && end
  321. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  322. : {statsPeriod: period};
  323. const issuesLocation = `/organizations/${organization.slug}/issues/?${qs.stringify({
  324. query: widget.queries?.[0]?.conditions,
  325. sort: widget.queries?.[0]?.orderby,
  326. ...datetime,
  327. project: selection.projects,
  328. environment: selection.environments,
  329. })}`;
  330. return issuesLocation;
  331. }
  332. export function getWidgetReleasesUrl(
  333. _widget: Widget,
  334. selection: PageFilters,
  335. organization: Organization
  336. ) {
  337. const {start, end, utc, period} = selection.datetime;
  338. const datetime =
  339. start && end
  340. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  341. : {statsPeriod: period};
  342. const releasesLocation = `/organizations/${organization.slug}/releases/?${qs.stringify({
  343. ...datetime,
  344. project: selection.projects,
  345. environment: selection.environments,
  346. })}`;
  347. return releasesLocation;
  348. }
  349. export function flattenErrors(
  350. data: ValidationError | string,
  351. update: FlatValidationError
  352. ): FlatValidationError {
  353. if (typeof data === 'string') {
  354. update.error = data;
  355. } else {
  356. Object.keys(data).forEach((key: string) => {
  357. const value = data[key];
  358. if (typeof value === 'string') {
  359. update[key] = value;
  360. return;
  361. }
  362. // Recurse into nested objects.
  363. if (Array.isArray(value) && typeof value[0] === 'string') {
  364. update[key] = value[0];
  365. return;
  366. }
  367. if (Array.isArray(value) && typeof value[0] === 'object') {
  368. (value as ValidationError[]).map(item => flattenErrors(item, update));
  369. } else {
  370. flattenErrors(value as ValidationError, update);
  371. }
  372. });
  373. }
  374. return update;
  375. }
  376. export function getDashboardsMEPQueryParams(isMEPEnabled: boolean) {
  377. return isMEPEnabled
  378. ? {
  379. dataset: DiscoverDatasets.METRICS_ENHANCED,
  380. }
  381. : {};
  382. }
  383. export function getNumEquations(possibleEquations: string[]) {
  384. return possibleEquations.filter(isEquation).length;
  385. }
  386. const DEFINED_MEASUREMENTS = new Set(Object.keys(getMeasurements()));
  387. export function isCustomMeasurement(field: string) {
  388. return !DEFINED_MEASUREMENTS.has(field) && isMeasurement(field);
  389. }
  390. export function isCustomMeasurementWidget(widget: Widget) {
  391. return (
  392. widget.widgetType === WidgetType.DISCOVER &&
  393. widget.queries.some(({aggregates, columns, fields}) => {
  394. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  395. // Should be ok to use getAggregateArg. getAggregateArg only returns the first arg
  396. // but there aren't any custom measurement aggregates that use custom measurements
  397. // outside of the first arg.
  398. const aggregateArg = getAggregateArg(aggregate);
  399. if (aggregateArg) {
  400. acc.push(aggregateArg);
  401. }
  402. return acc;
  403. }, []);
  404. return [...aggregateArgs, ...columns, ...(fields ?? [])].some(field =>
  405. isCustomMeasurement(field)
  406. );
  407. })
  408. );
  409. }
  410. export function getCustomMeasurementQueryParams() {
  411. return {
  412. dataset: 'metrics',
  413. };
  414. }
  415. export function isWidgetUsingTransactionName(widget: Widget) {
  416. return (
  417. widget.widgetType === WidgetType.DISCOVER &&
  418. widget.queries.some(({aggregates, columns, fields, conditions}) => {
  419. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  420. const aggregateArg = getAggregateArg(aggregate);
  421. if (aggregateArg) {
  422. acc.push(aggregateArg);
  423. }
  424. return acc;
  425. }, []);
  426. const transactionSelected = [...aggregateArgs, ...columns, ...(fields ?? [])].some(
  427. field => field === 'transaction'
  428. );
  429. const transactionUsedInFilter = parseSearch(conditions)?.some(
  430. parsedCondition =>
  431. parsedCondition.type === Token.FILTER &&
  432. parsedCondition.key?.text === 'transaction'
  433. );
  434. return transactionSelected || transactionUsedInFilter;
  435. })
  436. );
  437. }
  438. export function hasSavedPageFilters(dashboard: DashboardDetails) {
  439. return !(
  440. isEmpty(dashboard.projects) &&
  441. dashboard.environment === undefined &&
  442. dashboard.start === undefined &&
  443. dashboard.end === undefined &&
  444. dashboard.period === undefined
  445. );
  446. }
  447. export function hasUnsavedFilterChanges(
  448. initialDashboard: DashboardDetails,
  449. location: Location
  450. ) {
  451. // Use Sets to compare the filter fields that are arrays
  452. type Filters = {
  453. end?: string;
  454. environment?: Set<string>;
  455. period?: string;
  456. projects?: Set<number>;
  457. release?: Set<string>;
  458. start?: string;
  459. utc?: boolean;
  460. };
  461. const savedFilters: Filters = {
  462. projects: new Set(initialDashboard.projects),
  463. environment: new Set(initialDashboard.environment),
  464. period: initialDashboard.period,
  465. start: normalizeDateTimeString(initialDashboard.start),
  466. end: normalizeDateTimeString(initialDashboard.end),
  467. utc: initialDashboard.utc,
  468. };
  469. let currentFilters = {
  470. ...getCurrentPageFilters(location),
  471. } as unknown as Filters;
  472. currentFilters = {
  473. ...currentFilters,
  474. projects: new Set(currentFilters.projects),
  475. environment: new Set(currentFilters.environment),
  476. };
  477. if (defined(location.query?.release)) {
  478. // Release is only included in the comparison if it exists in the query
  479. // params, otherwise the dashboard should be using its saved state
  480. savedFilters.release = new Set(initialDashboard.filters?.release);
  481. currentFilters.release = new Set(location.query?.release);
  482. }
  483. return !isEqual(savedFilters, currentFilters);
  484. }
  485. export function getSavedFiltersAsPageFilters(dashboard: DashboardDetails): PageFilters {
  486. return {
  487. datetime: {
  488. end: dashboard.end || null,
  489. period: dashboard.period || null,
  490. start: dashboard.start || null,
  491. utc: null,
  492. },
  493. environments: dashboard.environment || [],
  494. projects: dashboard.projects || [],
  495. };
  496. }
  497. export function getSavedPageFilters(dashboard: DashboardDetails) {
  498. return {
  499. project: dashboard.projects,
  500. environment: dashboard.environment,
  501. statsPeriod: dashboard.period,
  502. start: normalizeDateTimeString(dashboard.start),
  503. end: normalizeDateTimeString(dashboard.end),
  504. utc: dashboard.utc,
  505. };
  506. }
  507. export function resetPageFilters(dashboard: DashboardDetails, location: Location) {
  508. browserHistory.replace({
  509. ...location,
  510. query: getSavedPageFilters(dashboard),
  511. });
  512. }
  513. export function getCurrentPageFilters(
  514. location: Location
  515. ): Pick<
  516. DashboardDetails,
  517. 'projects' | 'environment' | 'period' | 'start' | 'end' | 'utc'
  518. > {
  519. const {project, environment, statsPeriod, start, end, utc} = location.query ?? {};
  520. return {
  521. // Ensure projects and environment are sent as arrays, or undefined in the request
  522. // location.query will return a string if there's only one value
  523. projects:
  524. project === undefined || project === null
  525. ? []
  526. : typeof project === 'string'
  527. ? [Number(project)]
  528. : project.map(Number),
  529. environment:
  530. typeof environment === 'string' ? [environment] : environment ?? undefined,
  531. period: statsPeriod as string | undefined,
  532. start: defined(start) ? normalizeDateTimeString(start as string) : undefined,
  533. end: defined(end) ? normalizeDateTimeString(end as string) : undefined,
  534. utc: defined(utc) ? utc === 'true' : undefined,
  535. };
  536. }
  537. export function getDashboardFiltersFromURL(location: Location): DashboardFilters | null {
  538. const dashboardFilters: DashboardFilters = {};
  539. Object.values(DashboardFilterKeys).forEach(key => {
  540. if (defined(location.query?.[key])) {
  541. dashboardFilters[key] = decodeList(location.query?.[key]);
  542. }
  543. });
  544. return !isEmpty(dashboardFilters) ? dashboardFilters : null;
  545. }
  546. export function dashboardFiltersToString(
  547. dashboardFilters: DashboardFilters | null | undefined
  548. ): string {
  549. let dashboardFilterConditions = '';
  550. if (dashboardFilters) {
  551. for (const [key, activeFilters] of Object.entries(dashboardFilters)) {
  552. if (activeFilters.length === 1) {
  553. dashboardFilterConditions += `${key}:${activeFilters[0]} `;
  554. } else if (activeFilters.length > 1) {
  555. dashboardFilterConditions += `${key}:[${activeFilters.join(',')}] `;
  556. }
  557. }
  558. }
  559. return dashboardFilterConditions;
  560. }