utils.tsx 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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 {
  6. Organization,
  7. OrganizationSummary,
  8. PageFilters,
  9. Project,
  10. ReleaseProject,
  11. } from 'sentry/types';
  12. import {trackAnalyticsEvent} from 'sentry/utils/analytics';
  13. import {statsPeriodToDays} from 'sentry/utils/dates';
  14. import EventView from 'sentry/utils/discover/eventView';
  15. import {TRACING_FIELDS} from 'sentry/utils/discover/fields';
  16. import {getDuration} from 'sentry/utils/formatters';
  17. import getCurrentSentryReactTransaction from 'sentry/utils/getCurrentSentryReactTransaction';
  18. import {decodeScalar} from 'sentry/utils/queryString';
  19. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  20. import {DEFAULT_MAX_DURATION} from './trends/utils';
  21. export const QUERY_KEYS = [
  22. 'environment',
  23. 'project',
  24. 'query',
  25. 'start',
  26. 'end',
  27. 'statsPeriod',
  28. ] as const;
  29. /**
  30. * Performance type can used to determine a default view or which specific field should be used by default on pages
  31. * where we don't want to wait for transaction data to return to determine how to display aspects of a page.
  32. */
  33. export enum PROJECT_PERFORMANCE_TYPE {
  34. ANY = 'any', // Fallback to transaction duration
  35. FRONTEND = 'frontend',
  36. BACKEND = 'backend',
  37. FRONTEND_OTHER = 'frontend_other',
  38. MOBILE = 'mobile',
  39. }
  40. // The native SDK is equally used on clients and end-devices as on
  41. // backend, the default view should be "All Transactions".
  42. const FRONTEND_PLATFORMS: string[] = [...frontend];
  43. const BACKEND_PLATFORMS: string[] = backend.filter(platform => platform !== 'native');
  44. const MOBILE_PLATFORMS: string[] = [...mobile];
  45. export function platformToPerformanceType(
  46. projects: (Project | ReleaseProject)[],
  47. projectIds: readonly number[]
  48. ) {
  49. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  50. return PROJECT_PERFORMANCE_TYPE.ANY;
  51. }
  52. const selectedProjects = projects.filter(p =>
  53. projectIds.includes(parseInt(`${p.id}`, 10))
  54. );
  55. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  56. return PROJECT_PERFORMANCE_TYPE.ANY;
  57. }
  58. if (
  59. selectedProjects.every(project =>
  60. FRONTEND_PLATFORMS.includes(project.platform as string)
  61. )
  62. ) {
  63. return PROJECT_PERFORMANCE_TYPE.FRONTEND;
  64. }
  65. if (
  66. selectedProjects.every(project =>
  67. BACKEND_PLATFORMS.includes(project.platform as string)
  68. )
  69. ) {
  70. return PROJECT_PERFORMANCE_TYPE.BACKEND;
  71. }
  72. if (
  73. selectedProjects.every(project =>
  74. MOBILE_PLATFORMS.includes(project.platform as string)
  75. )
  76. ) {
  77. return PROJECT_PERFORMANCE_TYPE.MOBILE;
  78. }
  79. return PROJECT_PERFORMANCE_TYPE.ANY;
  80. }
  81. /**
  82. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  83. */
  84. export function platformAndConditionsToPerformanceType(
  85. projects: Project[],
  86. eventView: EventView
  87. ) {
  88. const performanceType = platformToPerformanceType(projects, eventView.project);
  89. if (performanceType === PROJECT_PERFORMANCE_TYPE.FRONTEND) {
  90. const conditions = new MutableSearch(eventView.query);
  91. const ops = conditions.getFilterValues('!transaction.op');
  92. if (ops.some(op => op === 'pageload')) {
  93. return PROJECT_PERFORMANCE_TYPE.FRONTEND_OTHER;
  94. }
  95. }
  96. return performanceType;
  97. }
  98. /**
  99. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  100. */
  101. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  102. return (
  103. platformAndConditionsToPerformanceType(projects, eventView) ===
  104. PROJECT_PERFORMANCE_TYPE.FRONTEND
  105. );
  106. }
  107. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  108. return (
  109. platformAndConditionsToPerformanceType(projects, eventView) ===
  110. PROJECT_PERFORMANCE_TYPE.FRONTEND ||
  111. platformAndConditionsToPerformanceType(projects, eventView) ===
  112. PROJECT_PERFORMANCE_TYPE.FRONTEND_OTHER
  113. );
  114. }
  115. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  116. return `/organizations/${organization.slug}/performance/`;
  117. }
  118. export function getPerformanceTrendsUrl(organization: OrganizationSummary): string {
  119. return `/organizations/${organization.slug}/performance/trends/`;
  120. }
  121. export function getTransactionSearchQuery(location: Location, query: string = '') {
  122. return decodeScalar(location.query.query, query).trim();
  123. }
  124. export function handleTrendsClick({
  125. location,
  126. organization,
  127. projectPlatforms,
  128. }: {
  129. location: Location;
  130. organization: Organization;
  131. projectPlatforms: string;
  132. }) {
  133. trackAnalyticsEvent({
  134. eventKey: 'performance_views.change_view',
  135. eventName: 'Performance Views: Change View',
  136. organization_id: parseInt(organization.id, 10),
  137. view_name: 'TRENDS',
  138. project_platforms: projectPlatforms,
  139. });
  140. const target = trendsTargetRoute({location, organization});
  141. browserHistory.push(target);
  142. }
  143. export function trendsTargetRoute({
  144. location,
  145. organization,
  146. initialConditions,
  147. additionalQuery,
  148. }: {
  149. location: Location;
  150. organization: Organization;
  151. additionalQuery?: {[x: string]: string};
  152. initialConditions?: MutableSearch;
  153. }) {
  154. const newQuery = {
  155. ...location.query,
  156. ...additionalQuery,
  157. };
  158. const query = decodeScalar(location.query.query, '');
  159. const conditions = new MutableSearch(query);
  160. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  161. if (conditions.hasFilter('tpm()')) {
  162. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  163. } else {
  164. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  165. }
  166. if (conditions.hasFilter('transaction.duration')) {
  167. modifiedConditions.setFilterValues(
  168. 'transaction.duration',
  169. conditions.getFilterValues('transaction.duration')
  170. );
  171. } else {
  172. modifiedConditions.setFilterValues('transaction.duration', [
  173. '>0',
  174. `<${DEFAULT_MAX_DURATION}`,
  175. ]);
  176. }
  177. newQuery.query = modifiedConditions.formatString();
  178. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  179. }
  180. export function removeTracingKeysFromSearch(
  181. currentFilter: MutableSearch,
  182. options: {excludeTagKeys: Set<string>} = {
  183. excludeTagKeys: new Set([
  184. // event type can be "transaction" but we're searching for issues
  185. 'event.type',
  186. // the project is already determined by the transaction,
  187. // and issue search does not support the project filter
  188. 'project',
  189. ]),
  190. }
  191. ) {
  192. currentFilter.getFilterKeys().forEach(tagKey => {
  193. const searchKey = tagKey.startsWith('!') ? tagKey.substr(1) : tagKey;
  194. // Remove aggregates and transaction event fields
  195. if (
  196. // aggregates
  197. searchKey.match(/\w+\(.*\)/) ||
  198. // transaction event fields
  199. TRACING_FIELDS.includes(searchKey) ||
  200. // tags that we don't want to pass to pass to issue search
  201. options.excludeTagKeys.has(searchKey)
  202. ) {
  203. currentFilter.removeFilter(tagKey);
  204. }
  205. });
  206. return currentFilter;
  207. }
  208. export function addRoutePerformanceContext(selection: PageFilters) {
  209. const transaction = getCurrentSentryReactTransaction();
  210. const days = statsPeriodToDays(
  211. selection.datetime.period,
  212. selection.datetime.start,
  213. selection.datetime.end
  214. );
  215. const oneDay = 86400;
  216. const seconds = Math.floor(days * oneDay);
  217. transaction?.setTag('query.period', seconds.toString());
  218. let groupedPeriod = '>30d';
  219. if (seconds <= oneDay) {
  220. groupedPeriod = '<=1d';
  221. } else if (seconds <= oneDay * 7) {
  222. groupedPeriod = '<=7d';
  223. } else if (seconds <= oneDay * 14) {
  224. groupedPeriod = '<=14d';
  225. } else if (seconds <= oneDay * 30) {
  226. groupedPeriod = '<=30d';
  227. }
  228. transaction?.setTag('query.period.grouped', groupedPeriod);
  229. }
  230. export function getTransactionName(location: Location): string | undefined {
  231. const {transaction} = location.query;
  232. return decodeScalar(transaction);
  233. }
  234. export function getPerformanceDuration(milliseconds: number) {
  235. return getDuration(milliseconds / 1000, milliseconds > 1000 ? 2 : 0, true);
  236. }
  237. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  238. const projectQuery = location.query.project;
  239. const selectedProjectIdSet = Array.isArray(projectQuery)
  240. ? new Set(projectQuery)
  241. : new Set([projectQuery]);
  242. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  243. if (selectedProjectIdSet.has(project.id)) {
  244. acc.push(project.platform ?? 'undefined');
  245. }
  246. return acc;
  247. }, []);
  248. return selectedProjectPlatforms.join(', ');
  249. }