index.tsx 13 KB

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