utils.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import {browserHistory} from 'react-router';
  2. import {Theme} from '@emotion/react';
  3. import {Location} from 'history';
  4. import {LineChartSeries} from 'sentry/components/charts/lineChart';
  5. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  6. import {backend, frontend, mobile} from 'sentry/data/platformCategories';
  7. import {t} from 'sentry/locale';
  8. import {
  9. NewQuery,
  10. Organization,
  11. OrganizationSummary,
  12. PageFilters,
  13. Project,
  14. ReleaseProject,
  15. } from 'sentry/types';
  16. import {Series} from 'sentry/types/echarts';
  17. import {trackAnalytics} from 'sentry/utils/analytics';
  18. import {statsPeriodToDays} from 'sentry/utils/dates';
  19. import {tooltipFormatter} from 'sentry/utils/discover/charts';
  20. import EventView, {EventData} from 'sentry/utils/discover/eventView';
  21. import {TRACING_FIELDS} from 'sentry/utils/discover/fields';
  22. import {getDuration} from 'sentry/utils/formatters';
  23. import getCurrentSentryReactTransaction from 'sentry/utils/getCurrentSentryReactTransaction';
  24. import {decodeScalar} from 'sentry/utils/queryString';
  25. import toArray from 'sentry/utils/toArray';
  26. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  27. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  28. import {
  29. NormalizedTrendsTransaction,
  30. TrendChangeType,
  31. } from 'sentry/views/performance/trends/types';
  32. import {DEFAULT_MAX_DURATION, getSelectedQueryKey} from './trends/utils';
  33. export const QUERY_KEYS = [
  34. 'environment',
  35. 'project',
  36. 'query',
  37. 'start',
  38. 'end',
  39. 'statsPeriod',
  40. ] as const;
  41. export const UNPARAMETERIZED_TRANSACTION = '<< unparameterized >>'; // Represents 'other' transactions with high cardinality names that were dropped on the metrics dataset.
  42. const UNPARAMETRIZED_TRANSACTION = '<< unparametrized >>'; // Old spelling. Can be deleted in the future when all data for this transaction name is gone.
  43. export const EXCLUDE_METRICS_UNPARAM_CONDITIONS = `(!transaction:"${UNPARAMETERIZED_TRANSACTION}" AND !transaction:"${UNPARAMETRIZED_TRANSACTION}")`;
  44. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  45. export enum DiscoverQueryPageSource {
  46. PERFORMANCE = 'performance',
  47. DISCOVER = 'discover',
  48. }
  49. export function createUnnamedTransactionsDiscoverTarget(props: {
  50. location: Location;
  51. organization: Organization;
  52. source?: DiscoverQueryPageSource;
  53. }) {
  54. const fields =
  55. props.source === DiscoverQueryPageSource.DISCOVER
  56. ? ['transaction', 'project', 'transaction.source', 'epm()']
  57. : ['transaction', 'project', 'transaction.source', 'epm()', 'p50()', 'p95()'];
  58. const query: NewQuery = {
  59. id: undefined,
  60. name:
  61. props.source === DiscoverQueryPageSource.DISCOVER
  62. ? t('Unparameterized Transactions')
  63. : t('Performance - Unparameterized Transactions'),
  64. query: 'event.type:transaction transaction.source:"url"',
  65. projects: [],
  66. fields,
  67. version: 2,
  68. };
  69. const discoverEventView = EventView.fromNewQueryWithLocation(
  70. query,
  71. props.location
  72. ).withSorts([{field: 'epm', kind: 'desc'}]);
  73. const target = discoverEventView.getResultsViewUrlTarget(props.organization.slug);
  74. target.query[SHOW_UNPARAM_BANNER] = 'true';
  75. return target;
  76. }
  77. /**
  78. * Performance type can used to determine a default view or which specific field should be used by default on pages
  79. * where we don't want to wait for transaction data to return to determine how to display aspects of a page.
  80. */
  81. export enum PROJECT_PERFORMANCE_TYPE {
  82. ANY = 'any', // Fallback to transaction duration
  83. FRONTEND = 'frontend',
  84. BACKEND = 'backend',
  85. FRONTEND_OTHER = 'frontend_other',
  86. MOBILE = 'mobile',
  87. }
  88. // The native SDK is equally used on clients and end-devices as on
  89. // backend, the default view should be "All Transactions".
  90. const FRONTEND_PLATFORMS: string[] = frontend.filter(
  91. platform =>
  92. // Next, Remix and Sveltekit habe both, frontend and backend transactions.
  93. !['javascript-nextjs', 'javascript-remix', 'javascript-sveltekit'].includes(platform)
  94. );
  95. const BACKEND_PLATFORMS: string[] = backend.filter(platform => platform !== 'native');
  96. const MOBILE_PLATFORMS: string[] = [...mobile];
  97. export function platformToPerformanceType(
  98. projects: (Project | ReleaseProject)[],
  99. projectIds: readonly number[]
  100. ) {
  101. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  102. return PROJECT_PERFORMANCE_TYPE.ANY;
  103. }
  104. const selectedProjects = projects.filter(p =>
  105. projectIds.includes(parseInt(`${p.id}`, 10))
  106. );
  107. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  108. return PROJECT_PERFORMANCE_TYPE.ANY;
  109. }
  110. const projectPerformanceTypes = new Set<PROJECT_PERFORMANCE_TYPE>();
  111. selectedProjects.forEach(project => {
  112. if (FRONTEND_PLATFORMS.includes(project.platform ?? '')) {
  113. projectPerformanceTypes.add(PROJECT_PERFORMANCE_TYPE.FRONTEND);
  114. }
  115. if (BACKEND_PLATFORMS.includes(project.platform ?? '')) {
  116. projectPerformanceTypes.add(PROJECT_PERFORMANCE_TYPE.BACKEND);
  117. }
  118. if (MOBILE_PLATFORMS.includes(project.platform ?? '')) {
  119. projectPerformanceTypes.add(PROJECT_PERFORMANCE_TYPE.MOBILE);
  120. }
  121. });
  122. const uniquePerformanceTypeCount = projectPerformanceTypes.size;
  123. if (!uniquePerformanceTypeCount || uniquePerformanceTypeCount > 1) {
  124. return PROJECT_PERFORMANCE_TYPE.ANY;
  125. }
  126. const [platformType] = projectPerformanceTypes;
  127. return platformType;
  128. }
  129. /**
  130. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  131. */
  132. export function platformAndConditionsToPerformanceType(
  133. projects: Project[],
  134. eventView: EventView
  135. ) {
  136. const performanceType = platformToPerformanceType(projects, eventView.project);
  137. if (performanceType === PROJECT_PERFORMANCE_TYPE.FRONTEND) {
  138. const conditions = new MutableSearch(eventView.query);
  139. const ops = conditions.getFilterValues('!transaction.op');
  140. if (ops.some(op => op === 'pageload')) {
  141. return PROJECT_PERFORMANCE_TYPE.FRONTEND_OTHER;
  142. }
  143. }
  144. return performanceType;
  145. }
  146. /**
  147. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  148. */
  149. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  150. return (
  151. platformAndConditionsToPerformanceType(projects, eventView) ===
  152. PROJECT_PERFORMANCE_TYPE.FRONTEND
  153. );
  154. }
  155. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  156. return (
  157. platformAndConditionsToPerformanceType(projects, eventView) ===
  158. PROJECT_PERFORMANCE_TYPE.FRONTEND ||
  159. platformAndConditionsToPerformanceType(projects, eventView) ===
  160. PROJECT_PERFORMANCE_TYPE.FRONTEND_OTHER
  161. );
  162. }
  163. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  164. return `/organizations/${organization.slug}/performance/`;
  165. }
  166. export function getPerformanceTrendsUrl(organization: OrganizationSummary): string {
  167. return `/organizations/${organization.slug}/performance/trends/`;
  168. }
  169. export function getTransactionSearchQuery(location: Location, query: string = '') {
  170. return decodeScalar(location.query.query, query).trim();
  171. }
  172. export function handleTrendsClick({
  173. location,
  174. organization,
  175. projectPlatforms,
  176. }: {
  177. location: Location;
  178. organization: Organization;
  179. projectPlatforms: string;
  180. }) {
  181. trackAnalytics('performance_views.change_view', {
  182. organization,
  183. view_name: 'TRENDS',
  184. project_platforms: projectPlatforms,
  185. });
  186. const target = trendsTargetRoute({location, organization});
  187. browserHistory.push(normalizeUrl(target));
  188. }
  189. export function trendsTargetRoute({
  190. location,
  191. organization,
  192. initialConditions,
  193. additionalQuery,
  194. }: {
  195. location: Location;
  196. organization: Organization;
  197. additionalQuery?: {[x: string]: string};
  198. initialConditions?: MutableSearch;
  199. }) {
  200. const newQuery = {
  201. ...location.query,
  202. ...additionalQuery,
  203. };
  204. const query = decodeScalar(location.query.query, '');
  205. const conditions = new MutableSearch(query);
  206. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  207. if (conditions.hasFilter('tpm()')) {
  208. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  209. } else {
  210. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  211. }
  212. // Metrics don't support duration filters
  213. if (!organization.features.includes('performance-new-trends')) {
  214. if (conditions.hasFilter('transaction.duration')) {
  215. modifiedConditions.setFilterValues(
  216. 'transaction.duration',
  217. conditions.getFilterValues('transaction.duration')
  218. );
  219. } else {
  220. modifiedConditions.setFilterValues('transaction.duration', [
  221. '>0',
  222. `<${DEFAULT_MAX_DURATION}`,
  223. ]);
  224. }
  225. }
  226. newQuery.query = modifiedConditions.formatString();
  227. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  228. }
  229. export function removeTracingKeysFromSearch(
  230. currentFilter: MutableSearch,
  231. options: {excludeTagKeys: Set<string>} = {
  232. excludeTagKeys: new Set([
  233. // event type can be "transaction" but we're searching for issues
  234. 'event.type',
  235. // the project is already determined by the transaction,
  236. // and issue search does not support the project filter
  237. 'project',
  238. ]),
  239. }
  240. ) {
  241. currentFilter.getFilterKeys().forEach(tagKey => {
  242. const searchKey = tagKey.startsWith('!') ? tagKey.substring(1) : tagKey;
  243. // Remove aggregates and transaction event fields
  244. if (
  245. // aggregates
  246. searchKey.match(/\w+\(.*\)/) ||
  247. // transaction event fields
  248. TRACING_FIELDS.includes(searchKey) ||
  249. // tags that we don't want to pass to pass to issue search
  250. options.excludeTagKeys.has(searchKey)
  251. ) {
  252. currentFilter.removeFilter(tagKey);
  253. }
  254. });
  255. return currentFilter;
  256. }
  257. export function addRoutePerformanceContext(selection: PageFilters) {
  258. const transaction = getCurrentSentryReactTransaction();
  259. const days = statsPeriodToDays(
  260. selection.datetime.period,
  261. selection.datetime.start,
  262. selection.datetime.end
  263. );
  264. const oneDay = 86400;
  265. const seconds = Math.floor(days * oneDay);
  266. transaction?.setTag('query.period', seconds.toString());
  267. let groupedPeriod = '>30d';
  268. if (seconds <= oneDay) {
  269. groupedPeriod = '<=1d';
  270. } else if (seconds <= oneDay * 7) {
  271. groupedPeriod = '<=7d';
  272. } else if (seconds <= oneDay * 14) {
  273. groupedPeriod = '<=14d';
  274. } else if (seconds <= oneDay * 30) {
  275. groupedPeriod = '<=30d';
  276. }
  277. transaction?.setTag('query.period.grouped', groupedPeriod);
  278. }
  279. export function getTransactionName(location: Location): string | undefined {
  280. const {transaction} = location.query;
  281. return decodeScalar(transaction);
  282. }
  283. export function getPerformanceDuration(milliseconds: number) {
  284. return getDuration(milliseconds / 1000, milliseconds > 1000 ? 2 : 0, true);
  285. }
  286. export function areMultipleProjectsSelected(eventView: EventView) {
  287. if (!eventView.project.length) {
  288. return true; // My projects
  289. }
  290. if (eventView.project.length === 1 && eventView.project[0] === ALL_ACCESS_PROJECTS) {
  291. return true; // All projects
  292. }
  293. return false;
  294. }
  295. export function getSelectedProjectPlatformsArray(
  296. location: Location,
  297. projects: Project[]
  298. ) {
  299. const projectQuery = location.query.project;
  300. const selectedProjectIdSet = new Set(toArray(projectQuery));
  301. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  302. if (selectedProjectIdSet.has(project.id)) {
  303. acc.push(project.platform ?? 'undefined');
  304. }
  305. return acc;
  306. }, []);
  307. return selectedProjectPlatforms;
  308. }
  309. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  310. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  311. return selectedProjectPlatforms.join(', ');
  312. }
  313. export function getProjectID(
  314. eventData: EventData,
  315. projects: Project[]
  316. ): string | undefined {
  317. const projectSlug = (eventData?.project as string) || undefined;
  318. if (typeof projectSlug === undefined) {
  319. return undefined;
  320. }
  321. return projects.find(currentProject => currentProject.slug === projectSlug)?.id;
  322. }
  323. export function transformTransaction(
  324. transaction: NormalizedTrendsTransaction
  325. ): NormalizedTrendsTransaction {
  326. if (transaction && transaction.breakpoint) {
  327. return {
  328. ...transaction,
  329. breakpoint: transaction.breakpoint * 1000,
  330. };
  331. }
  332. return transaction;
  333. }
  334. export function getIntervalLine(
  335. theme: Theme,
  336. series: Series[],
  337. intervalRatio: number,
  338. label: boolean,
  339. transaction?: NormalizedTrendsTransaction
  340. ): LineChartSeries[] {
  341. if (!transaction || !series.length || !series[0].data || !series[0].data.length) {
  342. return [];
  343. }
  344. const transformedTransaction = transformTransaction(transaction);
  345. const seriesStart = parseInt(series[0].data[0].name as string, 10);
  346. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 10);
  347. if (seriesEnd < seriesStart) {
  348. return [];
  349. }
  350. const periodLine: LineChartSeries = {
  351. data: [],
  352. color: theme.textColor,
  353. markLine: {
  354. data: [],
  355. label: {},
  356. lineStyle: {
  357. color: theme.textColor,
  358. type: 'dashed',
  359. width: label ? 1 : 2,
  360. },
  361. symbol: ['none', 'none'],
  362. tooltip: {
  363. show: false,
  364. },
  365. },
  366. seriesName: 'Baseline',
  367. };
  368. const periodLineLabel = {
  369. fontSize: 11,
  370. show: label,
  371. color: theme.textColor,
  372. silent: label,
  373. };
  374. const previousPeriod = {
  375. ...periodLine,
  376. markLine: {...periodLine.markLine},
  377. seriesName: 'Baseline',
  378. };
  379. const currentPeriod = {
  380. ...periodLine,
  381. markLine: {...periodLine.markLine},
  382. seriesName: 'Baseline',
  383. };
  384. const periodDividingLine = {
  385. ...periodLine,
  386. markLine: {...periodLine.markLine},
  387. seriesName: 'Baseline',
  388. };
  389. const seriesDiff = seriesEnd - seriesStart;
  390. const seriesLine = seriesDiff * intervalRatio + seriesStart;
  391. const {breakpoint} = transformedTransaction;
  392. const divider = breakpoint || seriesLine;
  393. previousPeriod.markLine.data = [
  394. [
  395. {value: 'Past', coord: [seriesStart, transformedTransaction.aggregate_range_1]},
  396. {coord: [divider, transformedTransaction.aggregate_range_1]},
  397. ],
  398. ];
  399. previousPeriod.markLine.tooltip = {
  400. formatter: () => {
  401. return [
  402. '<div class="tooltip-series tooltip-series-solo">',
  403. '<div>',
  404. `<span class="tooltip-label"><strong>${t('Past Baseline')}</strong></span>`,
  405. // p50() coerces the axis to be time based
  406. tooltipFormatter(transformedTransaction.aggregate_range_1, 'duration'),
  407. '</div>',
  408. '</div>',
  409. '<div class="tooltip-arrow"></div>',
  410. ].join('');
  411. },
  412. };
  413. currentPeriod.markLine.data = [
  414. [
  415. {value: 'Present', coord: [divider, transformedTransaction.aggregate_range_2]},
  416. {coord: [seriesEnd, transformedTransaction.aggregate_range_2]},
  417. ],
  418. ];
  419. currentPeriod.markLine.tooltip = {
  420. formatter: () => {
  421. return [
  422. '<div class="tooltip-series tooltip-series-solo">',
  423. '<div>',
  424. `<span class="tooltip-label"><strong>${t('Present Baseline')}</strong></span>`,
  425. // p50() coerces the axis to be time based
  426. tooltipFormatter(transformedTransaction.aggregate_range_2, 'duration'),
  427. '</div>',
  428. '</div>',
  429. '<div class="tooltip-arrow"></div>',
  430. ].join('');
  431. },
  432. };
  433. periodDividingLine.markLine = {
  434. data: [
  435. {
  436. xAxis: divider,
  437. },
  438. ],
  439. label: {show: false},
  440. lineStyle: {
  441. color: theme.textColor,
  442. type: 'solid',
  443. width: 2,
  444. },
  445. symbol: ['none', 'none'],
  446. tooltip: {
  447. show: false,
  448. },
  449. silent: true,
  450. };
  451. previousPeriod.markLine.label = {
  452. ...periodLineLabel,
  453. formatter: 'Past',
  454. position: 'insideStartBottom',
  455. };
  456. currentPeriod.markLine.label = {
  457. ...periodLineLabel,
  458. formatter: 'Present',
  459. position: 'insideEndBottom',
  460. };
  461. const additionalLineSeries = [previousPeriod, currentPeriod, periodDividingLine];
  462. return additionalLineSeries;
  463. }
  464. export function getSelectedTransaction(
  465. location: Location,
  466. trendChangeType: TrendChangeType,
  467. transactions?: NormalizedTrendsTransaction[]
  468. ): NormalizedTrendsTransaction | undefined {
  469. const queryKey = getSelectedQueryKey(trendChangeType);
  470. const selectedTransactionName = decodeScalar(location.query[queryKey]);
  471. if (!transactions) {
  472. return undefined;
  473. }
  474. const selectedTransaction = transactions.find(
  475. transaction =>
  476. `${transaction.transaction}-${transaction.project}` === selectedTransactionName
  477. );
  478. if (selectedTransaction) {
  479. return selectedTransaction;
  480. }
  481. return transactions.length > 0 ? transactions[0] : undefined;
  482. }