utils.tsx 18 KB

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