utils.tsx 20 KB

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