profileDetails.tsx 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import {Fragment, useCallback, useEffect, useMemo, useState} from 'react';
  2. import {browserHistory, Link} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import Fuse from 'fuse.js';
  5. import * as qs from 'query-string';
  6. import GridEditable, {
  7. COL_WIDTH_UNDEFINED,
  8. GridColumnOrder,
  9. } from 'sentry/components/gridEditable';
  10. import * as Layout from 'sentry/components/layouts/thirds';
  11. import Pagination from 'sentry/components/pagination';
  12. import SearchBar from 'sentry/components/searchBar';
  13. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  14. import {t} from 'sentry/locale';
  15. import space from 'sentry/styles/space';
  16. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  17. import {Container, NumberContainer} from 'sentry/utils/discover/styles';
  18. import {CallTreeNode} from 'sentry/utils/profiling/callTreeNode';
  19. import {Profile} from 'sentry/utils/profiling/profile/profile';
  20. import {generateProfileFlamechartRouteWithQuery} from 'sentry/utils/profiling/routes';
  21. import {renderTableHead} from 'sentry/utils/profiling/tableRenderer';
  22. import {makeFormatter} from 'sentry/utils/profiling/units/units';
  23. import {decodeScalar} from 'sentry/utils/queryString';
  24. import {useEffectAfterFirstRender} from 'sentry/utils/useEffectAfterFirstRender';
  25. import {useLocation} from 'sentry/utils/useLocation';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import {useParams} from 'sentry/utils/useParams';
  28. import {useProfileGroup} from './profileGroupProvider';
  29. function collectTopProfileFrames(profile: Profile) {
  30. const nodes: CallTreeNode[] = [];
  31. profile.forEach(
  32. node => {
  33. if (node.selfWeight > 0) {
  34. nodes.push(node);
  35. }
  36. },
  37. () => {}
  38. );
  39. return (
  40. nodes
  41. .sort((a, b) => b.selfWeight - a.selfWeight)
  42. // take only the slowest nodes from each thread because the rest
  43. // aren't useful to display
  44. .slice(0, 500)
  45. .map(node => ({
  46. symbol: node.frame.name,
  47. image: node.frame.image,
  48. thread: profile.threadId,
  49. type: node.frame.is_application ? 'application' : 'system',
  50. 'self weight': node.selfWeight,
  51. 'total weight': node.totalWeight,
  52. }))
  53. );
  54. }
  55. const RESULTS_PER_PAGE = 50;
  56. function ProfileDetails() {
  57. const location = useLocation();
  58. const [state] = useProfileGroup();
  59. const organization = useOrganization();
  60. useEffect(() => {
  61. trackAdvancedAnalyticsEvent('profiling_views.profile_summary', {
  62. organization,
  63. });
  64. }, [organization]);
  65. const cursor = useMemo<number>(() => {
  66. const cursorQuery = decodeScalar(location.query.cursor, '');
  67. return parseInt(cursorQuery, 10) || 0;
  68. }, [location.query.cursor]);
  69. const query = useMemo<string>(() => decodeScalar(location.query.query, ''), [location]);
  70. const allFunctions: TableDataRow[] = useMemo(() => {
  71. return state.type === 'resolved'
  72. ? state.data.profiles
  73. .flatMap(collectTopProfileFrames)
  74. // Self weight desc sort
  75. .sort((a, b) => b['self weight'] - a['self weight'])
  76. : [];
  77. }, [state]);
  78. const searchIndex = useMemo(() => {
  79. return new Fuse(allFunctions, {
  80. keys: ['symbol'],
  81. threshold: 0.3,
  82. });
  83. }, [allFunctions]);
  84. const search = useCallback(
  85. (queryString: string) => {
  86. if (!queryString) {
  87. return allFunctions;
  88. }
  89. return searchIndex
  90. .search(queryString)
  91. .map(result => result.item)
  92. .sort((a, b) => b['self weight'] - a['self weight']);
  93. },
  94. [searchIndex, allFunctions]
  95. );
  96. const [slowestFunctions, setSlowestFunctions] = useState<TableDataRow[]>(() => {
  97. return search(query);
  98. });
  99. useEffectAfterFirstRender(() => {
  100. setSlowestFunctions(search(query));
  101. }, [allFunctions, query, search]);
  102. const pageLinks = useMemo(() => {
  103. const prevResults = cursor >= RESULTS_PER_PAGE ? 'true' : 'false';
  104. const prevCursor = cursor >= RESULTS_PER_PAGE ? cursor - RESULTS_PER_PAGE : 0;
  105. const prevQuery = {...location.query, cursor: prevCursor};
  106. const prevHref = `${location.pathname}${qs.stringify(prevQuery)}`;
  107. const prev = `<${prevHref}>; rel="previous"; results="${prevResults}"; cursor="${prevCursor}"`;
  108. const nextResults =
  109. cursor + RESULTS_PER_PAGE < slowestFunctions.length ? 'true' : 'false';
  110. const nextCursor =
  111. cursor + RESULTS_PER_PAGE < slowestFunctions.length ? cursor + RESULTS_PER_PAGE : 0;
  112. const nextQuery = {...location.query, cursor: nextCursor};
  113. const nextHref = `${location.pathname}${qs.stringify(nextQuery)}`;
  114. const next = `<${nextHref}>; rel="next"; results="${nextResults}"; cursor="${nextCursor}"`;
  115. return `${prev},${next}`;
  116. }, [cursor, location, slowestFunctions]);
  117. const handleSearch = useCallback(
  118. searchString => {
  119. browserHistory.replace({
  120. ...location,
  121. query: {
  122. ...location.query,
  123. query: searchString,
  124. cursor: undefined,
  125. },
  126. });
  127. setSlowestFunctions(search(searchString));
  128. },
  129. [location, search]
  130. );
  131. return (
  132. <Fragment>
  133. <SentryDocumentTitle
  134. title={t('Profiling \u2014 Details')}
  135. orgSlug={organization.slug}
  136. >
  137. <Layout.Body>
  138. <Layout.Main fullWidth>
  139. <ActionBar>
  140. <SearchBar
  141. defaultQuery=""
  142. query={query}
  143. placeholder={t('Search for frames')}
  144. onChange={handleSearch}
  145. />
  146. </ActionBar>
  147. <GridEditable
  148. title={t('Slowest Functions')}
  149. isLoading={state.type === 'loading'}
  150. error={state.type === 'errored'}
  151. data={slowestFunctions.slice(cursor, cursor + RESULTS_PER_PAGE)}
  152. columnOrder={COLUMN_ORDER.map(key => COLUMNS[key])}
  153. columnSortBy={[]}
  154. grid={{
  155. renderHeadCell: renderTableHead({
  156. rightAlignedColumns: RIGHT_ALIGNED_COLUMNS,
  157. }),
  158. renderBodyCell: renderFunctionCell,
  159. }}
  160. location={location}
  161. />
  162. <Pagination pageLinks={pageLinks} />
  163. </Layout.Main>
  164. </Layout.Body>
  165. </SentryDocumentTitle>
  166. </Fragment>
  167. );
  168. }
  169. const RIGHT_ALIGNED_COLUMNS = new Set<TableColumnKey>(['self weight', 'total weight']);
  170. const ActionBar = styled('div')`
  171. display: grid;
  172. gap: ${space(2)};
  173. grid-template-columns: auto;
  174. margin-bottom: ${space(2)};
  175. `;
  176. function renderFunctionCell(
  177. column: TableColumn,
  178. dataRow: TableDataRow,
  179. rowIndex: number,
  180. columnIndex: number
  181. ) {
  182. return (
  183. <ProfilingFunctionsTableCell
  184. column={column}
  185. dataRow={dataRow}
  186. rowIndex={rowIndex}
  187. columnIndex={columnIndex}
  188. />
  189. );
  190. }
  191. interface ProfilingFunctionsTableCellProps {
  192. column: TableColumn;
  193. columnIndex: number;
  194. dataRow: TableDataRow;
  195. rowIndex: number;
  196. }
  197. const formatter = makeFormatter('nanoseconds');
  198. function ProfilingFunctionsTableCell({
  199. column,
  200. dataRow,
  201. }: ProfilingFunctionsTableCellProps) {
  202. const value = dataRow[column.key];
  203. const {orgId, projectId, eventId} = useParams();
  204. switch (column.key) {
  205. case 'self weight':
  206. return <NumberContainer>{formatter(value)}</NumberContainer>;
  207. case 'total weight':
  208. return <NumberContainer>{formatter(value)}</NumberContainer>;
  209. case 'image':
  210. return <Container>{value ?? 'Unknown'}</Container>;
  211. case 'thread': {
  212. return (
  213. <Container>
  214. <Link
  215. to={generateProfileFlamechartRouteWithQuery({
  216. orgSlug: orgId,
  217. projectSlug: projectId,
  218. profileId: eventId,
  219. query: {tid: dataRow.thread},
  220. })}
  221. >
  222. {value}
  223. </Link>
  224. </Container>
  225. );
  226. }
  227. default:
  228. return <Container>{value}</Container>;
  229. }
  230. }
  231. type TableColumnKey =
  232. | 'symbol'
  233. | 'image'
  234. | 'self weight'
  235. | 'total weight'
  236. | 'thread'
  237. | 'type';
  238. type TableDataRow = Record<TableColumnKey, any>;
  239. type TableColumn = GridColumnOrder<TableColumnKey>;
  240. const COLUMN_ORDER: TableColumnKey[] = [
  241. 'symbol',
  242. 'image',
  243. 'thread',
  244. 'type',
  245. 'self weight',
  246. 'total weight',
  247. ];
  248. // TODO: looks like these column names change depending on the platform?
  249. const COLUMNS: Record<TableColumnKey, TableColumn> = {
  250. symbol: {
  251. key: 'symbol',
  252. name: t('Symbol'),
  253. width: COL_WIDTH_UNDEFINED,
  254. },
  255. image: {
  256. key: 'image',
  257. name: t('Binary'),
  258. width: COL_WIDTH_UNDEFINED,
  259. },
  260. thread: {
  261. key: 'thread',
  262. name: t('Thread'),
  263. width: COL_WIDTH_UNDEFINED,
  264. },
  265. type: {
  266. key: 'type',
  267. name: t('Type'),
  268. width: COL_WIDTH_UNDEFINED,
  269. },
  270. 'self weight': {
  271. key: 'self weight',
  272. name: t('Self Weight'),
  273. width: COL_WIDTH_UNDEFINED,
  274. },
  275. 'total weight': {
  276. key: 'total weight',
  277. name: t('Total Weight'),
  278. width: COL_WIDTH_UNDEFINED,
  279. },
  280. };
  281. export default ProfileDetails;