utils.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557
  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 ProjectPerformanceType {
  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 ProjectPerformanceType.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 ProjectPerformanceType.ANY;
  109. }
  110. const projectPerformanceTypes = new Set<ProjectPerformanceType>();
  111. selectedProjects.forEach(project => {
  112. if (FRONTEND_PLATFORMS.includes(project.platform ?? '')) {
  113. projectPerformanceTypes.add(ProjectPerformanceType.FRONTEND);
  114. }
  115. if (BACKEND_PLATFORMS.includes(project.platform ?? '')) {
  116. projectPerformanceTypes.add(ProjectPerformanceType.BACKEND);
  117. }
  118. if (MOBILE_PLATFORMS.includes(project.platform ?? '')) {
  119. projectPerformanceTypes.add(ProjectPerformanceType.MOBILE);
  120. }
  121. });
  122. const uniquePerformanceTypeCount = projectPerformanceTypes.size;
  123. if (!uniquePerformanceTypeCount || uniquePerformanceTypeCount > 1) {
  124. return ProjectPerformanceType.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 === ProjectPerformanceType.FRONTEND) {
  138. const conditions = new MutableSearch(eventView.query);
  139. const ops = conditions.getFilterValues('!transaction.op');
  140. if (ops.some(op => op === 'pageload')) {
  141. return ProjectPerformanceType.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. ProjectPerformanceType.FRONTEND
  153. );
  154. }
  155. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  156. return (
  157. platformAndConditionsToPerformanceType(projects, eventView) ===
  158. ProjectPerformanceType.FRONTEND ||
  159. platformAndConditionsToPerformanceType(projects, eventView) ===
  160. ProjectPerformanceType.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. // Trends on metrics don't need these conditions
  208. if (!organization.features.includes('performance-new-trends')) {
  209. // No need to carry over tpm filters to transaction summary
  210. if (conditions.hasFilter('tpm()')) {
  211. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  212. } else {
  213. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  214. }
  215. if (conditions.hasFilter('transaction.duration')) {
  216. modifiedConditions.setFilterValues(
  217. 'transaction.duration',
  218. conditions.getFilterValues('transaction.duration')
  219. );
  220. } else {
  221. modifiedConditions.setFilterValues('transaction.duration', [
  222. '>0',
  223. `<${DEFAULT_MAX_DURATION}`,
  224. ]);
  225. }
  226. }
  227. newQuery.query = modifiedConditions.formatString();
  228. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  229. }
  230. export function removeTracingKeysFromSearch(
  231. currentFilter: MutableSearch,
  232. options: {excludeTagKeys: Set<string>} = {
  233. excludeTagKeys: new Set([
  234. // event type can be "transaction" but we're searching for issues
  235. 'event.type',
  236. // the project is already determined by the transaction,
  237. // and issue search does not support the project filter
  238. 'project',
  239. ]),
  240. }
  241. ) {
  242. currentFilter.getFilterKeys().forEach(tagKey => {
  243. const searchKey = tagKey.startsWith('!') ? tagKey.substring(1) : tagKey;
  244. // Remove aggregates and transaction event fields
  245. if (
  246. // aggregates
  247. searchKey.match(/\w+\(.*\)/) ||
  248. // transaction event fields
  249. TRACING_FIELDS.includes(searchKey) ||
  250. // tags that we don't want to pass to pass to issue search
  251. options.excludeTagKeys.has(searchKey)
  252. ) {
  253. currentFilter.removeFilter(tagKey);
  254. }
  255. });
  256. return currentFilter;
  257. }
  258. export function addRoutePerformanceContext(selection: PageFilters) {
  259. const transaction = getCurrentSentryReactTransaction();
  260. const days = statsPeriodToDays(
  261. selection.datetime.period,
  262. selection.datetime.start,
  263. selection.datetime.end
  264. );
  265. const oneDay = 86400;
  266. const seconds = Math.floor(days * oneDay);
  267. transaction?.setTag('query.period', seconds.toString());
  268. let groupedPeriod = '>30d';
  269. if (seconds <= oneDay) {
  270. groupedPeriod = '<=1d';
  271. } else if (seconds <= oneDay * 7) {
  272. groupedPeriod = '<=7d';
  273. } else if (seconds <= oneDay * 14) {
  274. groupedPeriod = '<=14d';
  275. } else if (seconds <= oneDay * 30) {
  276. groupedPeriod = '<=30d';
  277. }
  278. transaction?.setTag('query.period.grouped', groupedPeriod);
  279. }
  280. export function getTransactionName(location: Location): string | undefined {
  281. const {transaction} = location.query;
  282. return decodeScalar(transaction);
  283. }
  284. export function getPerformanceDuration(milliseconds: number) {
  285. return getDuration(milliseconds / 1000, milliseconds > 1000 ? 2 : 0, true);
  286. }
  287. export function getIsMultiProject(projects: readonly number[] | number[]) {
  288. if (!projects.length) {
  289. return true; // My projects
  290. }
  291. if (projects.length === 1 && projects[0] === ALL_ACCESS_PROJECTS) {
  292. return true; // All projects
  293. }
  294. return false;
  295. }
  296. export function getSelectedProjectPlatformsArray(
  297. location: Location,
  298. projects: Project[]
  299. ) {
  300. const projectQuery = location.query.project;
  301. const selectedProjectIdSet = new Set(toArray(projectQuery));
  302. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  303. if (selectedProjectIdSet.has(project.id)) {
  304. acc.push(project.platform ?? 'undefined');
  305. }
  306. return acc;
  307. }, []);
  308. return selectedProjectPlatforms;
  309. }
  310. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  311. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  312. return selectedProjectPlatforms.join(', ');
  313. }
  314. export function getProject(
  315. eventData: EventData,
  316. projects: Project[]
  317. ): Project | undefined {
  318. const projectSlug = (eventData?.project as string) || undefined;
  319. if (typeof projectSlug === undefined) {
  320. return undefined;
  321. }
  322. return projects.find(currentProject => currentProject.slug === projectSlug);
  323. }
  324. export function getProjectID(
  325. eventData: EventData,
  326. projects: Project[]
  327. ): string | undefined {
  328. return getProject(eventData, projects)?.id;
  329. }
  330. export function transformTransaction(
  331. transaction: NormalizedTrendsTransaction
  332. ): NormalizedTrendsTransaction {
  333. if (transaction && transaction.breakpoint) {
  334. return {
  335. ...transaction,
  336. breakpoint: transaction.breakpoint * 1000,
  337. };
  338. }
  339. return transaction;
  340. }
  341. export function getIntervalLine(
  342. theme: Theme,
  343. series: Series[],
  344. intervalRatio: number,
  345. label: boolean,
  346. transaction?: NormalizedTrendsTransaction
  347. ): LineChartSeries[] {
  348. if (!transaction || !series.length || !series[0].data || !series[0].data.length) {
  349. return [];
  350. }
  351. const transformedTransaction = transformTransaction(transaction);
  352. const seriesStart = parseInt(series[0].data[0].name as string, 10);
  353. const seriesEnd = parseInt(series[0].data.slice(-1)[0].name as string, 10);
  354. if (seriesEnd < seriesStart) {
  355. return [];
  356. }
  357. const periodLine: LineChartSeries = {
  358. data: [],
  359. color: theme.textColor,
  360. markLine: {
  361. data: [],
  362. label: {},
  363. lineStyle: {
  364. color: theme.textColor,
  365. type: 'dashed',
  366. width: label ? 1 : 2,
  367. },
  368. symbol: ['none', 'none'],
  369. tooltip: {
  370. show: false,
  371. },
  372. },
  373. seriesName: 'Baseline',
  374. };
  375. const periodLineLabel = {
  376. fontSize: 11,
  377. show: label,
  378. color: theme.textColor,
  379. silent: label,
  380. };
  381. const previousPeriod = {
  382. ...periodLine,
  383. markLine: {...periodLine.markLine},
  384. seriesName: 'Baseline',
  385. };
  386. const currentPeriod = {
  387. ...periodLine,
  388. markLine: {...periodLine.markLine},
  389. seriesName: 'Baseline',
  390. };
  391. const periodDividingLine = {
  392. ...periodLine,
  393. markLine: {...periodLine.markLine},
  394. seriesName: 'Baseline',
  395. };
  396. const seriesDiff = seriesEnd - seriesStart;
  397. const seriesLine = seriesDiff * intervalRatio + seriesStart;
  398. const {breakpoint} = transformedTransaction;
  399. const divider = breakpoint || seriesLine;
  400. previousPeriod.markLine.data = [
  401. [
  402. {value: 'Past', coord: [seriesStart, transformedTransaction.aggregate_range_1]},
  403. {coord: [divider, transformedTransaction.aggregate_range_1]},
  404. ],
  405. ];
  406. previousPeriod.markLine.tooltip = {
  407. formatter: () => {
  408. return [
  409. '<div class="tooltip-series tooltip-series-solo">',
  410. '<div>',
  411. `<span class="tooltip-label"><strong>${t('Past Baseline')}</strong></span>`,
  412. // p50() coerces the axis to be time based
  413. tooltipFormatter(transformedTransaction.aggregate_range_1, 'duration'),
  414. '</div>',
  415. '</div>',
  416. '<div class="tooltip-arrow"></div>',
  417. ].join('');
  418. },
  419. };
  420. currentPeriod.markLine.data = [
  421. [
  422. {value: 'Present', coord: [divider, transformedTransaction.aggregate_range_2]},
  423. {coord: [seriesEnd, transformedTransaction.aggregate_range_2]},
  424. ],
  425. ];
  426. currentPeriod.markLine.tooltip = {
  427. formatter: () => {
  428. return [
  429. '<div class="tooltip-series tooltip-series-solo">',
  430. '<div>',
  431. `<span class="tooltip-label"><strong>${t('Present Baseline')}</strong></span>`,
  432. // p50() coerces the axis to be time based
  433. tooltipFormatter(transformedTransaction.aggregate_range_2, 'duration'),
  434. '</div>',
  435. '</div>',
  436. '<div class="tooltip-arrow"></div>',
  437. ].join('');
  438. },
  439. };
  440. periodDividingLine.markLine = {
  441. data: [
  442. {
  443. xAxis: divider,
  444. },
  445. ],
  446. label: {show: false},
  447. lineStyle: {
  448. color: theme.textColor,
  449. type: 'solid',
  450. width: 2,
  451. },
  452. symbol: ['none', 'none'],
  453. tooltip: {
  454. show: false,
  455. },
  456. silent: true,
  457. };
  458. previousPeriod.markLine.label = {
  459. ...periodLineLabel,
  460. formatter: 'Past',
  461. position: 'insideStartBottom',
  462. };
  463. currentPeriod.markLine.label = {
  464. ...periodLineLabel,
  465. formatter: 'Present',
  466. position: 'insideEndBottom',
  467. };
  468. const additionalLineSeries = [previousPeriod, currentPeriod, periodDividingLine];
  469. return additionalLineSeries;
  470. }
  471. export function getSelectedTransaction(
  472. location: Location,
  473. trendChangeType: TrendChangeType,
  474. transactions?: NormalizedTrendsTransaction[]
  475. ): NormalizedTrendsTransaction | undefined {
  476. const queryKey = getSelectedQueryKey(trendChangeType);
  477. const selectedTransactionName = decodeScalar(location.query[queryKey]);
  478. if (!transactions) {
  479. return undefined;
  480. }
  481. const selectedTransaction = transactions.find(
  482. transaction =>
  483. `${transaction.transaction}-${transaction.project}` === selectedTransactionName
  484. );
  485. if (selectedTransaction) {
  486. return selectedTransaction;
  487. }
  488. return transactions.length > 0 ? transactions[0] : undefined;
  489. }