index.tsx 12 KB

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