utils.tsx 18 KB

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