profileDetails.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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 CompactSelect from 'sentry/components/compactSelect';
  7. import GridEditable, {
  8. COL_WIDTH_UNDEFINED,
  9. GridColumnOrder,
  10. GridColumnSortBy,
  11. } from 'sentry/components/gridEditable';
  12. import * as Layout from 'sentry/components/layouts/thirds';
  13. import Pagination from 'sentry/components/pagination';
  14. import SearchBar from 'sentry/components/searchBar';
  15. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  16. import {t} from 'sentry/locale';
  17. import space from 'sentry/styles/space';
  18. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  19. import {Container, NumberContainer} from 'sentry/utils/discover/styles';
  20. import {CallTreeNode} from 'sentry/utils/profiling/callTreeNode';
  21. import {Profile} from 'sentry/utils/profiling/profile/profile';
  22. import {generateProfileFlamechartRouteWithQuery} from 'sentry/utils/profiling/routes';
  23. import {renderTableHead} from 'sentry/utils/profiling/tableRenderer';
  24. import {makeFormatter} from 'sentry/utils/profiling/units/units';
  25. import {decodeScalar} from 'sentry/utils/queryString';
  26. import {useEffectAfterFirstRender} from 'sentry/utils/useEffectAfterFirstRender';
  27. import {useLocation} from 'sentry/utils/useLocation';
  28. import useOrganization from 'sentry/utils/useOrganization';
  29. import {useParams} from 'sentry/utils/useParams';
  30. import {useProfileGroup} from './profileGroupProvider';
  31. function collectTopProfileFrames(profile: Profile) {
  32. const nodes: CallTreeNode[] = [];
  33. profile.forEach(
  34. node => {
  35. if (node.selfWeight > 0) {
  36. nodes.push(node);
  37. }
  38. },
  39. () => {}
  40. );
  41. return (
  42. nodes
  43. .sort((a, b) => b.selfWeight - a.selfWeight)
  44. // take only the slowest nodes from each thread because the rest
  45. // aren't useful to display
  46. .slice(0, 500)
  47. .map(node => ({
  48. symbol: node.frame.name,
  49. image: node.frame.image,
  50. thread: profile.threadId,
  51. type: node.frame.is_application ? 'application' : 'system',
  52. 'self weight': node.selfWeight,
  53. 'total weight': node.totalWeight,
  54. }))
  55. );
  56. }
  57. const RESULTS_PER_PAGE = 50;
  58. function ProfileDetails() {
  59. const location = useLocation();
  60. const [state] = useProfileGroup();
  61. const organization = useOrganization();
  62. useEffect(() => {
  63. trackAdvancedAnalyticsEvent('profiling_views.profile_summary', {
  64. organization,
  65. });
  66. }, [organization]);
  67. const cursor = useMemo<number>(() => {
  68. const cursorQuery = decodeScalar(location.query.cursor, '');
  69. return parseInt(cursorQuery, 10) || 0;
  70. }, [location.query.cursor]);
  71. const query = useMemo<string>(() => decodeScalar(location.query.query, ''), [location]);
  72. const allFunctions: TableDataRow[] = useMemo(() => {
  73. return state.type === 'resolved'
  74. ? state.data.profiles
  75. .flatMap(collectTopProfileFrames)
  76. // Self weight desc sort
  77. .sort((a, b) => b['self weight'] - a['self weight'])
  78. : [];
  79. }, [state]);
  80. const searchIndex = useMemo(() => {
  81. return new Fuse(allFunctions, {
  82. keys: ['symbol'],
  83. threshold: 0.3,
  84. });
  85. }, [allFunctions]);
  86. const search = useCallback(
  87. (queryString: string) => {
  88. if (!queryString) {
  89. return allFunctions;
  90. }
  91. return searchIndex.search(queryString).map(result => result.item);
  92. },
  93. [searchIndex, allFunctions]
  94. );
  95. const [slowestFunctions, setSlowestFunctions] = useState<TableDataRow[]>(() => {
  96. return search(query);
  97. });
  98. useEffectAfterFirstRender(() => {
  99. setSlowestFunctions(search(query));
  100. }, [allFunctions, query, search]);
  101. const pageLinks = useMemo(() => {
  102. const prevResults = cursor >= RESULTS_PER_PAGE ? 'true' : 'false';
  103. const prevCursor = cursor >= RESULTS_PER_PAGE ? cursor - RESULTS_PER_PAGE : 0;
  104. const prevQuery = {...location.query, cursor: prevCursor};
  105. const prevHref = `${location.pathname}${qs.stringify(prevQuery)}`;
  106. const prev = `<${prevHref}>; rel="previous"; results="${prevResults}"; cursor="${prevCursor}"`;
  107. const nextResults =
  108. cursor + RESULTS_PER_PAGE < slowestFunctions.length ? 'true' : 'false';
  109. const nextCursor =
  110. cursor + RESULTS_PER_PAGE < slowestFunctions.length ? cursor + RESULTS_PER_PAGE : 0;
  111. const nextQuery = {...location.query, cursor: nextCursor};
  112. const nextHref = `${location.pathname}${qs.stringify(nextQuery)}`;
  113. const next = `<${nextHref}>; rel="next"; results="${nextResults}"; cursor="${nextCursor}"`;
  114. return `${prev},${next}`;
  115. }, [cursor, location, slowestFunctions]);
  116. const handleSearch = useCallback(
  117. searchString => {
  118. browserHistory.replace({
  119. ...location,
  120. query: {
  121. ...location.query,
  122. query: searchString,
  123. cursor: undefined,
  124. },
  125. });
  126. setSlowestFunctions(search(searchString));
  127. },
  128. [location, search]
  129. );
  130. const [filters, setFilters] = useState<Partial<Record<TableColumnKey, string[]>>>({});
  131. const columnFilters = useMemo(() => {
  132. function makeOnFilterChange(key: string) {
  133. return values => {
  134. setFilters(prevFilters => ({
  135. ...prevFilters,
  136. [key]: values.length > 0 ? values.map(val => val.value) : undefined,
  137. }));
  138. };
  139. }
  140. return {
  141. type: {
  142. values: ['application', 'system'],
  143. onChange: makeOnFilterChange('type'),
  144. },
  145. image: {
  146. values: pluckUniqueValues(slowestFunctions, 'image').sort((a, b) =>
  147. a.localeCompare(b)
  148. ),
  149. onChange: makeOnFilterChange('image'),
  150. },
  151. };
  152. }, [slowestFunctions]);
  153. const currentSort = useMemo<GridColumnSortBy<TableColumnKey>>(() => {
  154. let key = location.query?.functionsSort ?? '';
  155. const defaultSort = {
  156. key: 'self weight',
  157. order: 'desc',
  158. } as GridColumnSortBy<TableColumnKey>;
  159. const isDesc = key[0] === '-';
  160. if (isDesc) {
  161. key = key.slice(1);
  162. }
  163. if (!key || !tableColumnKey.includes(key as TableColumnKey)) {
  164. return defaultSort;
  165. }
  166. return {
  167. key,
  168. order: isDesc ? 'desc' : 'asc',
  169. } as GridColumnSortBy<TableColumnKey>;
  170. }, [location.query]);
  171. useEffect(() => {
  172. const removeListener = browserHistory.listenBefore((nextLocation, next) => {
  173. if (location.pathname === nextLocation.pathname) {
  174. next(nextLocation);
  175. return;
  176. }
  177. if ('functionsSort' in nextLocation.query) {
  178. delete nextLocation.query.functionsSort;
  179. }
  180. next(nextLocation);
  181. });
  182. return removeListener;
  183. });
  184. const generateSortLink = useCallback(
  185. (column: TableColumnKey) => {
  186. if (!SORTABLE_COLUMNS.has(column)) {
  187. return () => undefined;
  188. }
  189. if (!currentSort) {
  190. return () => ({
  191. ...location,
  192. query: {
  193. ...location.query,
  194. functionsSort: column,
  195. },
  196. });
  197. }
  198. const direction =
  199. currentSort.key !== column
  200. ? 'desc'
  201. : currentSort.order === 'desc'
  202. ? 'asc'
  203. : 'desc';
  204. return () => ({
  205. ...location,
  206. query: {
  207. ...location.query,
  208. functionsSort: `${direction === 'desc' ? '-' : ''}${column}`,
  209. },
  210. });
  211. },
  212. [location, currentSort]
  213. );
  214. const data = slowestFunctions
  215. .filter(row => {
  216. let include = true;
  217. for (const key in filters) {
  218. const values = filters[key];
  219. if (!values) {
  220. continue;
  221. }
  222. include = values.includes(row[key]);
  223. if (!include) {
  224. return false;
  225. }
  226. }
  227. return include;
  228. })
  229. .sort((a, b) => {
  230. if (currentSort.order === 'asc') {
  231. return a[currentSort.key] - b[currentSort.key];
  232. }
  233. return b[currentSort.key] - a[currentSort.key];
  234. })
  235. .slice(cursor, cursor + RESULTS_PER_PAGE);
  236. return (
  237. <Fragment>
  238. <SentryDocumentTitle
  239. title={t('Profiling \u2014 Details')}
  240. orgSlug={organization.slug}
  241. >
  242. <Layout.Body>
  243. <Layout.Main fullWidth>
  244. <ActionBar>
  245. <SearchBar
  246. defaultQuery=""
  247. query={query}
  248. placeholder={t('Search for frames')}
  249. onChange={handleSearch}
  250. />
  251. <CompactSelect
  252. options={columnFilters.type.values.map(value => ({value, label: value}))}
  253. value={filters.type}
  254. triggerLabel={
  255. !filters.type ||
  256. (Array.isArray(filters.type) &&
  257. filters.type.length === columnFilters.type.values.length)
  258. ? t('All')
  259. : undefined
  260. }
  261. triggerProps={{
  262. prefix: t('Type'),
  263. }}
  264. multiple
  265. onChange={columnFilters.type.onChange}
  266. placement="bottom right"
  267. />
  268. <CompactSelect
  269. options={columnFilters.image.values.map(value => ({value, label: value}))}
  270. value={filters.image}
  271. triggerLabel={
  272. !filters.image ||
  273. (Array.isArray(filters.image) &&
  274. filters.image.length === columnFilters.image.values.length)
  275. ? t('All')
  276. : undefined
  277. }
  278. triggerProps={{
  279. prefix: t('Package'),
  280. }}
  281. multiple
  282. onChange={columnFilters.image.onChange}
  283. placement="bottom right"
  284. />
  285. </ActionBar>
  286. <GridEditable
  287. title={t('Slowest Functions')}
  288. isLoading={state.type === 'loading'}
  289. error={state.type === 'errored'}
  290. data={data}
  291. columnOrder={COLUMN_ORDER.map(key => COLUMNS[key])}
  292. columnSortBy={[currentSort]}
  293. grid={{
  294. renderHeadCell: renderTableHead({
  295. rightAlignedColumns: RIGHT_ALIGNED_COLUMNS,
  296. sortableColumns: RIGHT_ALIGNED_COLUMNS,
  297. currentSort,
  298. generateSortLink,
  299. }),
  300. renderBodyCell: renderFunctionCell,
  301. }}
  302. location={location}
  303. />
  304. <Pagination pageLinks={pageLinks} />
  305. </Layout.Main>
  306. </Layout.Body>
  307. </SentryDocumentTitle>
  308. </Fragment>
  309. );
  310. }
  311. function pluckUniqueValues<T extends Record<string, any>>(collection: T[], key: keyof T) {
  312. return collection.reduce((acc, val) => {
  313. if (!acc.includes(val[key])) {
  314. acc.push(val[key]);
  315. }
  316. return acc;
  317. }, [] as string[]);
  318. }
  319. const RIGHT_ALIGNED_COLUMNS = new Set<TableColumnKey>(['self weight', 'total weight']);
  320. const SORTABLE_COLUMNS = new Set<TableColumnKey>(['self weight', 'total weight']);
  321. const ActionBar = styled('div')`
  322. display: grid;
  323. grid-template-columns: 1fr auto auto;
  324. gap: ${space(2)};
  325. margin-bottom: ${space(2)};
  326. `;
  327. function renderFunctionCell(
  328. column: TableColumn,
  329. dataRow: TableDataRow,
  330. rowIndex: number,
  331. columnIndex: number
  332. ) {
  333. return (
  334. <ProfilingFunctionsTableCell
  335. column={column}
  336. dataRow={dataRow}
  337. rowIndex={rowIndex}
  338. columnIndex={columnIndex}
  339. />
  340. );
  341. }
  342. interface ProfilingFunctionsTableCellProps {
  343. column: TableColumn;
  344. columnIndex: number;
  345. dataRow: TableDataRow;
  346. rowIndex: number;
  347. }
  348. const formatter = makeFormatter('nanoseconds');
  349. function ProfilingFunctionsTableCell({
  350. column,
  351. dataRow,
  352. }: ProfilingFunctionsTableCellProps) {
  353. const value = dataRow[column.key];
  354. const {orgId, projectId, eventId} = useParams();
  355. switch (column.key) {
  356. case 'self weight':
  357. return <NumberContainer>{formatter(value)}</NumberContainer>;
  358. case 'total weight':
  359. return <NumberContainer>{formatter(value)}</NumberContainer>;
  360. case 'image':
  361. return <Container>{value ?? 'Unknown'}</Container>;
  362. case 'thread': {
  363. return (
  364. <Container>
  365. <Link
  366. to={generateProfileFlamechartRouteWithQuery({
  367. orgSlug: orgId,
  368. projectSlug: projectId,
  369. profileId: eventId,
  370. query: {tid: dataRow.thread},
  371. })}
  372. >
  373. {value}
  374. </Link>
  375. </Container>
  376. );
  377. }
  378. default:
  379. return <Container>{value}</Container>;
  380. }
  381. }
  382. const tableColumnKey = [
  383. 'symbol',
  384. 'image',
  385. 'thread',
  386. 'type',
  387. 'self weight',
  388. 'total weight',
  389. ] as const;
  390. type TableColumnKey = typeof tableColumnKey[number];
  391. type TableDataRow = Record<TableColumnKey, any>;
  392. type TableColumn = GridColumnOrder<TableColumnKey>;
  393. const COLUMN_ORDER: TableColumnKey[] = [
  394. 'symbol',
  395. 'image',
  396. 'thread',
  397. 'type',
  398. 'self weight',
  399. 'total weight',
  400. ];
  401. // TODO: looks like these column names change depending on the platform?
  402. const COLUMNS: Record<TableColumnKey, TableColumn> = {
  403. symbol: {
  404. key: 'symbol',
  405. name: t('Symbol'),
  406. width: COL_WIDTH_UNDEFINED,
  407. },
  408. image: {
  409. key: 'image',
  410. name: t('Package'),
  411. width: COL_WIDTH_UNDEFINED,
  412. },
  413. thread: {
  414. key: 'thread',
  415. name: t('Thread'),
  416. width: COL_WIDTH_UNDEFINED,
  417. },
  418. type: {
  419. key: 'type',
  420. name: t('Type'),
  421. width: COL_WIDTH_UNDEFINED,
  422. },
  423. 'self weight': {
  424. key: 'self weight',
  425. name: t('Self Weight'),
  426. width: COL_WIDTH_UNDEFINED,
  427. },
  428. 'total weight': {
  429. key: 'total weight',
  430. name: t('Total Weight'),
  431. width: COL_WIDTH_UNDEFINED,
  432. },
  433. };
  434. export default ProfileDetails;