slowestFunctionsWidget.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  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('Suspect Functions')}</HeaderTitleLegend>}
  104. <Subtitle>{t('Slowest functions by total 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 self time 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('Total Self Time')}</TextOverflow>
  242. </TransactionsListHeader>
  243. {(functionTransactionsQuery.data?.data ?? []).map(transaction => {
  244. const examples = transaction['examples()'] as string[];
  245. let transactionCol = <Fragment>{transaction.transaction}</Fragment>;
  246. if (project && examples.length) {
  247. const target = generateProfileFlamechartRouteWithQuery({
  248. orgSlug: organization.slug,
  249. projectSlug: project.slug,
  250. profileId: examples[0],
  251. query: {
  252. frameName: func.function as string,
  253. framePackage: func.package as string,
  254. },
  255. });
  256. transactionCol = (
  257. <Link
  258. to={target}
  259. onClick={() => {
  260. trackAnalytics('profiling_views.go_to_flamegraph', {
  261. organization,
  262. source: 'profiling.global_suspect_functions',
  263. });
  264. }}
  265. >
  266. {transactionCol}
  267. </Link>
  268. );
  269. }
  270. return (
  271. <Fragment key={transaction.transaction as string}>
  272. <TransactionsListCell>
  273. <TextOverflow>{transactionCol}</TextOverflow>
  274. </TransactionsListCell>
  275. <TransactionsListCell align="right">
  276. <Count value={transaction['count()'] as number} />
  277. </TransactionsListCell>
  278. <TransactionsListCell align="right">
  279. <PerformanceDuration
  280. nanoseconds={transaction['sum()'] as number}
  281. abbreviation
  282. />
  283. </TransactionsListCell>
  284. </Fragment>
  285. );
  286. })}
  287. </TransactionsList>
  288. )}
  289. </Fragment>
  290. )}
  291. </Fragment>
  292. );
  293. }
  294. const functionsFields = [
  295. 'project.id',
  296. 'fingerprint',
  297. 'package',
  298. 'function',
  299. 'count()',
  300. 'sum()',
  301. ] as const;
  302. type FunctionsField = (typeof functionsFields)[number];
  303. const totalsFields = ['project.id', 'sum()'] as const;
  304. type TotalsField = (typeof totalsFields)[number];
  305. const functionTransactionsFields = [
  306. 'transaction',
  307. 'count()',
  308. 'sum()',
  309. 'examples()',
  310. ] as const;
  311. type FunctionTransactionField = (typeof functionTransactionsFields)[number];
  312. const StyledPagination = styled(Pagination)`
  313. margin: 0;
  314. `;
  315. const StyledAccordion = styled(Accordion)`
  316. display: flex;
  317. flex-direction: column;
  318. `;
  319. const StyledAccordionItem = styled(AccordionItem)`
  320. display: grid;
  321. grid-template-columns: auto 1fr auto auto;
  322. `;
  323. const FunctionName = styled(TextOverflow)`
  324. flex: 1 1 auto;
  325. `;
  326. const TransactionsList = styled('div')`
  327. flex: 1 1 auto;
  328. display: grid;
  329. grid-template-columns: minmax(0, 1fr) auto auto;
  330. grid-template-rows: 18px auto auto auto auto auto;
  331. column-gap: ${space(1)};
  332. padding: ${space(0)} ${space(2)};
  333. `;
  334. const TransactionsListHeader = styled('span')<{
  335. align?: CSSProperties['textAlign'];
  336. }>`
  337. text-transform: uppercase;
  338. font-size: ${p => p.theme.fontSizeExtraSmall};
  339. font-weight: 600;
  340. color: ${p => p.theme.subText};
  341. text-align: ${p => p.align};
  342. `;
  343. const TransactionsListCell = styled('div')<{align?: CSSProperties['textAlign']}>`
  344. font-size: ${p => p.theme.fontSizeSmall};
  345. text-align: ${p => p.align};
  346. padding: ${space(0.5)} 0px;
  347. `;