utils.tsx 11 KB

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