regressedProfileFunctions.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. import {useCallback, useMemo, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import type {SelectOption} from 'sentry/components/compactSelect';
  5. import {CompactSelect} from 'sentry/components/compactSelect';
  6. import Link from 'sentry/components/links/link';
  7. import LoadingIndicator from 'sentry/components/loadingIndicator';
  8. import Pagination from 'sentry/components/pagination';
  9. import PerformanceDuration from 'sentry/components/performanceDuration';
  10. import {TextTruncateOverflow} from 'sentry/components/profiling/textTruncateOverflow';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import {trackAnalytics} from 'sentry/utils/analytics';
  14. import {formatPercentage} from 'sentry/utils/formatters';
  15. import type {FunctionTrend, TrendType} from 'sentry/utils/profiling/hooks/types';
  16. import {useCurrentProjectFromRouteParam} from 'sentry/utils/profiling/hooks/useCurrentProjectFromRouteParam';
  17. import {useProfileFunctionTrends} from 'sentry/utils/profiling/hooks/useProfileFunctionTrends';
  18. import {generateProfileFlamechartRouteWithQuery} from 'sentry/utils/profiling/routes';
  19. import {relativeChange} from 'sentry/utils/profiling/units/units';
  20. import {decodeScalar} from 'sentry/utils/queryString';
  21. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  22. import {useLocation} from 'sentry/utils/useLocation';
  23. import useOrganization from 'sentry/utils/useOrganization';
  24. import {ProfilingSparklineChart} from './profilingSparklineChart';
  25. const REGRESSED_FUNCTIONS_LIMIT = 5;
  26. const REGRESSED_FUNCTIONS_CURSOR = 'functionRegressionCursor';
  27. function trendToPoints(trend: FunctionTrend): {timestamp: number; value: number}[] {
  28. if (!trend.stats.data.length) {
  29. return [];
  30. }
  31. return trend.stats.data.map(p => {
  32. return {
  33. timestamp: p[0],
  34. value: p[1][0].count,
  35. };
  36. });
  37. }
  38. function findBreakPointIndex(
  39. breakpoint: number,
  40. worst: FunctionTrend['worst']
  41. ): number | undefined {
  42. let low = 0;
  43. let high = worst.length - 1;
  44. let mid = 0;
  45. let bestMatch: number | undefined;
  46. // eslint-disable-next-line
  47. while (low <= high) {
  48. mid = Math.floor((low + high) / 2);
  49. const value = worst[mid][0];
  50. if (breakpoint === value) {
  51. return mid;
  52. }
  53. if (breakpoint > value) {
  54. low = mid + 1;
  55. bestMatch = mid;
  56. } else if (breakpoint < value) {
  57. high = mid - 1;
  58. }
  59. }
  60. // We dont need an exact match as the breakpoint is not guaranteed to be
  61. // in the worst array, so we return the closest index
  62. return bestMatch;
  63. }
  64. function findWorstProfileIDBeforeAndAfter(trend: FunctionTrend): {
  65. after: string;
  66. before: string;
  67. } {
  68. const breakPointIndex = findBreakPointIndex(trend.breakpoint, trend.worst);
  69. if (breakPointIndex === undefined) {
  70. throw new Error('Could not find breakpoint index');
  71. }
  72. let beforeProfileID = '';
  73. let afterProfileID = '';
  74. const STABILITY_WINDOW = 2 * 60 * 1000;
  75. for (let i = breakPointIndex; i >= 0; i--) {
  76. if (trend.worst[i][0] < trend.breakpoint - STABILITY_WINDOW) {
  77. break;
  78. }
  79. beforeProfileID = trend.worst[i][1];
  80. }
  81. for (let i = breakPointIndex; i < trend.worst.length; i++) {
  82. if (trend.worst[i][0] > trend.breakpoint + STABILITY_WINDOW) {
  83. break;
  84. }
  85. afterProfileID = trend.worst[i][1];
  86. }
  87. return {
  88. before: beforeProfileID,
  89. after: afterProfileID,
  90. };
  91. }
  92. interface MostRegressedProfileFunctionsProps {
  93. transaction: string;
  94. }
  95. export function MostRegressedProfileFunctions(props: MostRegressedProfileFunctionsProps) {
  96. const organization = useOrganization();
  97. const project = useCurrentProjectFromRouteParam();
  98. const location = useLocation();
  99. const fnTrendCursor = useMemo(
  100. () => decodeScalar(location.query[REGRESSED_FUNCTIONS_CURSOR]),
  101. [location.query]
  102. );
  103. const handleRegressedFunctionsCursor = useCallback((cursor, pathname, query) => {
  104. browserHistory.push({
  105. pathname,
  106. query: {...query, [REGRESSED_FUNCTIONS_CURSOR]: cursor},
  107. });
  108. }, []);
  109. const functionQuery = useMemo(() => {
  110. const conditions = new MutableSearch('');
  111. conditions.setFilterValues('is_application', ['1']);
  112. conditions.setFilterValues('transaction', [props.transaction]);
  113. return conditions.formatString();
  114. }, [props.transaction]);
  115. const [trendType, setTrendType] = useState<TrendType>('regression');
  116. const trendsQuery = useProfileFunctionTrends({
  117. trendFunction: 'p95()',
  118. trendType,
  119. query: functionQuery,
  120. limit: REGRESSED_FUNCTIONS_LIMIT,
  121. cursor: fnTrendCursor,
  122. });
  123. const trends = trendsQuery?.data ?? [];
  124. const onRegressedFunctionClick = useCallback(() => {
  125. trackAnalytics('profiling_views.go_to_flamegraph', {
  126. organization,
  127. source: `profiling_transaction.regressed_functions_table`,
  128. });
  129. }, [organization]);
  130. const onChangeTrendType = useCallback(v => setTrendType(v.value), []);
  131. return (
  132. <RegressedFunctionsContainer>
  133. <RegressedFunctionsTitleContainer>
  134. <RegressedFunctionsTypeSelect
  135. value={trendType}
  136. options={TREND_FUNCTION_OPTIONS}
  137. onChange={onChangeTrendType}
  138. triggerProps={TRIGGER_PROPS}
  139. offset={4}
  140. />
  141. <RegressedFunctionsPagination
  142. pageLinks={trendsQuery.getResponseHeader?.('Link')}
  143. onCursor={handleRegressedFunctionsCursor}
  144. size="xs"
  145. />
  146. </RegressedFunctionsTitleContainer>
  147. {trendsQuery.isLoading ? (
  148. <RegressedFunctionsQueryState>
  149. <LoadingIndicator size={36} />
  150. </RegressedFunctionsQueryState>
  151. ) : trendsQuery.isError ? (
  152. <RegressedFunctionsQueryState>
  153. {t('Failed to fetch regressed functions')}
  154. </RegressedFunctionsQueryState>
  155. ) : !trends.length ? (
  156. <RegressedFunctionsQueryState>
  157. {t('Horay, no regressed functions detected!')}
  158. </RegressedFunctionsQueryState>
  159. ) : (
  160. trends.map((fn, i) => {
  161. const {before, after} = findWorstProfileIDBeforeAndAfter(fn);
  162. return (
  163. <RegressedFunctionRow key={i}>
  164. <RegressedFunctionMainRow>
  165. <div>
  166. <Link
  167. onClick={onRegressedFunctionClick}
  168. to={generateProfileFlamechartRouteWithQuery({
  169. orgSlug: organization.slug,
  170. projectSlug: project?.slug ?? '',
  171. profileId: (fn['examples()']?.[0] as string) ?? '',
  172. query: {
  173. // specify the frame to focus, the flamegraph will switch
  174. // to the appropriate thread when these are specified
  175. frameName: fn.function as string,
  176. framePackage: fn.package as string,
  177. },
  178. })}
  179. >
  180. <TextTruncateOverflow>{fn.function}</TextTruncateOverflow>
  181. </Link>
  182. </div>
  183. <div>
  184. <Link
  185. onClick={onRegressedFunctionClick}
  186. to={generateProfileFlamechartRouteWithQuery({
  187. orgSlug: organization.slug,
  188. projectSlug: project?.slug ?? '',
  189. profileId: before,
  190. query: {
  191. // specify the frame to focus, the flamegraph will switch
  192. // to the appropriate thread when these are specified
  193. frameName: fn.function as string,
  194. framePackage: fn.package as string,
  195. },
  196. })}
  197. >
  198. <PerformanceDuration
  199. abbreviation
  200. nanoseconds={fn.aggregate_range_1 as number}
  201. />
  202. </Link>
  203. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  204. <Link
  205. onClick={onRegressedFunctionClick}
  206. to={generateProfileFlamechartRouteWithQuery({
  207. orgSlug: organization.slug,
  208. projectSlug: project?.slug ?? '',
  209. profileId: after,
  210. query: {
  211. // specify the frame to focus, the flamegraph will switch
  212. // to the appropriate thread when these are specified
  213. frameName: fn.function as string,
  214. framePackage: fn.package as string,
  215. },
  216. })}
  217. >
  218. <PerformanceDuration
  219. abbreviation
  220. nanoseconds={fn.aggregate_range_2 as number}
  221. />
  222. </Link>
  223. </div>
  224. </RegressedFunctionMainRow>
  225. <RegressedFunctionMetricsRow>
  226. <div>
  227. <TextTruncateOverflow>{fn.package}</TextTruncateOverflow>
  228. </div>
  229. <div>
  230. {/* We dont handle improvements as formatPercentage and relativeChange
  231. on lines below dont return absolute values, else we end up with a double sign */}
  232. {trendType === 'regression'
  233. ? fn.aggregate_range_1 < fn.aggregate_range_2
  234. ? '+'
  235. : '-'
  236. : null}
  237. {formatPercentage(
  238. relativeChange(fn.aggregate_range_2, fn.aggregate_range_1)
  239. )}
  240. </div>
  241. </RegressedFunctionMetricsRow>
  242. <RegressedFunctionSparklineContainer>
  243. <ProfilingSparklineChart points={trendToPoints(fn)} name="" />
  244. </RegressedFunctionSparklineContainer>
  245. </RegressedFunctionRow>
  246. );
  247. })
  248. )}
  249. </RegressedFunctionsContainer>
  250. );
  251. }
  252. const ChangeArrow = styled('span')`
  253. color: ${p => p.theme.subText};
  254. `;
  255. const RegressedFunctionsTypeSelect = styled(CompactSelect)`
  256. button {
  257. margin: 0;
  258. padding: 0;
  259. }
  260. `;
  261. const RegressedFunctionSparklineContainer = styled('div')``;
  262. const RegressedFunctionRow = styled('div')`
  263. position: relative;
  264. margin-bottom: ${space(1)};
  265. `;
  266. const RegressedFunctionMainRow = styled('div')`
  267. display: flex;
  268. align-items: center;
  269. justify-content: space-between;
  270. > div:first-child {
  271. min-width: 0;
  272. }
  273. > div:last-child {
  274. white-space: nowrap;
  275. }
  276. `;
  277. const RegressedFunctionMetricsRow = styled('div')`
  278. display: flex;
  279. align-items: center;
  280. justify-content: space-between;
  281. font-size: ${p => p.theme.fontSizeSmall};
  282. color: ${p => p.theme.subText};
  283. margin-top: ${space(0.25)};
  284. `;
  285. const RegressedFunctionsContainer = styled('div')`
  286. flex-basis: 80px;
  287. margin-top: ${space(0.5)};
  288. `;
  289. const RegressedFunctionsPagination = styled(Pagination)`
  290. margin: 0;
  291. `;
  292. const RegressedFunctionsTitleContainer = styled('div')`
  293. display: flex;
  294. align-items: center;
  295. justify-content: space-between;
  296. margin-bottom: ${space(0.5)};
  297. `;
  298. const RegressedFunctionsQueryState = styled('div')`
  299. text-align: center;
  300. padding: ${space(2)} ${space(0.5)};
  301. color: ${p => p.theme.subText};
  302. `;
  303. const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
  304. const TREND_FUNCTION_OPTIONS: SelectOption<TrendType>[] = [
  305. {
  306. label: t('Most regressed functions'),
  307. value: 'regression' as const,
  308. },
  309. {
  310. label: t('Most improved functions'),
  311. value: 'improvement' as const,
  312. },
  313. ];