utils.tsx 10 KB

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