index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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: (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. /**
  135. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  136. */
  137. export function platformAndConditionsToPerformanceType(
  138. projects: Project[],
  139. eventView: EventView
  140. ) {
  141. const performanceType = platformToPerformanceType(projects, eventView.project);
  142. if (performanceType === ProjectPerformanceType.FRONTEND) {
  143. const conditions = new MutableSearch(eventView.query);
  144. const ops = conditions.getFilterValues('!transaction.op');
  145. if (ops.some(op => op === 'pageload')) {
  146. return ProjectPerformanceType.FRONTEND_OTHER;
  147. }
  148. }
  149. return performanceType;
  150. }
  151. /**
  152. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  153. */
  154. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  155. return (
  156. platformAndConditionsToPerformanceType(projects, eventView) ===
  157. ProjectPerformanceType.FRONTEND
  158. );
  159. }
  160. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  161. return (
  162. platformAndConditionsToPerformanceType(projects, eventView) ===
  163. ProjectPerformanceType.FRONTEND ||
  164. platformAndConditionsToPerformanceType(projects, eventView) ===
  165. ProjectPerformanceType.FRONTEND_OTHER
  166. );
  167. }
  168. // TODO - remove in favour of `getPerformanceBaseUrl`
  169. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  170. return `${getPerformanceBaseUrl(organization.slug)}/`;
  171. }
  172. export function getPerformanceTrendsUrl(
  173. organization: OrganizationSummary,
  174. view?: DomainView
  175. ): string {
  176. return `${getPerformanceBaseUrl(organization.slug, view)}/trends/`;
  177. }
  178. export function getTransactionSearchQuery(location: Location, query: string = '') {
  179. return decodeScalar(location.query.query, query).trim();
  180. }
  181. export function handleTrendsClick({
  182. location,
  183. organization,
  184. projectPlatforms,
  185. }: {
  186. location: Location;
  187. organization: Organization;
  188. projectPlatforms: string;
  189. }) {
  190. trackAnalytics('performance_views.change_view', {
  191. organization,
  192. view_name: 'TRENDS',
  193. project_platforms: projectPlatforms,
  194. });
  195. const target = trendsTargetRoute({location, organization});
  196. browserHistory.push(normalizeUrl(target));
  197. }
  198. export function trendsTargetRoute({
  199. location,
  200. organization,
  201. initialConditions,
  202. additionalQuery,
  203. view,
  204. }: {
  205. location: Location;
  206. organization: Organization;
  207. additionalQuery?: {[x: string]: string};
  208. initialConditions?: MutableSearch;
  209. view?: DomainView;
  210. }) {
  211. const newQuery = {
  212. ...location.query,
  213. ...additionalQuery,
  214. };
  215. const query = decodeScalar(location.query.query, '');
  216. const conditions = new MutableSearch(query);
  217. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  218. // Trends on metrics don't need these conditions
  219. if (!organization.features.includes('performance-new-trends')) {
  220. // No need to carry over tpm filters to transaction summary
  221. if (conditions.hasFilter('tpm()')) {
  222. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  223. } else {
  224. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  225. }
  226. if (conditions.hasFilter('transaction.duration')) {
  227. modifiedConditions.setFilterValues(
  228. 'transaction.duration',
  229. conditions.getFilterValues('transaction.duration')
  230. );
  231. } else {
  232. modifiedConditions.setFilterValues('transaction.duration', [
  233. '>0',
  234. `<${DEFAULT_MAX_DURATION}`,
  235. ]);
  236. }
  237. }
  238. newQuery.query = modifiedConditions.formatString();
  239. return {pathname: getPerformanceTrendsUrl(organization, view), query: {...newQuery}};
  240. }
  241. export function removeTracingKeysFromSearch(
  242. currentFilter: MutableSearch,
  243. options: {excludeTagKeys: Set<string>} = {
  244. excludeTagKeys: new Set([
  245. // event type can be "transaction" but we're searching for issues
  246. 'event.type',
  247. // the project is already determined by the transaction,
  248. // and issue search does not support the project filter
  249. 'project',
  250. ]),
  251. }
  252. ) {
  253. currentFilter.getFilterKeys().forEach(tagKey => {
  254. const searchKey = tagKey.startsWith('!') ? tagKey.substring(1) : tagKey;
  255. // Remove aggregates and transaction event fields
  256. if (
  257. // aggregates
  258. searchKey.match(/\w+\(.*\)/) ||
  259. // transaction event fields
  260. TRACING_FIELDS.includes(searchKey) ||
  261. // tags that we don't want to pass to pass to issue search
  262. options.excludeTagKeys.has(searchKey)
  263. ) {
  264. currentFilter.removeFilter(tagKey);
  265. }
  266. });
  267. return currentFilter;
  268. }
  269. export function addRoutePerformanceContext(selection: PageFilters) {
  270. const transaction = getCurrentSentryReactRootSpan();
  271. const days = statsPeriodToDays(
  272. selection.datetime.period,
  273. selection.datetime.start,
  274. selection.datetime.end
  275. );
  276. const oneDay = 86400;
  277. const seconds = Math.floor(days * oneDay);
  278. transaction?.setAttribute('query.period', seconds.toString());
  279. let groupedPeriod = '>30d';
  280. if (seconds <= oneDay) {
  281. groupedPeriod = '<=1d';
  282. } else if (seconds <= oneDay * 7) {
  283. groupedPeriod = '<=7d';
  284. } else if (seconds <= oneDay * 14) {
  285. groupedPeriod = '<=14d';
  286. } else if (seconds <= oneDay * 30) {
  287. groupedPeriod = '<=30d';
  288. }
  289. transaction?.setAttribute('query.period.grouped', groupedPeriod);
  290. }
  291. export function getTransactionName(location: Location): string | undefined {
  292. const {transaction} = location.query;
  293. return decodeScalar(transaction);
  294. }
  295. export function getIsMultiProject(projects: readonly number[] | number[]) {
  296. if (!projects.length) {
  297. return true; // My projects
  298. }
  299. if (projects.length === 1 && projects[0] === ALL_ACCESS_PROJECTS) {
  300. return true; // All projects
  301. }
  302. return false;
  303. }
  304. export function getSelectedProjectPlatformsArray(
  305. location: Location,
  306. projects: Project[]
  307. ) {
  308. const projectQuery = location.query.project;
  309. const selectedProjectIdSet = new Set(toArray(projectQuery));
  310. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  311. if (selectedProjectIdSet.has(project.id)) {
  312. acc.push(project.platform ?? 'undefined');
  313. }
  314. return acc;
  315. }, []);
  316. return selectedProjectPlatforms;
  317. }
  318. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  319. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  320. return selectedProjectPlatforms.join(', ');
  321. }
  322. export function getProject(
  323. eventData: EventData,
  324. projects: Project[]
  325. ): Project | undefined {
  326. const projectSlug = (eventData?.project as string) || undefined;
  327. if (typeof projectSlug === undefined) {
  328. return undefined;
  329. }
  330. return projects.find(currentProject => currentProject.slug === projectSlug);
  331. }
  332. export function getProjectID(
  333. eventData: EventData,
  334. projects: Project[]
  335. ): string | undefined {
  336. return getProject(eventData, projects)?.id;
  337. }
  338. export function usePerformanceGeneralProjectSettings(projectId?: number) {
  339. const organization = useOrganization();
  340. const {projects} = useProjects();
  341. const stringProjectId = projectId?.toString();
  342. const project = projects.find(p => p.id === stringProjectId);
  343. return useApiQuery<{enable_images: boolean}>(
  344. [`/projects/${organization.slug}/${project?.slug}/performance/configure/`],
  345. {
  346. staleTime: 0,
  347. enabled: Boolean(project),
  348. }
  349. );
  350. }
  351. export function getPerformanceBaseUrl(
  352. orgSlug: string,
  353. view?: DomainView,
  354. bare: boolean = false
  355. ) {
  356. let url = 'performance';
  357. if (view) {
  358. url = `${DOMAIN_VIEW_BASE_URL}/${view}`;
  359. }
  360. return bare ? url : normalizeUrl(`/organizations/${orgSlug}/${url}`);
  361. }