utils.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 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];
  83. const BACKEND_PLATFORMS: string[] = backend.filter(platform => platform !== 'native');
  84. const MOBILE_PLATFORMS: string[] = [...mobile];
  85. export function platformToPerformanceType(
  86. projects: (Project | ReleaseProject)[],
  87. projectIds: readonly number[]
  88. ) {
  89. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  90. return PROJECT_PERFORMANCE_TYPE.ANY;
  91. }
  92. const selectedProjects = projects.filter(p =>
  93. projectIds.includes(parseInt(`${p.id}`, 10))
  94. );
  95. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  96. return PROJECT_PERFORMANCE_TYPE.ANY;
  97. }
  98. if (
  99. selectedProjects.every(project =>
  100. FRONTEND_PLATFORMS.includes(project.platform as string)
  101. )
  102. ) {
  103. return PROJECT_PERFORMANCE_TYPE.FRONTEND;
  104. }
  105. if (
  106. selectedProjects.every(project =>
  107. BACKEND_PLATFORMS.includes(project.platform as string)
  108. )
  109. ) {
  110. return PROJECT_PERFORMANCE_TYPE.BACKEND;
  111. }
  112. if (
  113. selectedProjects.every(project =>
  114. MOBILE_PLATFORMS.includes(project.platform as string)
  115. )
  116. ) {
  117. return PROJECT_PERFORMANCE_TYPE.MOBILE;
  118. }
  119. return PROJECT_PERFORMANCE_TYPE.ANY;
  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. trackAdvancedAnalyticsEvent('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. if (conditions.hasFilter('transaction.duration')) {
  205. modifiedConditions.setFilterValues(
  206. 'transaction.duration',
  207. conditions.getFilterValues('transaction.duration')
  208. );
  209. } else {
  210. modifiedConditions.setFilterValues('transaction.duration', [
  211. '>0',
  212. `<${DEFAULT_MAX_DURATION}`,
  213. ]);
  214. }
  215. newQuery.query = modifiedConditions.formatString();
  216. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  217. }
  218. export function removeTracingKeysFromSearch(
  219. currentFilter: MutableSearch,
  220. options: {excludeTagKeys: Set<string>} = {
  221. excludeTagKeys: new Set([
  222. // event type can be "transaction" but we're searching for issues
  223. 'event.type',
  224. // the project is already determined by the transaction,
  225. // and issue search does not support the project filter
  226. 'project',
  227. ]),
  228. }
  229. ) {
  230. currentFilter.getFilterKeys().forEach(tagKey => {
  231. const searchKey = tagKey.startsWith('!') ? tagKey.substr(1) : tagKey;
  232. // Remove aggregates and transaction event fields
  233. if (
  234. // aggregates
  235. searchKey.match(/\w+\(.*\)/) ||
  236. // transaction event fields
  237. TRACING_FIELDS.includes(searchKey) ||
  238. // tags that we don't want to pass to pass to issue search
  239. options.excludeTagKeys.has(searchKey)
  240. ) {
  241. currentFilter.removeFilter(tagKey);
  242. }
  243. });
  244. return currentFilter;
  245. }
  246. export function addRoutePerformanceContext(selection: PageFilters) {
  247. const transaction = getCurrentSentryReactTransaction();
  248. const days = statsPeriodToDays(
  249. selection.datetime.period,
  250. selection.datetime.start,
  251. selection.datetime.end
  252. );
  253. const oneDay = 86400;
  254. const seconds = Math.floor(days * oneDay);
  255. transaction?.setTag('query.period', seconds.toString());
  256. let groupedPeriod = '>30d';
  257. if (seconds <= oneDay) {
  258. groupedPeriod = '<=1d';
  259. } else if (seconds <= oneDay * 7) {
  260. groupedPeriod = '<=7d';
  261. } else if (seconds <= oneDay * 14) {
  262. groupedPeriod = '<=14d';
  263. } else if (seconds <= oneDay * 30) {
  264. groupedPeriod = '<=30d';
  265. }
  266. transaction?.setTag('query.period.grouped', groupedPeriod);
  267. }
  268. export function getTransactionName(location: Location): string | undefined {
  269. const {transaction} = location.query;
  270. return decodeScalar(transaction);
  271. }
  272. export function getPerformanceDuration(milliseconds: number) {
  273. return getDuration(milliseconds / 1000, milliseconds > 1000 ? 2 : 0, true);
  274. }
  275. export function areMultipleProjectsSelected(eventView: EventView) {
  276. if (!eventView.project.length) {
  277. return true; // My projects
  278. }
  279. if (eventView.project.length === 1 && eventView.project[0] === ALL_ACCESS_PROJECTS) {
  280. return true; // All projects
  281. }
  282. return false;
  283. }
  284. export function getSelectedProjectPlatformsArray(
  285. location: Location,
  286. projects: Project[]
  287. ) {
  288. const projectQuery = location.query.project;
  289. const selectedProjectIdSet = new Set(toArray(projectQuery));
  290. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  291. if (selectedProjectIdSet.has(project.id)) {
  292. acc.push(project.platform ?? 'undefined');
  293. }
  294. return acc;
  295. }, []);
  296. return selectedProjectPlatforms;
  297. }
  298. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  299. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  300. return selectedProjectPlatforms.join(', ');
  301. }