utils.tsx 11 KB

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