utils.tsx 11 KB

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