index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 {DEFAULT_MAX_DURATION} from '../trends/utils';
  30. export const QUERY_KEYS = [
  31. 'environment',
  32. 'project',
  33. 'query',
  34. 'start',
  35. 'end',
  36. 'statsPeriod',
  37. ] as const;
  38. export const UNPARAMETERIZED_TRANSACTION = '<< unparameterized >>'; // Represents 'other' transactions with high cardinality names that were dropped on the metrics dataset.
  39. const UNPARAMETRIZED_TRANSACTION = '<< unparametrized >>'; // Old spelling. Can be deleted in the future when all data for this transaction name is gone.
  40. export const EXCLUDE_METRICS_UNPARAM_CONDITIONS = `(!transaction:"${UNPARAMETERIZED_TRANSACTION}" AND !transaction:"${UNPARAMETRIZED_TRANSACTION}")`;
  41. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  42. export enum DiscoverQueryPageSource {
  43. PERFORMANCE = 'performance',
  44. DISCOVER = 'discover',
  45. }
  46. export function createUnnamedTransactionsDiscoverTarget(props: {
  47. location: Location;
  48. organization: Organization;
  49. source?: DiscoverQueryPageSource;
  50. }) {
  51. const fields =
  52. props.source === DiscoverQueryPageSource.DISCOVER
  53. ? ['transaction', 'project', 'transaction.source', 'epm()']
  54. : ['transaction', 'project', 'transaction.source', 'epm()', 'p50()', 'p95()'];
  55. const query: NewQuery = {
  56. id: undefined,
  57. name:
  58. props.source === DiscoverQueryPageSource.DISCOVER
  59. ? t('Unparameterized Transactions')
  60. : t('Performance - Unparameterized Transactions'),
  61. query: 'event.type:transaction transaction.source:"url"',
  62. projects: [],
  63. fields,
  64. version: 2,
  65. };
  66. const discoverEventView = EventView.fromNewQueryWithLocation(
  67. query,
  68. props.location
  69. ).withSorts([{field: 'epm', kind: 'desc'}]);
  70. const target = discoverEventView.getResultsViewUrlTarget(
  71. props.organization.slug,
  72. false,
  73. hasDatasetSelector(props.organization) ? SavedQueryDatasets.TRANSACTIONS : undefined
  74. );
  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 have both, frontend and backend transactions.
  94. !['javascript-nextjs', 'javascript-remix', 'javascript-sveltekit'].includes(platform)
  95. );
  96. const BACKEND_PLATFORMS: string[] = backend.filter(
  97. platform => platform !== 'native' && platform !== 'nintendo-switch'
  98. );
  99. const MOBILE_PLATFORMS: string[] = [...mobile];
  100. export function platformToPerformanceType(
  101. projects: (Project | ReleaseProject)[],
  102. projectIds: readonly number[]
  103. ) {
  104. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  105. return ProjectPerformanceType.ANY;
  106. }
  107. const selectedProjects = projects.filter(p =>
  108. projectIds.includes(parseInt(`${p.id}`, 10))
  109. );
  110. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  111. return ProjectPerformanceType.ANY;
  112. }
  113. const projectPerformanceTypes = new Set<ProjectPerformanceType>();
  114. selectedProjects.forEach(project => {
  115. if (FRONTEND_PLATFORMS.includes(project.platform ?? '')) {
  116. projectPerformanceTypes.add(ProjectPerformanceType.FRONTEND);
  117. }
  118. if (BACKEND_PLATFORMS.includes(project.platform ?? '')) {
  119. projectPerformanceTypes.add(ProjectPerformanceType.BACKEND);
  120. }
  121. if (MOBILE_PLATFORMS.includes(project.platform ?? '')) {
  122. projectPerformanceTypes.add(ProjectPerformanceType.MOBILE);
  123. }
  124. });
  125. const uniquePerformanceTypeCount = projectPerformanceTypes.size;
  126. if (!uniquePerformanceTypeCount || uniquePerformanceTypeCount > 1) {
  127. return ProjectPerformanceType.ANY;
  128. }
  129. const [PlatformKey] = projectPerformanceTypes;
  130. return PlatformKey;
  131. }
  132. /**
  133. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  134. */
  135. export function platformAndConditionsToPerformanceType(
  136. projects: Project[],
  137. eventView: EventView
  138. ) {
  139. const performanceType = platformToPerformanceType(projects, eventView.project);
  140. if (performanceType === ProjectPerformanceType.FRONTEND) {
  141. const conditions = new MutableSearch(eventView.query);
  142. const ops = conditions.getFilterValues('!transaction.op');
  143. if (ops.some(op => op === 'pageload')) {
  144. return ProjectPerformanceType.FRONTEND_OTHER;
  145. }
  146. }
  147. return performanceType;
  148. }
  149. /**
  150. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  151. */
  152. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  153. return (
  154. platformAndConditionsToPerformanceType(projects, eventView) ===
  155. ProjectPerformanceType.FRONTEND
  156. );
  157. }
  158. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  159. return (
  160. platformAndConditionsToPerformanceType(projects, eventView) ===
  161. ProjectPerformanceType.FRONTEND ||
  162. platformAndConditionsToPerformanceType(projects, eventView) ===
  163. ProjectPerformanceType.FRONTEND_OTHER
  164. );
  165. }
  166. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  167. return `/organizations/${organization.slug}/performance/`;
  168. }
  169. export function getPerformanceTrendsUrl(organization: OrganizationSummary): string {
  170. return `/organizations/${organization.slug}/performance/trends/`;
  171. }
  172. export function getTransactionSearchQuery(location: Location, query: string = '') {
  173. return decodeScalar(location.query.query, query).trim();
  174. }
  175. export function handleTrendsClick({
  176. location,
  177. organization,
  178. projectPlatforms,
  179. }: {
  180. location: Location;
  181. organization: Organization;
  182. projectPlatforms: string;
  183. }) {
  184. trackAnalytics('performance_views.change_view', {
  185. organization,
  186. view_name: 'TRENDS',
  187. project_platforms: projectPlatforms,
  188. });
  189. const target = trendsTargetRoute({location, organization});
  190. browserHistory.push(normalizeUrl(target));
  191. }
  192. export function trendsTargetRoute({
  193. location,
  194. organization,
  195. initialConditions,
  196. additionalQuery,
  197. }: {
  198. location: Location;
  199. organization: Organization;
  200. additionalQuery?: {[x: string]: string};
  201. initialConditions?: MutableSearch;
  202. }) {
  203. const newQuery = {
  204. ...location.query,
  205. ...additionalQuery,
  206. };
  207. const query = decodeScalar(location.query.query, '');
  208. const conditions = new MutableSearch(query);
  209. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  210. // Trends on metrics don't need these conditions
  211. if (!organization.features.includes('performance-new-trends')) {
  212. // No need to carry over tpm filters to transaction summary
  213. if (conditions.hasFilter('tpm()')) {
  214. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  215. } else {
  216. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  217. }
  218. if (conditions.hasFilter('transaction.duration')) {
  219. modifiedConditions.setFilterValues(
  220. 'transaction.duration',
  221. conditions.getFilterValues('transaction.duration')
  222. );
  223. } else {
  224. modifiedConditions.setFilterValues('transaction.duration', [
  225. '>0',
  226. `<${DEFAULT_MAX_DURATION}`,
  227. ]);
  228. }
  229. }
  230. newQuery.query = modifiedConditions.formatString();
  231. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  232. }
  233. export function removeTracingKeysFromSearch(
  234. currentFilter: MutableSearch,
  235. options: {excludeTagKeys: Set<string>} = {
  236. excludeTagKeys: new Set([
  237. // event type can be "transaction" but we're searching for issues
  238. 'event.type',
  239. // the project is already determined by the transaction,
  240. // and issue search does not support the project filter
  241. 'project',
  242. ]),
  243. }
  244. ) {
  245. currentFilter.getFilterKeys().forEach(tagKey => {
  246. const searchKey = tagKey.startsWith('!') ? tagKey.substring(1) : tagKey;
  247. // Remove aggregates and transaction event fields
  248. if (
  249. // aggregates
  250. searchKey.match(/\w+\(.*\)/) ||
  251. // transaction event fields
  252. TRACING_FIELDS.includes(searchKey) ||
  253. // tags that we don't want to pass to pass to issue search
  254. options.excludeTagKeys.has(searchKey)
  255. ) {
  256. currentFilter.removeFilter(tagKey);
  257. }
  258. });
  259. return currentFilter;
  260. }
  261. export function addRoutePerformanceContext(selection: PageFilters) {
  262. const transaction = getCurrentSentryReactRootSpan();
  263. const days = statsPeriodToDays(
  264. selection.datetime.period,
  265. selection.datetime.start,
  266. selection.datetime.end
  267. );
  268. const oneDay = 86400;
  269. const seconds = Math.floor(days * oneDay);
  270. transaction?.setAttribute('query.period', seconds.toString());
  271. let groupedPeriod = '>30d';
  272. if (seconds <= oneDay) {
  273. groupedPeriod = '<=1d';
  274. } else if (seconds <= oneDay * 7) {
  275. groupedPeriod = '<=7d';
  276. } else if (seconds <= oneDay * 14) {
  277. groupedPeriod = '<=14d';
  278. } else if (seconds <= oneDay * 30) {
  279. groupedPeriod = '<=30d';
  280. }
  281. transaction?.setAttribute('query.period.grouped', groupedPeriod);
  282. }
  283. export function getTransactionName(location: Location): string | undefined {
  284. const {transaction} = location.query;
  285. return decodeScalar(transaction);
  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 usePerformanceGeneralProjectSettings(projectId?: number) {
  331. const organization = useOrganization();
  332. const {projects} = useProjects();
  333. const stringProjectId = projectId?.toString();
  334. const project = projects.find(p => p.id === stringProjectId);
  335. return useApiQuery<{enable_images: boolean}>(
  336. [`/projects/${organization.slug}/${project?.slug}/performance/configure/`],
  337. {
  338. staleTime: 0,
  339. enabled: Boolean(project),
  340. }
  341. );
  342. }