utils.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 {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.WORLD_MAP:
  227. discoverLocation.query.display = DisplayModes.WORLDMAP;
  228. break;
  229. case DisplayType.BAR:
  230. discoverLocation.query.display = DisplayModes.BAR;
  231. break;
  232. case DisplayType.TOP_N:
  233. discoverLocation.query.display = DisplayModes.TOP5;
  234. // Last field is used as the yAxis
  235. const aggregates = widget.queries[0].aggregates;
  236. discoverLocation.query.yAxis = aggregates[aggregates.length - 1];
  237. if (aggregates.slice(0, -1).includes(aggregates[aggregates.length - 1])) {
  238. discoverLocation.query.field = aggregates.slice(0, -1);
  239. }
  240. break;
  241. default:
  242. break;
  243. }
  244. // Equation fields need to have their terms explicitly selected as columns in the discover table
  245. const fields = discoverLocation.query.field;
  246. const query = widget.queries[0];
  247. const queryFields = defined(query.fields)
  248. ? query.fields
  249. : [...query.columns, ...query.aggregates];
  250. const equationFields = getFieldsFromEquations(queryFields);
  251. // Updates fields by adding any individual terms from equation fields as a column
  252. equationFields.forEach(term => {
  253. if (Array.isArray(fields) && !fields.includes(term)) {
  254. fields.unshift(term);
  255. }
  256. });
  257. if (isMetricsData) {
  258. discoverLocation.query.fromMetric = 'true';
  259. }
  260. // Construct and return the discover url
  261. const discoverPath = `${discoverLocation.pathname}?${qs.stringify({
  262. ...discoverLocation.query,
  263. })}`;
  264. return discoverPath;
  265. }
  266. export function getWidgetIssueUrl(
  267. widget: Widget,
  268. selection: PageFilters,
  269. organization: Organization
  270. ) {
  271. const {start, end, utc, period} = selection.datetime;
  272. const datetime =
  273. start && end
  274. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  275. : {statsPeriod: period};
  276. const issuesLocation = `/organizations/${organization.slug}/issues/?${qs.stringify({
  277. query: widget.queries?.[0]?.conditions,
  278. sort: widget.queries?.[0]?.orderby,
  279. ...datetime,
  280. project: selection.projects,
  281. environment: selection.environments,
  282. })}`;
  283. return issuesLocation;
  284. }
  285. export function getWidgetReleasesUrl(
  286. _widget: Widget,
  287. selection: PageFilters,
  288. organization: Organization
  289. ) {
  290. const {start, end, utc, period} = selection.datetime;
  291. const datetime =
  292. start && end
  293. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  294. : {statsPeriod: period};
  295. const releasesLocation = `/organizations/${organization.slug}/releases/?${qs.stringify({
  296. ...datetime,
  297. project: selection.projects,
  298. environment: selection.environments,
  299. })}`;
  300. return releasesLocation;
  301. }
  302. export function flattenErrors(
  303. data: ValidationError | string,
  304. update: FlatValidationError
  305. ): FlatValidationError {
  306. if (typeof data === 'string') {
  307. update.error = data;
  308. } else {
  309. Object.keys(data).forEach((key: string) => {
  310. const value = data[key];
  311. if (typeof value === 'string') {
  312. update[key] = value;
  313. return;
  314. }
  315. // Recurse into nested objects.
  316. if (Array.isArray(value) && typeof value[0] === 'string') {
  317. update[key] = value[0];
  318. return;
  319. }
  320. if (Array.isArray(value) && typeof value[0] === 'object') {
  321. (value as ValidationError[]).map(item => flattenErrors(item, update));
  322. } else {
  323. flattenErrors(value as ValidationError, update);
  324. }
  325. });
  326. }
  327. return update;
  328. }
  329. export function getDashboardsMEPQueryParams(isMEPEnabled: boolean) {
  330. return isMEPEnabled
  331. ? {
  332. dataset: 'metricsEnhanced',
  333. }
  334. : {};
  335. }
  336. export function getNumEquations(possibleEquations: string[]) {
  337. return possibleEquations.filter(isEquation).length;
  338. }
  339. const DEFINED_MEASUREMENTS = new Set(Object.keys(getMeasurements()));
  340. export function isCustomMeasurement(field: string) {
  341. return !DEFINED_MEASUREMENTS.has(field) && isMeasurement(field);
  342. }
  343. export function isCustomMeasurementWidget(widget: Widget) {
  344. return (
  345. widget.widgetType === WidgetType.DISCOVER &&
  346. widget.queries.some(({aggregates, columns, fields}) => {
  347. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  348. // Should be ok to use getAggregateArg. getAggregateArg only returns the first arg
  349. // but there aren't any custom measurement aggregates that use custom measurements
  350. // outside of the first arg.
  351. const aggregateArg = getAggregateArg(aggregate);
  352. if (aggregateArg) {
  353. acc.push(aggregateArg);
  354. }
  355. return acc;
  356. }, []);
  357. return [...aggregateArgs, ...columns, ...(fields ?? [])].some(field =>
  358. isCustomMeasurement(field)
  359. );
  360. })
  361. );
  362. }
  363. export function getCustomMeasurementQueryParams() {
  364. return {
  365. dataset: 'metrics',
  366. };
  367. }
  368. export function isWidgetUsingTransactionName(widget: Widget) {
  369. return (
  370. widget.widgetType === WidgetType.DISCOVER &&
  371. widget.queries.some(({aggregates, columns, fields, conditions}) => {
  372. const aggregateArgs = aggregates.reduce((acc: string[], aggregate) => {
  373. const aggregateArg = getAggregateArg(aggregate);
  374. if (aggregateArg) {
  375. acc.push(aggregateArg);
  376. }
  377. return acc;
  378. }, []);
  379. const transactionSelected = [...aggregateArgs, ...columns, ...(fields ?? [])].some(
  380. field => field === 'transaction'
  381. );
  382. const transactionUsedInFilter = parseSearch(conditions)?.some(
  383. parsedCondition =>
  384. parsedCondition.type === Token.Filter &&
  385. parsedCondition.key?.text === 'transaction'
  386. );
  387. return transactionSelected || transactionUsedInFilter;
  388. })
  389. );
  390. }
  391. export function hasSavedPageFilters(dashboard: DashboardDetails) {
  392. return !(
  393. isEmpty(dashboard.projects) &&
  394. dashboard.environment === undefined &&
  395. dashboard.start === undefined &&
  396. dashboard.end === undefined &&
  397. dashboard.period === undefined
  398. );
  399. }
  400. export function hasUnsavedFilterChanges(
  401. initialDashboard: DashboardDetails,
  402. location: Location
  403. ) {
  404. // Use Sets to compare the filter fields that are arrays
  405. type Filters = {
  406. end?: string;
  407. environment?: Set<string>;
  408. period?: string;
  409. projects?: Set<number>;
  410. release?: Set<string>;
  411. start?: string;
  412. utc?: boolean;
  413. };
  414. const savedFilters: Filters = {
  415. projects: new Set(initialDashboard.projects),
  416. environment: new Set(initialDashboard.environment),
  417. period: initialDashboard.period,
  418. start: normalizeDateTimeString(initialDashboard.start),
  419. end: normalizeDateTimeString(initialDashboard.end),
  420. utc: initialDashboard.utc,
  421. };
  422. let currentFilters = {
  423. ...getCurrentPageFilters(location),
  424. } as unknown as Filters;
  425. currentFilters = {
  426. ...currentFilters,
  427. projects: new Set(currentFilters.projects),
  428. environment: new Set(currentFilters.environment),
  429. };
  430. if (defined(location.query?.release)) {
  431. // Release is only included in the comparison if it exists in the query
  432. // params, otherwise the dashboard should be using its saved state
  433. savedFilters.release = new Set(initialDashboard.filters?.release);
  434. currentFilters.release = new Set(location.query?.release);
  435. }
  436. return !isEqual(savedFilters, currentFilters);
  437. }
  438. export function getSavedFiltersAsPageFilters(dashboard: DashboardDetails): PageFilters {
  439. return {
  440. datetime: {
  441. end: dashboard.end || null,
  442. period: dashboard.period || null,
  443. start: dashboard.start || null,
  444. utc: null,
  445. },
  446. environments: dashboard.environment || [],
  447. projects: dashboard.projects || [],
  448. };
  449. }
  450. export function getSavedPageFilters(dashboard: DashboardDetails) {
  451. return {
  452. project: dashboard.projects,
  453. environment: dashboard.environment,
  454. statsPeriod: dashboard.period,
  455. start: normalizeDateTimeString(dashboard.start),
  456. end: normalizeDateTimeString(dashboard.end),
  457. utc: dashboard.utc,
  458. };
  459. }
  460. export function resetPageFilters(dashboard: DashboardDetails, location: Location) {
  461. browserHistory.replace({
  462. ...location,
  463. query: getSavedPageFilters(dashboard),
  464. });
  465. }
  466. export function getCurrentPageFilters(
  467. location: Location
  468. ): Pick<
  469. DashboardDetails,
  470. 'projects' | 'environment' | 'period' | 'start' | 'end' | 'utc'
  471. > {
  472. const {project, environment, statsPeriod, start, end, utc} = location.query ?? {};
  473. return {
  474. // Ensure projects and environment are sent as arrays, or undefined in the request
  475. // location.query will return a string if there's only one value
  476. projects:
  477. project === undefined || project === null
  478. ? []
  479. : typeof project === 'string'
  480. ? [Number(project)]
  481. : project.map(Number),
  482. environment:
  483. typeof environment === 'string' ? [environment] : environment ?? undefined,
  484. period: statsPeriod as string | undefined,
  485. start: defined(start) ? normalizeDateTimeString(start as string) : undefined,
  486. end: defined(end) ? normalizeDateTimeString(end as string) : undefined,
  487. utc: defined(utc) ? utc === 'true' : undefined,
  488. };
  489. }
  490. export function getDashboardFiltersFromURL(location: Location): DashboardFilters | null {
  491. const dashboardFilters: DashboardFilters = {};
  492. Object.values(DashboardFilterKeys).forEach(key => {
  493. if (defined(location.query?.[key])) {
  494. dashboardFilters[key] = decodeList(location.query?.[key]);
  495. }
  496. });
  497. return !isEmpty(dashboardFilters) ? dashboardFilters : null;
  498. }
  499. export function dashboardFiltersToString(
  500. dashboardFilters: DashboardFilters | null | undefined
  501. ): string {
  502. let dashboardFilterConditions = '';
  503. if (dashboardFilters) {
  504. for (const [key, activeFilters] of Object.entries(dashboardFilters)) {
  505. if (activeFilters.length === 1) {
  506. dashboardFilterConditions += `${key}:${activeFilters[0]} `;
  507. } else if (activeFilters.length > 1) {
  508. dashboardFilterConditions += `${key}:[${activeFilters.join(',')}] `;
  509. }
  510. }
  511. }
  512. return dashboardFilterConditions;
  513. }