index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. import type {Location} from 'history';
  2. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  3. import {backend, frontend, mobile} from 'sentry/data/platformCategories';
  4. import {t} from 'sentry/locale';
  5. import type {PageFilters} from 'sentry/types/core';
  6. import type {
  7. NewQuery,
  8. Organization,
  9. OrganizationSummary,
  10. } from 'sentry/types/organization';
  11. import type {Project} from 'sentry/types/project';
  12. import type {ReleaseProject} from 'sentry/types/release';
  13. import {trackAnalytics} from 'sentry/utils/analytics';
  14. import toArray from 'sentry/utils/array/toArray';
  15. import {browserHistory} from 'sentry/utils/browserHistory';
  16. import type {EventData} from 'sentry/utils/discover/eventView';
  17. import EventView from 'sentry/utils/discover/eventView';
  18. import {TRACING_FIELDS} from 'sentry/utils/discover/fields';
  19. import {SavedQueryDatasets} from 'sentry/utils/discover/types';
  20. import {statsPeriodToDays} from 'sentry/utils/duration/statsPeriodToDays';
  21. import getCurrentSentryReactRootSpan from 'sentry/utils/getCurrentSentryReactRootSpan';
  22. import {useApiQuery} from 'sentry/utils/queryClient';
  23. import {decodeScalar} from 'sentry/utils/queryString';
  24. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  25. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import useProjects from 'sentry/utils/useProjects';
  28. import {hasDatasetSelector} from 'sentry/views/dashboards/utils';
  29. import {DOMAIN_VIEW_BASE_URL} from 'sentry/views/insights/pages/settings';
  30. import type {DomainView} from 'sentry/views/insights/pages/useFilters';
  31. import {DEFAULT_MAX_DURATION} from '../trends/utils';
  32. export const QUERY_KEYS = [
  33. 'environment',
  34. 'project',
  35. 'query',
  36. 'start',
  37. 'end',
  38. 'statsPeriod',
  39. ] as const;
  40. export const UNPARAMETERIZED_TRANSACTION = '<< unparameterized >>'; // Represents 'other' transactions with high cardinality names that were dropped on the metrics dataset.
  41. const UNPARAMETRIZED_TRANSACTION = '<< unparametrized >>'; // Old spelling. Can be deleted in the future when all data for this transaction name is gone.
  42. export const EXCLUDE_METRICS_UNPARAM_CONDITIONS = `(!transaction:"${UNPARAMETERIZED_TRANSACTION}" AND !transaction:"${UNPARAMETRIZED_TRANSACTION}")`;
  43. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  44. export enum DiscoverQueryPageSource {
  45. PERFORMANCE = 'performance',
  46. DISCOVER = 'discover',
  47. }
  48. export function createUnnamedTransactionsDiscoverTarget(props: {
  49. location: Location;
  50. organization: Organization;
  51. source?: DiscoverQueryPageSource;
  52. }) {
  53. const fields =
  54. props.source === DiscoverQueryPageSource.DISCOVER
  55. ? ['transaction', 'project', 'transaction.source', 'epm()']
  56. : ['transaction', 'project', 'transaction.source', 'epm()', 'p50()', 'p95()'];
  57. const query: NewQuery = {
  58. id: undefined,
  59. name:
  60. props.source === DiscoverQueryPageSource.DISCOVER
  61. ? t('Unparameterized Transactions')
  62. : t('Performance - Unparameterized Transactions'),
  63. query: 'event.type:transaction transaction.source:"url"',
  64. projects: [],
  65. fields,
  66. version: 2,
  67. };
  68. const discoverEventView = EventView.fromNewQueryWithLocation(
  69. query,
  70. props.location
  71. ).withSorts([{field: 'epm', kind: 'desc'}]);
  72. const target = discoverEventView.getResultsViewUrlTarget(
  73. props.organization.slug,
  74. false,
  75. hasDatasetSelector(props.organization) ? SavedQueryDatasets.TRANSACTIONS : undefined
  76. );
  77. target.query[SHOW_UNPARAM_BANNER] = 'true';
  78. return target;
  79. }
  80. /**
  81. * Performance type can used to determine a default view or which specific field should be used by default on pages
  82. * where we don't want to wait for transaction data to return to determine how to display aspects of a page.
  83. */
  84. export enum ProjectPerformanceType {
  85. ANY = 'any', // Fallback to transaction duration
  86. FRONTEND = 'frontend',
  87. BACKEND = 'backend',
  88. FRONTEND_OTHER = 'frontend_other',
  89. MOBILE = 'mobile',
  90. }
  91. // The native SDK is equally used on clients and end-devices as on
  92. // backend, the default view should be "All Transactions".
  93. const FRONTEND_PLATFORMS: string[] = frontend.filter(
  94. platform =>
  95. // Next, Remix and Sveltekit have both, frontend and backend transactions.
  96. !['javascript-nextjs', 'javascript-remix', 'javascript-sveltekit'].includes(platform)
  97. );
  98. const BACKEND_PLATFORMS: string[] = backend.filter(
  99. platform => platform !== 'native' && platform !== 'nintendo-switch'
  100. );
  101. const MOBILE_PLATFORMS: string[] = [...mobile];
  102. export function platformToPerformanceType(
  103. projects: Array<Project | ReleaseProject>,
  104. projectIds: readonly number[]
  105. ) {
  106. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  107. return ProjectPerformanceType.ANY;
  108. }
  109. const selectedProjects = projects.filter(p =>
  110. projectIds.includes(parseInt(`${p.id}`, 10))
  111. );
  112. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  113. return ProjectPerformanceType.ANY;
  114. }
  115. const projectPerformanceTypes = new Set<ProjectPerformanceType>();
  116. selectedProjects.forEach(project => {
  117. if (FRONTEND_PLATFORMS.includes(project.platform ?? '')) {
  118. projectPerformanceTypes.add(ProjectPerformanceType.FRONTEND);
  119. }
  120. if (BACKEND_PLATFORMS.includes(project.platform ?? '')) {
  121. projectPerformanceTypes.add(ProjectPerformanceType.BACKEND);
  122. }
  123. if (MOBILE_PLATFORMS.includes(project.platform ?? '')) {
  124. projectPerformanceTypes.add(ProjectPerformanceType.MOBILE);
  125. }
  126. });
  127. const uniquePerformanceTypeCount = projectPerformanceTypes.size;
  128. if (!uniquePerformanceTypeCount || uniquePerformanceTypeCount > 1) {
  129. return ProjectPerformanceType.ANY;
  130. }
  131. const [PlatformKey] = projectPerformanceTypes;
  132. return PlatformKey;
  133. }
  134. export function platformToDomainView(
  135. projects: Array<Project | ReleaseProject>,
  136. projectIds: readonly number[]
  137. ): DomainView | undefined {
  138. const performanceType = platformToPerformanceType(projects, projectIds);
  139. switch (performanceType) {
  140. case ProjectPerformanceType.FRONTEND:
  141. return 'frontend';
  142. case ProjectPerformanceType.BACKEND:
  143. return 'backend';
  144. case ProjectPerformanceType.MOBILE:
  145. return 'mobile';
  146. default:
  147. return undefined;
  148. }
  149. }
  150. /**
  151. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  152. */
  153. export function platformAndConditionsToPerformanceType(
  154. projects: Project[],
  155. eventView: EventView
  156. ) {
  157. const performanceType = platformToPerformanceType(projects, eventView.project);
  158. if (performanceType === ProjectPerformanceType.FRONTEND) {
  159. const conditions = new MutableSearch(eventView.query);
  160. const ops = conditions.getFilterValues('!transaction.op');
  161. if (ops.some(op => op === 'pageload')) {
  162. return ProjectPerformanceType.FRONTEND_OTHER;
  163. }
  164. }
  165. return performanceType;
  166. }
  167. /**
  168. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  169. */
  170. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  171. return (
  172. platformAndConditionsToPerformanceType(projects, eventView) ===
  173. ProjectPerformanceType.FRONTEND
  174. );
  175. }
  176. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  177. return (
  178. platformAndConditionsToPerformanceType(projects, eventView) ===
  179. ProjectPerformanceType.FRONTEND ||
  180. platformAndConditionsToPerformanceType(projects, eventView) ===
  181. ProjectPerformanceType.FRONTEND_OTHER
  182. );
  183. }
  184. // TODO - remove in favour of `getPerformanceBaseUrl`
  185. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  186. return `${getPerformanceBaseUrl(organization.slug)}/`;
  187. }
  188. export function getPerformanceTrendsUrl(
  189. organization: OrganizationSummary,
  190. view?: DomainView
  191. ): string {
  192. return `${getPerformanceBaseUrl(organization.slug, view)}/trends/`;
  193. }
  194. export function getTransactionSearchQuery(location: Location, query: string = '') {
  195. return decodeScalar(location.query.query, query).trim();
  196. }
  197. export function handleTrendsClick({
  198. location,
  199. organization,
  200. projectPlatforms,
  201. }: {
  202. location: Location;
  203. organization: Organization;
  204. projectPlatforms: string;
  205. }) {
  206. trackAnalytics('performance_views.change_view', {
  207. organization,
  208. view_name: 'TRENDS',
  209. project_platforms: projectPlatforms,
  210. });
  211. const target = trendsTargetRoute({location, organization});
  212. browserHistory.push(normalizeUrl(target));
  213. }
  214. export function trendsTargetRoute({
  215. location,
  216. organization,
  217. initialConditions,
  218. additionalQuery,
  219. view,
  220. }: {
  221. location: Location;
  222. organization: Organization;
  223. additionalQuery?: {[x: string]: string};
  224. initialConditions?: MutableSearch;
  225. view?: DomainView;
  226. }) {
  227. const newQuery = {
  228. ...location.query,
  229. ...additionalQuery,
  230. };
  231. const query = decodeScalar(location.query.query, '');
  232. const conditions = new MutableSearch(query);
  233. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  234. // Trends on metrics don't need these conditions
  235. if (!organization.features.includes('performance-new-trends')) {
  236. // No need to carry over tpm filters to transaction summary
  237. if (conditions.hasFilter('tpm()')) {
  238. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  239. } else {
  240. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  241. }
  242. if (conditions.hasFilter('transaction.duration')) {
  243. modifiedConditions.setFilterValues(
  244. 'transaction.duration',
  245. conditions.getFilterValues('transaction.duration')
  246. );
  247. } else {
  248. modifiedConditions.setFilterValues('transaction.duration', [
  249. '>0',
  250. `<${DEFAULT_MAX_DURATION}`,
  251. ]);
  252. }
  253. }
  254. newQuery.query = modifiedConditions.formatString();
  255. return {pathname: getPerformanceTrendsUrl(organization, view), query: {...newQuery}};
  256. }
  257. export function removeTracingKeysFromSearch(
  258. currentFilter: MutableSearch,
  259. options: {excludeTagKeys: Set<string>} = {
  260. excludeTagKeys: new Set([
  261. // event type can be "transaction" but we're searching for issues
  262. 'event.type',
  263. // the project is already determined by the transaction,
  264. // and issue search does not support the project filter
  265. 'project',
  266. ]),
  267. }
  268. ) {
  269. currentFilter.getFilterKeys().forEach(tagKey => {
  270. const searchKey = tagKey.startsWith('!') ? tagKey.substring(1) : tagKey;
  271. // Remove aggregates and transaction event fields
  272. if (
  273. // aggregates
  274. searchKey.match(/\w+\(.*\)/) ||
  275. // transaction event fields
  276. TRACING_FIELDS.includes(searchKey) ||
  277. // tags that we don't want to pass to pass to issue search
  278. options.excludeTagKeys.has(searchKey)
  279. ) {
  280. currentFilter.removeFilter(tagKey);
  281. }
  282. });
  283. return currentFilter;
  284. }
  285. export function addRoutePerformanceContext(selection: PageFilters) {
  286. const transaction = getCurrentSentryReactRootSpan();
  287. const days = statsPeriodToDays(
  288. selection.datetime.period,
  289. selection.datetime.start,
  290. selection.datetime.end
  291. );
  292. const oneDay = 86400;
  293. const seconds = Math.floor(days * oneDay);
  294. transaction?.setAttribute('query.period', seconds.toString());
  295. let groupedPeriod = '>30d';
  296. if (seconds <= oneDay) {
  297. groupedPeriod = '<=1d';
  298. } else if (seconds <= oneDay * 7) {
  299. groupedPeriod = '<=7d';
  300. } else if (seconds <= oneDay * 14) {
  301. groupedPeriod = '<=14d';
  302. } else if (seconds <= oneDay * 30) {
  303. groupedPeriod = '<=30d';
  304. }
  305. transaction?.setAttribute('query.period.grouped', groupedPeriod);
  306. }
  307. export function getTransactionName(location: Location): string | undefined {
  308. const {transaction} = location.query;
  309. return decodeScalar(transaction);
  310. }
  311. export function getIsMultiProject(projects: readonly number[] | number[]) {
  312. if (!projects.length) {
  313. return true; // My projects
  314. }
  315. if (projects.length === 1 && projects[0] === ALL_ACCESS_PROJECTS) {
  316. return true; // All projects
  317. }
  318. return false;
  319. }
  320. export function getSelectedProjectPlatformsArray(
  321. location: Location,
  322. projects: Project[]
  323. ) {
  324. const projectQuery = location.query.project;
  325. const selectedProjectIdSet = new Set(toArray(projectQuery));
  326. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  327. if (selectedProjectIdSet.has(project.id)) {
  328. acc.push(project.platform ?? 'undefined');
  329. }
  330. return acc;
  331. }, []);
  332. return selectedProjectPlatforms;
  333. }
  334. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  335. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  336. return selectedProjectPlatforms.join(', ');
  337. }
  338. export function getProject(
  339. eventData: EventData,
  340. projects: Project[]
  341. ): Project | undefined {
  342. const projectSlug = eventData.project as string | undefined;
  343. return projects.find(currentProject => currentProject.slug === projectSlug);
  344. }
  345. export function getProjectID(
  346. eventData: EventData,
  347. projects: Project[]
  348. ): string | undefined {
  349. return getProject(eventData, projects)?.id;
  350. }
  351. export function usePerformanceGeneralProjectSettings(projectId?: number) {
  352. const organization = useOrganization();
  353. const {projects} = useProjects();
  354. const stringProjectId = projectId?.toString();
  355. const project = projects.find(p => p.id === stringProjectId);
  356. return useApiQuery<{enable_images: boolean}>(
  357. [`/projects/${organization.slug}/${project?.slug}/performance/configure/`],
  358. {
  359. staleTime: 0,
  360. enabled: Boolean(project),
  361. }
  362. );
  363. }
  364. export function getPerformanceBaseUrl(
  365. orgSlug: string,
  366. view?: DomainView,
  367. bare: boolean = false
  368. ) {
  369. let url = 'performance';
  370. if (view) {
  371. url = `${DOMAIN_VIEW_BASE_URL}/${view}`;
  372. }
  373. return bare ? url : normalizeUrl(`/organizations/${orgSlug}/${url}`);
  374. }