utils.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 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. trackAnalyticsEvent({
  173. eventKey: 'performance_views.change_view',
  174. eventName: 'Performance Views: Change View',
  175. organization_id: parseInt(organization.id, 10),
  176. view_name: 'TRENDS',
  177. project_platforms: projectPlatforms,
  178. });
  179. const target = trendsTargetRoute({location, organization});
  180. browserHistory.push(target);
  181. }
  182. export function trendsTargetRoute({
  183. location,
  184. organization,
  185. initialConditions,
  186. additionalQuery,
  187. }: {
  188. location: Location;
  189. organization: Organization;
  190. additionalQuery?: {[x: string]: string};
  191. initialConditions?: MutableSearch;
  192. }) {
  193. const newQuery = {
  194. ...location.query,
  195. ...additionalQuery,
  196. };
  197. const query = decodeScalar(location.query.query, '');
  198. const conditions = new MutableSearch(query);
  199. const modifiedConditions = initialConditions ?? new MutableSearch([]);
  200. if (conditions.hasFilter('tpm()')) {
  201. modifiedConditions.setFilterValues('tpm()', conditions.getFilterValues('tpm()'));
  202. } else {
  203. modifiedConditions.setFilterValues('tpm()', ['>0.01']);
  204. }
  205. if (conditions.hasFilter('transaction.duration')) {
  206. modifiedConditions.setFilterValues(
  207. 'transaction.duration',
  208. conditions.getFilterValues('transaction.duration')
  209. );
  210. } else {
  211. modifiedConditions.setFilterValues('transaction.duration', [
  212. '>0',
  213. `<${DEFAULT_MAX_DURATION}`,
  214. ]);
  215. }
  216. newQuery.query = modifiedConditions.formatString();
  217. return {pathname: getPerformanceTrendsUrl(organization), query: {...newQuery}};
  218. }
  219. export function removeTracingKeysFromSearch(
  220. currentFilter: MutableSearch,
  221. options: {excludeTagKeys: Set<string>} = {
  222. excludeTagKeys: new Set([
  223. // event type can be "transaction" but we're searching for issues
  224. 'event.type',
  225. // the project is already determined by the transaction,
  226. // and issue search does not support the project filter
  227. 'project',
  228. ]),
  229. }
  230. ) {
  231. currentFilter.getFilterKeys().forEach(tagKey => {
  232. const searchKey = tagKey.startsWith('!') ? tagKey.substr(1) : tagKey;
  233. // Remove aggregates and transaction event fields
  234. if (
  235. // aggregates
  236. searchKey.match(/\w+\(.*\)/) ||
  237. // transaction event fields
  238. TRACING_FIELDS.includes(searchKey) ||
  239. // tags that we don't want to pass to pass to issue search
  240. options.excludeTagKeys.has(searchKey)
  241. ) {
  242. currentFilter.removeFilter(tagKey);
  243. }
  244. });
  245. return currentFilter;
  246. }
  247. export function addRoutePerformanceContext(selection: PageFilters) {
  248. const transaction = getCurrentSentryReactTransaction();
  249. const days = statsPeriodToDays(
  250. selection.datetime.period,
  251. selection.datetime.start,
  252. selection.datetime.end
  253. );
  254. const oneDay = 86400;
  255. const seconds = Math.floor(days * oneDay);
  256. transaction?.setTag('query.period', seconds.toString());
  257. let groupedPeriod = '>30d';
  258. if (seconds <= oneDay) {
  259. groupedPeriod = '<=1d';
  260. } else if (seconds <= oneDay * 7) {
  261. groupedPeriod = '<=7d';
  262. } else if (seconds <= oneDay * 14) {
  263. groupedPeriod = '<=14d';
  264. } else if (seconds <= oneDay * 30) {
  265. groupedPeriod = '<=30d';
  266. }
  267. transaction?.setTag('query.period.grouped', groupedPeriod);
  268. }
  269. export function getTransactionName(location: Location): string | undefined {
  270. const {transaction} = location.query;
  271. return decodeScalar(transaction);
  272. }
  273. export function getPerformanceDuration(milliseconds: number) {
  274. return getDuration(milliseconds / 1000, milliseconds > 1000 ? 2 : 0, true);
  275. }
  276. export function areMultipleProjectsSelected(eventView: EventView) {
  277. if (!eventView.project.length) {
  278. return true; // My projects
  279. }
  280. if (eventView.project.length === 1 && eventView.project[0] === ALL_ACCESS_PROJECTS) {
  281. return true; // All projects
  282. }
  283. return false;
  284. }
  285. export function getSelectedProjectPlatformsArray(
  286. location: Location,
  287. projects: Project[]
  288. ) {
  289. const projectQuery = location.query.project;
  290. const selectedProjectIdSet = new Set(toArray(projectQuery));
  291. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  292. if (selectedProjectIdSet.has(project.id)) {
  293. acc.push(project.platform ?? 'undefined');
  294. }
  295. return acc;
  296. }, []);
  297. return selectedProjectPlatforms;
  298. }
  299. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  300. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  301. return selectedProjectPlatforms.join(', ');
  302. }