utils.tsx 17 KB

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