utils.tsx 18 KB

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