utils.tsx 11 KB

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