index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  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(platform => platform !== 'native');
  92. const MOBILE_PLATFORMS: string[] = [...mobile];
  93. export function platformToPerformanceType(
  94. projects: (Project | ReleaseProject)[],
  95. projectIds: readonly number[]
  96. ) {
  97. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  98. return ProjectPerformanceType.ANY;
  99. }
  100. const selectedProjects = projects.filter(p =>
  101. projectIds.includes(parseInt(`${p.id}`, 10))
  102. );
  103. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  104. return ProjectPerformanceType.ANY;
  105. }
  106. const projectPerformanceTypes = new Set<ProjectPerformanceType>();
  107. selectedProjects.forEach(project => {
  108. if (FRONTEND_PLATFORMS.includes(project.platform ?? '')) {
  109. projectPerformanceTypes.add(ProjectPerformanceType.FRONTEND);
  110. }
  111. if (BACKEND_PLATFORMS.includes(project.platform ?? '')) {
  112. projectPerformanceTypes.add(ProjectPerformanceType.BACKEND);
  113. }
  114. if (MOBILE_PLATFORMS.includes(project.platform ?? '')) {
  115. projectPerformanceTypes.add(ProjectPerformanceType.MOBILE);
  116. }
  117. });
  118. const uniquePerformanceTypeCount = projectPerformanceTypes.size;
  119. if (!uniquePerformanceTypeCount || uniquePerformanceTypeCount > 1) {
  120. return ProjectPerformanceType.ANY;
  121. }
  122. const [PlatformKey] = projectPerformanceTypes;
  123. return PlatformKey;
  124. }
  125. /**
  126. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  127. */
  128. export function platformAndConditionsToPerformanceType(
  129. projects: Project[],
  130. eventView: EventView
  131. ) {
  132. const performanceType = platformToPerformanceType(projects, eventView.project);
  133. if (performanceType === ProjectPerformanceType.FRONTEND) {
  134. const conditions = new MutableSearch(eventView.query);
  135. const ops = conditions.getFilterValues('!transaction.op');
  136. if (ops.some(op => op === 'pageload')) {
  137. return ProjectPerformanceType.FRONTEND_OTHER;
  138. }
  139. }
  140. return performanceType;
  141. }
  142. /**
  143. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  144. */
  145. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  146. return (
  147. platformAndConditionsToPerformanceType(projects, eventView) ===
  148. ProjectPerformanceType.FRONTEND
  149. );
  150. }
  151. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  152. return (
  153. platformAndConditionsToPerformanceType(projects, eventView) ===
  154. ProjectPerformanceType.FRONTEND ||
  155. platformAndConditionsToPerformanceType(projects, eventView) ===
  156. ProjectPerformanceType.FRONTEND_OTHER
  157. );
  158. }
  159. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  160. return `/organizations/${organization.slug}/performance/`;
  161. }
  162. export function getPerformanceTrendsUrl(organization: OrganizationSummary): string {
  163. return `/organizations/${organization.slug}/performance/trends/`;
  164. }
  165. export function getTransactionSearchQuery(location: Location, query: string = '') {
  166. return decodeScalar(location.query.query, query).trim();
  167. }
  168. export function handleTrendsClick({
  169. location,
  170. organization,
  171. projectPlatforms,
  172. }: {
  173. location: Location;
  174. organization: Organization;
  175. projectPlatforms: string;
  176. }) {
  177. trackAnalytics('performance_views.change_view', {
  178. organization,
  179. view_name: 'TRENDS',
  180. project_platforms: projectPlatforms,
  181. });
  182. const target = trendsTargetRoute({location, organization});
  183. browserHistory.push(normalizeUrl(target));
  184. }
  185. export function trendsTargetRoute({
  186. location,
  187. organization,
  188. initialConditions,
  189. additionalQuery,
  190. }: {
  191. location: Location;
  192. organization: Organization;
  193. additionalQuery?: {[x: string]: string};
  194. initialConditions?: MutableSearch;
  195. }) {
  196. const newQuery = {
  197. ...location.query,
  198. ...additionalQuery,
  199. };
  200. const query = decodeScalar(location.query.query, '');
  201. const conditions = new MutableSearch(query);
  202. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  203. // Trends on metrics don't need these conditions
  204. if (!organization.features.includes('performance-new-trends')) {
  205. // No need to carry over tpm filters to transaction summary
  206. if (conditions.hasFilter('tpm()')) {
  207. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  208. } else {
  209. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  210. }
  211. if (conditions.hasFilter('transaction.duration')) {
  212. modifiedConditions.setFilterValues(
  213. 'transaction.duration',
  214. conditions.getFilterValues('transaction.duration')
  215. );
  216. } else {
  217. modifiedConditions.setFilterValues('transaction.duration', [
  218. '>0',
  219. `<${DEFAULT_MAX_DURATION}`,
  220. ]);
  221. }
  222. }
  223. newQuery.query = modifiedConditions.formatString();
  224. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  225. }
  226. export function removeTracingKeysFromSearch(
  227. currentFilter: MutableSearch,
  228. options: {excludeTagKeys: Set<string>} = {
  229. excludeTagKeys: new Set([
  230. // event type can be "transaction" but we're searching for issues
  231. 'event.type',
  232. // the project is already determined by the transaction,
  233. // and issue search does not support the project filter
  234. 'project',
  235. ]),
  236. }
  237. ) {
  238. currentFilter.getFilterKeys().forEach(tagKey => {
  239. const searchKey = tagKey.startsWith('!') ? tagKey.substring(1) : tagKey;
  240. // Remove aggregates and transaction event fields
  241. if (
  242. // aggregates
  243. searchKey.match(/\w+\(.*\)/) ||
  244. // transaction event fields
  245. TRACING_FIELDS.includes(searchKey) ||
  246. // tags that we don't want to pass to pass to issue search
  247. options.excludeTagKeys.has(searchKey)
  248. ) {
  249. currentFilter.removeFilter(tagKey);
  250. }
  251. });
  252. return currentFilter;
  253. }
  254. export function addRoutePerformanceContext(selection: PageFilters) {
  255. const transaction = getCurrentSentryReactTransaction();
  256. const days = statsPeriodToDays(
  257. selection.datetime.period,
  258. selection.datetime.start,
  259. selection.datetime.end
  260. );
  261. const oneDay = 86400;
  262. const seconds = Math.floor(days * oneDay);
  263. transaction?.setTag('query.period', seconds.toString());
  264. let groupedPeriod = '>30d';
  265. if (seconds <= oneDay) {
  266. groupedPeriod = '<=1d';
  267. } else if (seconds <= oneDay * 7) {
  268. groupedPeriod = '<=7d';
  269. } else if (seconds <= oneDay * 14) {
  270. groupedPeriod = '<=14d';
  271. } else if (seconds <= oneDay * 30) {
  272. groupedPeriod = '<=30d';
  273. }
  274. transaction?.setTag('query.period.grouped', groupedPeriod);
  275. }
  276. export function getTransactionName(location: Location): string | undefined {
  277. const {transaction} = location.query;
  278. return decodeScalar(transaction);
  279. }
  280. export function getIsMultiProject(projects: readonly number[] | number[]) {
  281. if (!projects.length) {
  282. return true; // My projects
  283. }
  284. if (projects.length === 1 && projects[0] === ALL_ACCESS_PROJECTS) {
  285. return true; // All projects
  286. }
  287. return false;
  288. }
  289. export function getSelectedProjectPlatformsArray(
  290. location: Location,
  291. projects: Project[]
  292. ) {
  293. const projectQuery = location.query.project;
  294. const selectedProjectIdSet = new Set(toArray(projectQuery));
  295. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  296. if (selectedProjectIdSet.has(project.id)) {
  297. acc.push(project.platform ?? 'undefined');
  298. }
  299. return acc;
  300. }, []);
  301. return selectedProjectPlatforms;
  302. }
  303. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  304. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  305. return selectedProjectPlatforms.join(', ');
  306. }
  307. export function getProject(
  308. eventData: EventData,
  309. projects: Project[]
  310. ): Project | undefined {
  311. const projectSlug = (eventData?.project as string) || undefined;
  312. if (typeof projectSlug === undefined) {
  313. return undefined;
  314. }
  315. return projects.find(currentProject => currentProject.slug === projectSlug);
  316. }
  317. export function getProjectID(
  318. eventData: EventData,
  319. projects: Project[]
  320. ): string | undefined {
  321. return getProject(eventData, projects)?.id;
  322. }
  323. export function usePerformanceGeneralProjectSettings(projectId?: number) {
  324. const api = useApi();
  325. const organization = useOrganization();
  326. const {projects} = useProjects();
  327. const stringProjectId = projectId?.toString();
  328. const project = projects.find(p => p.id === stringProjectId);
  329. return useQuery(['settings', 'general', projectId], {
  330. enabled: Boolean(project),
  331. queryFn: () =>
  332. api.requestPromise(
  333. `/api/0/projects/${organization.slug}/${project?.slug}/performance/configure/`
  334. ) as Promise<{enable_images: boolean}>,
  335. });
  336. }