utils.tsx 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. import {Location} from 'history';
  2. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  3. import {backend, frontend, mobile} from 'sentry/data/platformCategories';
  4. import {t} from 'sentry/locale';
  5. import {
  6. NewQuery,
  7. Organization,
  8. OrganizationSummary,
  9. PageFilters,
  10. Project,
  11. ReleaseProject,
  12. } from 'sentry/types';
  13. import {statsPeriodToDays} from 'sentry/utils/dates';
  14. import EventView, {EventData} 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 toArray from 'sentry/utils/toArray';
  20. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  21. export const QUERY_KEYS = [
  22. 'environment',
  23. 'project',
  24. 'query',
  25. 'start',
  26. 'end',
  27. 'statsPeriod',
  28. ] as const;
  29. export const UNPARAMETERIZED_TRANSACTION = '<< unparameterized >>'; // Represents 'other' transactions with high cardinality names that were dropped on the metrics dataset.
  30. const UNPARAMETRIZED_TRANSACTION = '<< unparametrized >>'; // Old spelling. Can be deleted in the future when all data for this transaction name is gone.
  31. export const EXCLUDE_METRICS_UNPARAM_CONDITIONS = `(!transaction:"${UNPARAMETERIZED_TRANSACTION}" AND !transaction:"${UNPARAMETRIZED_TRANSACTION}")`;
  32. const SHOW_UNPARAM_BANNER = 'showUnparameterizedBanner';
  33. export enum DiscoverQueryPageSource {
  34. PERFORMANCE = 'performance',
  35. DISCOVER = 'discover',
  36. }
  37. export function createUnnamedTransactionsDiscoverTarget(props: {
  38. location: Location;
  39. organization: Organization;
  40. source?: DiscoverQueryPageSource;
  41. }) {
  42. const fields =
  43. props.source === DiscoverQueryPageSource.DISCOVER
  44. ? ['transaction', 'project', 'transaction.source', 'epm()']
  45. : ['transaction', 'project', 'transaction.source', 'epm()', 'p50()', 'p95()'];
  46. const query: NewQuery = {
  47. id: undefined,
  48. name:
  49. props.source === DiscoverQueryPageSource.DISCOVER
  50. ? t('Unparameterized Transactions')
  51. : t('Performance - Unparameterized Transactions'),
  52. query: 'event.type:transaction transaction.source:"url"',
  53. projects: [],
  54. fields,
  55. version: 2,
  56. };
  57. const discoverEventView = EventView.fromNewQueryWithLocation(
  58. query,
  59. props.location
  60. ).withSorts([{field: 'epm', kind: 'desc'}]);
  61. const target = discoverEventView.getResultsViewUrlTarget(props.organization.slug);
  62. target.query[SHOW_UNPARAM_BANNER] = 'true';
  63. return target;
  64. }
  65. /**
  66. * Performance type can used to determine a default view or which specific field should be used by default on pages
  67. * where we don't want to wait for transaction data to return to determine how to display aspects of a page.
  68. */
  69. export enum PROJECT_PERFORMANCE_TYPE {
  70. ANY = 'any', // Fallback to transaction duration
  71. FRONTEND = 'frontend',
  72. BACKEND = 'backend',
  73. FRONTEND_OTHER = 'frontend_other',
  74. MOBILE = 'mobile',
  75. }
  76. // The native SDK is equally used on clients and end-devices as on
  77. // backend, the default view should be "All Transactions".
  78. const FRONTEND_PLATFORMS: string[] = [...frontend].filter(
  79. platform => platform !== 'javascript-nextjs' // Next has both frontend and backend transactions.
  80. );
  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. const projectPerformanceTypes = new Set<PROJECT_PERFORMANCE_TYPE>();
  97. selectedProjects.forEach(project => {
  98. if (FRONTEND_PLATFORMS.includes(project.platform ?? '')) {
  99. projectPerformanceTypes.add(PROJECT_PERFORMANCE_TYPE.FRONTEND);
  100. }
  101. if (BACKEND_PLATFORMS.includes(project.platform ?? '')) {
  102. projectPerformanceTypes.add(PROJECT_PERFORMANCE_TYPE.BACKEND);
  103. }
  104. if (MOBILE_PLATFORMS.includes(project.platform ?? '')) {
  105. projectPerformanceTypes.add(PROJECT_PERFORMANCE_TYPE.MOBILE);
  106. }
  107. });
  108. const uniquePerformanceTypeCount = projectPerformanceTypes.size;
  109. if (!uniquePerformanceTypeCount || uniquePerformanceTypeCount > 1) {
  110. return PROJECT_PERFORMANCE_TYPE.ANY;
  111. }
  112. const [platformType] = projectPerformanceTypes;
  113. return platformType;
  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 removeTracingKeysFromSearch(
  159. currentFilter: MutableSearch,
  160. options: {excludeTagKeys: Set<string>} = {
  161. excludeTagKeys: new Set([
  162. // event type can be "transaction" but we're searching for issues
  163. 'event.type',
  164. // the project is already determined by the transaction,
  165. // and issue search does not support the project filter
  166. 'project',
  167. ]),
  168. }
  169. ) {
  170. currentFilter.getFilterKeys().forEach(tagKey => {
  171. const searchKey = tagKey.startsWith('!') ? tagKey.substr(1) : tagKey;
  172. // Remove aggregates and transaction event fields
  173. if (
  174. // aggregates
  175. searchKey.match(/\w+\(.*\)/) ||
  176. // transaction event fields
  177. TRACING_FIELDS.includes(searchKey) ||
  178. // tags that we don't want to pass to pass to issue search
  179. options.excludeTagKeys.has(searchKey)
  180. ) {
  181. currentFilter.removeFilter(tagKey);
  182. }
  183. });
  184. return currentFilter;
  185. }
  186. export function addRoutePerformanceContext(selection: PageFilters) {
  187. const transaction = getCurrentSentryReactTransaction();
  188. const days = statsPeriodToDays(
  189. selection.datetime.period,
  190. selection.datetime.start,
  191. selection.datetime.end
  192. );
  193. const oneDay = 86400;
  194. const seconds = Math.floor(days * oneDay);
  195. transaction?.setTag('query.period', seconds.toString());
  196. let groupedPeriod = '>30d';
  197. if (seconds <= oneDay) {
  198. groupedPeriod = '<=1d';
  199. } else if (seconds <= oneDay * 7) {
  200. groupedPeriod = '<=7d';
  201. } else if (seconds <= oneDay * 14) {
  202. groupedPeriod = '<=14d';
  203. } else if (seconds <= oneDay * 30) {
  204. groupedPeriod = '<=30d';
  205. }
  206. transaction?.setTag('query.period.grouped', groupedPeriod);
  207. }
  208. export function getTransactionName(location: Location): string | undefined {
  209. const {transaction} = location.query;
  210. return decodeScalar(transaction);
  211. }
  212. export function getPerformanceDuration(milliseconds: number) {
  213. return getDuration(milliseconds / 1000, milliseconds > 1000 ? 2 : 0, true);
  214. }
  215. export function areMultipleProjectsSelected(eventView: EventView) {
  216. if (!eventView.project.length) {
  217. return true; // My projects
  218. }
  219. if (eventView.project.length === 1 && eventView.project[0] === ALL_ACCESS_PROJECTS) {
  220. return true; // All projects
  221. }
  222. return false;
  223. }
  224. export function getSelectedProjectPlatformsArray(
  225. location: Location,
  226. projects: Project[]
  227. ) {
  228. const projectQuery = location.query.project;
  229. const selectedProjectIdSet = new Set(toArray(projectQuery));
  230. const selectedProjectPlatforms = projects.reduce((acc: string[], project) => {
  231. if (selectedProjectIdSet.has(project.id)) {
  232. acc.push(project.platform ?? 'undefined');
  233. }
  234. return acc;
  235. }, []);
  236. return selectedProjectPlatforms;
  237. }
  238. export function getSelectedProjectPlatforms(location: Location, projects: Project[]) {
  239. const selectedProjectPlatforms = getSelectedProjectPlatformsArray(location, projects);
  240. return selectedProjectPlatforms.join(', ');
  241. }
  242. export function getProjectID(
  243. eventData: EventData,
  244. projects: Project[]
  245. ): string | undefined {
  246. const projectSlug = (eventData?.project as string) || undefined;
  247. if (typeof projectSlug === undefined) {
  248. return undefined;
  249. }
  250. return projects.find(currentProject => currentProject.slug === projectSlug)?.id;
  251. }