regressedProfileFunctions.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  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. {trendType === 'regression' ? (
  158. <p>{t('No regressed functions detected')}</p>
  159. ) : (
  160. <p>{t('No improved functions detected')}</p>
  161. )}
  162. </RegressedFunctionsQueryState>
  163. ) : (
  164. trends.map((fn, i) => {
  165. const {before, after} = findWorstProfileIDBeforeAndAfter(fn);
  166. return (
  167. <RegressedFunctionRow key={i}>
  168. <RegressedFunctionMainRow>
  169. <div>
  170. <Link
  171. onClick={onRegressedFunctionClick}
  172. to={generateProfileFlamechartRouteWithQuery({
  173. orgSlug: organization.slug,
  174. projectSlug: project?.slug ?? '',
  175. profileId: (fn['examples()']?.[0] as string) ?? '',
  176. query: {
  177. // specify the frame to focus, the flamegraph will switch
  178. // to the appropriate thread when these are specified
  179. frameName: fn.function as string,
  180. framePackage: fn.package as string,
  181. },
  182. })}
  183. >
  184. <TextTruncateOverflow>{fn.function}</TextTruncateOverflow>
  185. </Link>
  186. </div>
  187. <div>
  188. <Link
  189. onClick={onRegressedFunctionClick}
  190. to={generateProfileFlamechartRouteWithQuery({
  191. orgSlug: organization.slug,
  192. projectSlug: project?.slug ?? '',
  193. profileId: before,
  194. query: {
  195. // specify the frame to focus, the flamegraph will switch
  196. // to the appropriate thread when these are specified
  197. frameName: fn.function as string,
  198. framePackage: fn.package as string,
  199. },
  200. })}
  201. >
  202. <PerformanceDuration
  203. abbreviation
  204. nanoseconds={fn.aggregate_range_1 as number}
  205. />
  206. </Link>
  207. <ChangeArrow>{' \u2192 '}</ChangeArrow>
  208. <Link
  209. onClick={onRegressedFunctionClick}
  210. to={generateProfileFlamechartRouteWithQuery({
  211. orgSlug: organization.slug,
  212. projectSlug: project?.slug ?? '',
  213. profileId: after,
  214. query: {
  215. // specify the frame to focus, the flamegraph will switch
  216. // to the appropriate thread when these are specified
  217. frameName: fn.function as string,
  218. framePackage: fn.package as string,
  219. },
  220. })}
  221. >
  222. <PerformanceDuration
  223. abbreviation
  224. nanoseconds={fn.aggregate_range_2 as number}
  225. />
  226. </Link>
  227. </div>
  228. </RegressedFunctionMainRow>
  229. <RegressedFunctionMetricsRow>
  230. <div>
  231. <TextTruncateOverflow>{fn.package}</TextTruncateOverflow>
  232. </div>
  233. <div>
  234. {/* We dont handle improvements as formatPercentage and relativeChange
  235. on lines below dont return absolute values, else we end up with a double sign */}
  236. {trendType === 'regression'
  237. ? fn.aggregate_range_1 < fn.aggregate_range_2
  238. ? '+'
  239. : '-'
  240. : null}
  241. {formatPercentage(
  242. relativeChange(fn.aggregate_range_2, fn.aggregate_range_1)
  243. )}
  244. </div>
  245. </RegressedFunctionMetricsRow>
  246. <RegressedFunctionSparklineContainer>
  247. <ProfilingSparklineChart points={trendToPoints(fn)} name="" />
  248. </RegressedFunctionSparklineContainer>
  249. </RegressedFunctionRow>
  250. );
  251. })
  252. )}
  253. </RegressedFunctionsContainer>
  254. );
  255. }
  256. const ChangeArrow = styled('span')`
  257. color: ${p => p.theme.subText};
  258. `;
  259. const RegressedFunctionsTypeSelect = styled(CompactSelect)`
  260. button {
  261. margin: 0;
  262. padding: 0;
  263. }
  264. `;
  265. const RegressedFunctionSparklineContainer = styled('div')``;
  266. const RegressedFunctionRow = styled('div')`
  267. position: relative;
  268. margin-bottom: ${space(1)};
  269. `;
  270. const RegressedFunctionMainRow = styled('div')`
  271. display: flex;
  272. align-items: center;
  273. justify-content: space-between;
  274. > div:first-child {
  275. min-width: 0;
  276. }
  277. > div:last-child {
  278. white-space: nowrap;
  279. }
  280. `;
  281. const RegressedFunctionMetricsRow = styled('div')`
  282. display: flex;
  283. align-items: center;
  284. justify-content: space-between;
  285. font-size: ${p => p.theme.fontSizeSmall};
  286. color: ${p => p.theme.subText};
  287. margin-top: ${space(0.25)};
  288. `;
  289. const RegressedFunctionsContainer = styled('div')`
  290. flex-basis: 80px;
  291. padding: 0 ${space(1)};
  292. border-bottom: 1px solid ${p => p.theme.border};
  293. `;
  294. const RegressedFunctionsPagination = styled(Pagination)`
  295. margin: 0;
  296. button {
  297. height: 16px;
  298. width: 16px;
  299. min-width: 16px;
  300. min-height: 16px;
  301. svg {
  302. width: 10px;
  303. height: 10px;
  304. }
  305. }
  306. `;
  307. const RegressedFunctionsTitleContainer = styled('div')`
  308. display: flex;
  309. align-items: center;
  310. justify-content: space-between;
  311. margin-bottom: ${space(0.5)};
  312. margin-top: ${space(0.5)};
  313. `;
  314. const RegressedFunctionsQueryState = styled('div')`
  315. text-align: center;
  316. padding: ${space(2)} ${space(0.5)};
  317. color: ${p => p.theme.subText};
  318. `;
  319. const TRIGGER_PROPS = {borderless: true, size: 'zero' as const};
  320. const TREND_FUNCTION_OPTIONS: SelectOption<TrendType>[] = [
  321. {
  322. label: t('Most Regressed Functions'),
  323. value: 'regression' as const,
  324. },
  325. {
  326. label: t('Most Improved Functions'),
  327. value: 'improvement' as const,
  328. },
  329. ];