slowestFunctionsWidget.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. import {CSSProperties, Fragment, ReactNode, useCallback, useMemo, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Button} from 'sentry/components/button';
  5. import Count from 'sentry/components/count';
  6. import EmptyStateWarning from 'sentry/components/emptyStateWarning';
  7. import IdBadge from 'sentry/components/idBadge';
  8. import Link from 'sentry/components/links/link';
  9. import LoadingIndicator from 'sentry/components/loadingIndicator';
  10. import Pagination from 'sentry/components/pagination';
  11. import PerformanceDuration from 'sentry/components/performanceDuration';
  12. import ScoreBar from 'sentry/components/scoreBar';
  13. import TextOverflow from 'sentry/components/textOverflow';
  14. import {Tooltip} from 'sentry/components/tooltip';
  15. import {CHART_PALETTE} from 'sentry/constants/chartPalette';
  16. import {IconChevron, IconWarning} from 'sentry/icons';
  17. import {t, tct} from 'sentry/locale';
  18. import {space} from 'sentry/styles/space';
  19. import {trackAnalytics} from 'sentry/utils/analytics';
  20. import {EventsResultsDataRow} from 'sentry/utils/profiling/hooks/types';
  21. import {useProfileFunctions} from 'sentry/utils/profiling/hooks/useProfileFunctions';
  22. import {generateProfileFlamechartRouteWithQuery} from 'sentry/utils/profiling/routes';
  23. import {decodeScalar} from 'sentry/utils/queryString';
  24. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  25. import {useLocation} from 'sentry/utils/useLocation';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import useProjects from 'sentry/utils/useProjects';
  28. import {
  29. Accordion,
  30. AccordionItem,
  31. ContentContainer,
  32. HeaderContainer,
  33. HeaderTitleLegend,
  34. StatusContainer,
  35. Subtitle,
  36. WidgetContainer,
  37. } from './styles';
  38. const MAX_FUNCTIONS = 3;
  39. const DEFAULT_CURSOR_NAME = 'slowFnCursor';
  40. interface SlowestFunctionsWidgetProps {
  41. cursorName?: string;
  42. header?: ReactNode;
  43. userQuery?: string;
  44. widgetHeight?: string;
  45. }
  46. export function SlowestFunctionsWidget({
  47. cursorName = DEFAULT_CURSOR_NAME,
  48. header,
  49. userQuery,
  50. widgetHeight,
  51. }: SlowestFunctionsWidgetProps) {
  52. const location = useLocation();
  53. const [expandedIndex, setExpandedIndex] = useState(0);
  54. const slowFnCursor = useMemo(
  55. () => decodeScalar(location.query[cursorName]),
  56. [cursorName, location.query]
  57. );
  58. const handleCursor = useCallback(
  59. (cursor, pathname, query) => {
  60. browserHistory.push({
  61. pathname,
  62. query: {...query, [cursorName]: cursor},
  63. });
  64. },
  65. [cursorName]
  66. );
  67. const functionsQuery = useProfileFunctions<FunctionsField>({
  68. fields: functionsFields,
  69. referrer: 'api.profiling.suspect-functions.list',
  70. sort: {
  71. key: 'sum()',
  72. order: 'desc',
  73. },
  74. query: userQuery,
  75. limit: MAX_FUNCTIONS,
  76. cursor: slowFnCursor,
  77. });
  78. const hasFunctions = (functionsQuery.data?.data?.length || 0) > 0;
  79. const totalsQuery = useProfileFunctions<TotalsField>({
  80. fields: totalsFields,
  81. referrer: 'api.profiling.suspect-functions.totals',
  82. sort: {
  83. key: 'sum()',
  84. order: 'desc',
  85. },
  86. query: userQuery,
  87. limit: MAX_FUNCTIONS,
  88. // make sure to query for the projects from the top functions
  89. projects: functionsQuery.isFetched
  90. ? [
  91. ...new Set(
  92. (functionsQuery.data?.data ?? []).map(func => func['project.id'] as number)
  93. ),
  94. ]
  95. : [],
  96. enabled: functionsQuery.isFetched && hasFunctions,
  97. });
  98. const isLoading = functionsQuery.isLoading || (hasFunctions && totalsQuery.isLoading);
  99. const isError = functionsQuery.isError || totalsQuery.isError;
  100. return (
  101. <WidgetContainer height={widgetHeight}>
  102. <HeaderContainer>
  103. {header ?? <HeaderTitleLegend>{t('Slowest Functions')}</HeaderTitleLegend>}
  104. <Subtitle>{t('Slowest functions by total self time spent.')}</Subtitle>
  105. <StyledPagination
  106. pageLinks={functionsQuery.getResponseHeader?.('Link') ?? null}
  107. size="xs"
  108. onCursor={handleCursor}
  109. />
  110. </HeaderContainer>
  111. <ContentContainer>
  112. {isLoading && (
  113. <StatusContainer>
  114. <LoadingIndicator />
  115. </StatusContainer>
  116. )}
  117. {isError && (
  118. <StatusContainer>
  119. <IconWarning data-test-id="error-indicator" color="gray300" size="lg" />
  120. </StatusContainer>
  121. )}
  122. {!isError && !isLoading && !hasFunctions && (
  123. <EmptyStateWarning>
  124. <p>{t('No functions found')}</p>
  125. </EmptyStateWarning>
  126. )}
  127. {hasFunctions && totalsQuery.isFetched && (
  128. <StyledAccordion>
  129. {(functionsQuery.data?.data ?? []).map((f, i) => {
  130. const projectEntry = totalsQuery.data?.data?.find(
  131. row => row['project.id'] === f['project.id']
  132. );
  133. const projectTotalDuration = projectEntry?.['sum()'] ?? f['sum()'];
  134. return (
  135. <SlowestFunctionEntry
  136. key={`${f['project.id']}-${f.package}-${f.function}`}
  137. isExpanded={i === expandedIndex}
  138. setExpanded={() => setExpandedIndex(i)}
  139. func={f}
  140. totalDuration={projectTotalDuration as number}
  141. query={userQuery ?? ''}
  142. />
  143. );
  144. })}
  145. </StyledAccordion>
  146. )}
  147. </ContentContainer>
  148. </WidgetContainer>
  149. );
  150. }
  151. interface SlowestFunctionEntryProps {
  152. func: EventsResultsDataRow<FunctionsField>;
  153. isExpanded: boolean;
  154. query: string;
  155. setExpanded: () => void;
  156. totalDuration: number;
  157. }
  158. const BARS = 10;
  159. function SlowestFunctionEntry({
  160. func,
  161. isExpanded,
  162. query,
  163. setExpanded,
  164. totalDuration,
  165. }: SlowestFunctionEntryProps) {
  166. const organization = useOrganization();
  167. const {projects} = useProjects();
  168. const project = projects.find(p => p.id === String(func['project.id']));
  169. const score = Math.ceil((((func['sum()'] as number) ?? 0) / totalDuration) * BARS);
  170. const palette = new Array(BARS).fill([CHART_PALETTE[0][0]]);
  171. const userQuery = useMemo(() => {
  172. const conditions = new MutableSearch(query);
  173. conditions.setFilterValues('project.id', [String(func['project.id'])]);
  174. // it is more efficient to filter on the fingerprint
  175. // than it is to filter on the package + function
  176. conditions.setFilterValues('fingerprint', [String(func.fingerprint)]);
  177. return conditions.formatString();
  178. }, [func, query]);
  179. const functionTransactionsQuery = useProfileFunctions<FunctionTransactionField>({
  180. fields: functionTransactionsFields,
  181. referrer: 'api.profiling.suspect-functions.transactions',
  182. sort: {
  183. key: 'sum()',
  184. order: 'desc',
  185. },
  186. query: userQuery,
  187. limit: 5,
  188. enabled: isExpanded,
  189. });
  190. return (
  191. <Fragment>
  192. <StyledAccordionItem>
  193. {project && (
  194. <Tooltip title={project.name}>
  195. <IdBadge project={project} avatarSize={16} hideName />
  196. </Tooltip>
  197. )}
  198. <FunctionName>
  199. <Tooltip title={func.package}>{func.function}</Tooltip>
  200. </FunctionName>
  201. <Tooltip
  202. title={tct('Appeared [count] times for a total time spent of [totalSelfTime]', {
  203. count: <Count value={func['count()'] as number} />,
  204. totalSelfTime: (
  205. <PerformanceDuration nanoseconds={func['sum()'] as number} abbreviation />
  206. ),
  207. })}
  208. >
  209. <ScoreBar score={score} palette={palette} size={20} radius={0} />
  210. </Tooltip>
  211. <Button
  212. icon={<IconChevron size="xs" direction={isExpanded ? 'up' : 'down'} />}
  213. aria-label={t('Expand')}
  214. aria-expanded={isExpanded}
  215. size="zero"
  216. borderless
  217. onClick={() => setExpanded()}
  218. />
  219. </StyledAccordionItem>
  220. {isExpanded && (
  221. <Fragment>
  222. {functionTransactionsQuery.isError && (
  223. <StatusContainer>
  224. <IconWarning data-test-id="error-indicator" color="gray300" size="lg" />
  225. </StatusContainer>
  226. )}
  227. {functionTransactionsQuery.isLoading && (
  228. <StatusContainer>
  229. <LoadingIndicator />
  230. </StatusContainer>
  231. )}
  232. {functionTransactionsQuery.isFetched && (
  233. <TransactionsList data-test-id="transactions-list">
  234. <TransactionsListHeader>
  235. <TextOverflow>{t('Transaction')}</TextOverflow>
  236. </TransactionsListHeader>
  237. <TransactionsListHeader align="right">
  238. <TextOverflow>{t('Count')}</TextOverflow>
  239. </TransactionsListHeader>
  240. <TransactionsListHeader align="right">
  241. <TextOverflow>{t('P75()')}</TextOverflow>
  242. </TransactionsListHeader>
  243. <TransactionsListHeader align="right">
  244. <TextOverflow>{t('Time Spent')}</TextOverflow>
  245. </TransactionsListHeader>
  246. {(functionTransactionsQuery.data?.data ?? []).map(transaction => {
  247. const examples = transaction['examples()'] as string[];
  248. let transactionCol = <Fragment>{transaction.transaction}</Fragment>;
  249. if (project && examples.length) {
  250. const target = generateProfileFlamechartRouteWithQuery({
  251. orgSlug: organization.slug,
  252. projectSlug: project.slug,
  253. profileId: examples[0],
  254. query: {
  255. frameName: func.function as string,
  256. framePackage: func.package as string,
  257. },
  258. });
  259. transactionCol = (
  260. <Link
  261. to={target}
  262. onClick={() => {
  263. trackAnalytics('profiling_views.go_to_flamegraph', {
  264. organization,
  265. source: 'profiling.global_suspect_functions',
  266. });
  267. }}
  268. >
  269. {transactionCol}
  270. </Link>
  271. );
  272. }
  273. return (
  274. <Fragment key={transaction.transaction as string}>
  275. <TransactionsListCell>
  276. <TextOverflow>{transactionCol}</TextOverflow>
  277. </TransactionsListCell>
  278. <TransactionsListCell align="right">
  279. <Count value={transaction['count()'] as number} />
  280. </TransactionsListCell>
  281. <TransactionsListCell align="right">
  282. <PerformanceDuration
  283. nanoseconds={transaction['p75()'] as number}
  284. abbreviation
  285. />
  286. </TransactionsListCell>
  287. <TransactionsListCell align="right">
  288. <PerformanceDuration
  289. nanoseconds={transaction['sum()'] as number}
  290. abbreviation
  291. />
  292. </TransactionsListCell>
  293. </Fragment>
  294. );
  295. })}
  296. </TransactionsList>
  297. )}
  298. </Fragment>
  299. )}
  300. </Fragment>
  301. );
  302. }
  303. const functionsFields = [
  304. 'project.id',
  305. 'fingerprint',
  306. 'package',
  307. 'function',
  308. 'count()',
  309. 'sum()',
  310. ] as const;
  311. type FunctionsField = (typeof functionsFields)[number];
  312. const totalsFields = ['project.id', 'sum()'] as const;
  313. type TotalsField = (typeof totalsFields)[number];
  314. const functionTransactionsFields = [
  315. 'transaction',
  316. 'count()',
  317. 'p75()',
  318. 'sum()',
  319. 'examples()',
  320. ] as const;
  321. type FunctionTransactionField = (typeof functionTransactionsFields)[number];
  322. const StyledPagination = styled(Pagination)`
  323. margin: 0;
  324. `;
  325. const StyledAccordion = styled(Accordion)`
  326. display: flex;
  327. flex-direction: column;
  328. `;
  329. const StyledAccordionItem = styled(AccordionItem)`
  330. display: grid;
  331. grid-template-columns: auto 1fr auto auto;
  332. `;
  333. const FunctionName = styled(TextOverflow)`
  334. flex: 1 1 auto;
  335. `;
  336. const TransactionsList = styled('div')`
  337. flex: 1 1 auto;
  338. display: grid;
  339. grid-template-columns: minmax(0, 1fr) auto auto auto;
  340. grid-template-rows: 18px auto auto auto auto auto;
  341. column-gap: ${space(1)};
  342. padding: ${space(0)} ${space(2)};
  343. `;
  344. const TransactionsListHeader = styled('span')<{
  345. align?: CSSProperties['textAlign'];
  346. }>`
  347. text-transform: uppercase;
  348. font-size: ${p => p.theme.fontSizeExtraSmall};
  349. font-weight: 600;
  350. color: ${p => p.theme.subText};
  351. text-align: ${p => p.align};
  352. `;
  353. const TransactionsListCell = styled('div')<{align?: CSSProperties['textAlign']}>`
  354. font-size: ${p => p.theme.fontSizeSmall};
  355. text-align: ${p => p.align};
  356. padding: ${space(0.5)} 0px;
  357. `;