utils.tsx 17 KB

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