utils.tsx 19 KB

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