utils.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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 enum DiscoverQueryPageSource {
  36. PERFORMANCE = 'performance',
  37. DISCOVER = 'discover',
  38. }
  39. export function createUnnamedTransactionsDiscoverTarget(props: {
  40. location: Location;
  41. organization: Organization;
  42. source?: DiscoverQueryPageSource;
  43. }) {
  44. const fields =
  45. props.source === DiscoverQueryPageSource.DISCOVER
  46. ? ['transaction', 'project', 'transaction.source', 'epm()']
  47. : ['transaction', 'project', 'transaction.source', 'epm()', 'p50()', 'p95()'];
  48. const query: NewQuery = {
  49. id: undefined,
  50. name:
  51. props.source === DiscoverQueryPageSource.DISCOVER
  52. ? t('Unparameterized Transactions')
  53. : t('Performance - Unparameterized Transactions'),
  54. query: 'event.type:transaction transaction.source:"url"',
  55. projects: [],
  56. fields,
  57. version: 2,
  58. };
  59. const discoverEventView = EventView.fromNewQueryWithLocation(
  60. query,
  61. props.location
  62. ).withSorts([{field: 'epm', kind: 'desc'}]);
  63. const target = discoverEventView.getResultsViewUrlTarget(props.organization.slug);
  64. target.query[SHOW_UNPARAM_BANNER] = 'true';
  65. return target;
  66. }
  67. /**
  68. * Performance type can used to determine a default view or which specific field should be used by default on pages
  69. * where we don't want to wait for transaction data to return to determine how to display aspects of a page.
  70. */
  71. export enum PROJECT_PERFORMANCE_TYPE {
  72. ANY = 'any', // Fallback to transaction duration
  73. FRONTEND = 'frontend',
  74. BACKEND = 'backend',
  75. FRONTEND_OTHER = 'frontend_other',
  76. MOBILE = 'mobile',
  77. }
  78. // The native SDK is equally used on clients and end-devices as on
  79. // backend, the default view should be "All Transactions".
  80. const FRONTEND_PLATFORMS: string[] = [...frontend];
  81. const BACKEND_PLATFORMS: string[] = backend.filter(platform => platform !== 'native');
  82. const MOBILE_PLATFORMS: string[] = [...mobile];
  83. export function platformToPerformanceType(
  84. projects: (Project | ReleaseProject)[],
  85. projectIds: readonly number[]
  86. ) {
  87. if (projectIds.length === 0 || projectIds[0] === ALL_ACCESS_PROJECTS) {
  88. return PROJECT_PERFORMANCE_TYPE.ANY;
  89. }
  90. const selectedProjects = projects.filter(p =>
  91. projectIds.includes(parseInt(`${p.id}`, 10))
  92. );
  93. if (selectedProjects.length === 0 || selectedProjects.some(p => !p.platform)) {
  94. return PROJECT_PERFORMANCE_TYPE.ANY;
  95. }
  96. if (
  97. selectedProjects.every(project =>
  98. FRONTEND_PLATFORMS.includes(project.platform as string)
  99. )
  100. ) {
  101. return PROJECT_PERFORMANCE_TYPE.FRONTEND;
  102. }
  103. if (
  104. selectedProjects.every(project =>
  105. BACKEND_PLATFORMS.includes(project.platform as string)
  106. )
  107. ) {
  108. return PROJECT_PERFORMANCE_TYPE.BACKEND;
  109. }
  110. if (
  111. selectedProjects.every(project =>
  112. MOBILE_PLATFORMS.includes(project.platform as string)
  113. )
  114. ) {
  115. return PROJECT_PERFORMANCE_TYPE.MOBILE;
  116. }
  117. return PROJECT_PERFORMANCE_TYPE.ANY;
  118. }
  119. /**
  120. * Used for transaction summary to determine appropriate columns on a page, since there is no display field set for the page.
  121. */
  122. export function platformAndConditionsToPerformanceType(
  123. projects: Project[],
  124. eventView: EventView
  125. ) {
  126. const performanceType = platformToPerformanceType(projects, eventView.project);
  127. if (performanceType === PROJECT_PERFORMANCE_TYPE.FRONTEND) {
  128. const conditions = new MutableSearch(eventView.query);
  129. const ops = conditions.getFilterValues('!transaction.op');
  130. if (ops.some(op => op === 'pageload')) {
  131. return PROJECT_PERFORMANCE_TYPE.FRONTEND_OTHER;
  132. }
  133. }
  134. return performanceType;
  135. }
  136. /**
  137. * Used for transaction summary to check the view itself, since it can have conditions which would exclude it from having vitals aside from platform.
  138. */
  139. export function isSummaryViewFrontendPageLoad(eventView: EventView, projects: Project[]) {
  140. return (
  141. platformAndConditionsToPerformanceType(projects, eventView) ===
  142. PROJECT_PERFORMANCE_TYPE.FRONTEND
  143. );
  144. }
  145. export function isSummaryViewFrontend(eventView: EventView, projects: Project[]) {
  146. return (
  147. platformAndConditionsToPerformanceType(projects, eventView) ===
  148. PROJECT_PERFORMANCE_TYPE.FRONTEND ||
  149. platformAndConditionsToPerformanceType(projects, eventView) ===
  150. PROJECT_PERFORMANCE_TYPE.FRONTEND_OTHER
  151. );
  152. }
  153. export function getPerformanceLandingUrl(organization: OrganizationSummary): string {
  154. return `/organizations/${organization.slug}/performance/`;
  155. }
  156. export function getPerformanceTrendsUrl(organization: OrganizationSummary): string {
  157. return `/organizations/${organization.slug}/performance/trends/`;
  158. }
  159. export function getTransactionSearchQuery(location: Location, query: string = '') {
  160. return decodeScalar(location.query.query, query).trim();
  161. }
  162. export function handleTrendsClick({
  163. location,
  164. organization,
  165. projectPlatforms,
  166. }: {
  167. location: Location;
  168. organization: Organization;
  169. projectPlatforms: string;
  170. }) {
  171. trackAnalyticsEvent({
  172. eventKey: 'performance_views.change_view',
  173. eventName: 'Performance Views: Change View',
  174. organization_id: parseInt(organization.id, 10),
  175. view_name: 'TRENDS',
  176. project_platforms: projectPlatforms,
  177. });
  178. const target = trendsTargetRoute({location, organization});
  179. browserHistory.push(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 = Array.isArray(projectQuery)
  290. ? new Set(projectQuery)
  291. : new Set([projectQuery]);
  292. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  293. if (selectedProjectIdSet.has(project.id)) {
  294. acc.push(project.platform ?? 'undefined');
  295. }
  296. return acc;
  297. }, []);
  298. return selectedProjectPlatforms;
  299. }
  300. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  301. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  302. return selectedProjectPlatforms.join(', ');
  303. }