content.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import {Fragment, useCallback, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import {Button, LinkButton} from 'sentry/components/button';
  4. import ErrorPanel from 'sentry/components/charts/errorPanel';
  5. import {SectionHeading} from 'sentry/components/charts/styles';
  6. import {CompactSelect} from 'sentry/components/compactSelect';
  7. import type {SelectOption} from 'sentry/components/compactSelect/types';
  8. import Count from 'sentry/components/count';
  9. import {DateTime} from 'sentry/components/dateTime';
  10. import Link from 'sentry/components/links/link';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import Pagination from 'sentry/components/pagination';
  13. import PerformanceDuration from 'sentry/components/performanceDuration';
  14. import {AggregateFlamegraph} from 'sentry/components/profiling/flamegraph/aggregateFlamegraph';
  15. import {AggregateFlamegraphTreeTable} from 'sentry/components/profiling/flamegraph/aggregateFlamegraphTreeTable';
  16. import {FlamegraphSearch} from 'sentry/components/profiling/flamegraph/flamegraphToolbar/flamegraphSearch';
  17. import {SegmentedControl} from 'sentry/components/segmentedControl';
  18. import {IconProfiling, IconWarning} from 'sentry/icons';
  19. import {t} from 'sentry/locale';
  20. import {space} from 'sentry/styles/space';
  21. import type {DeepPartial} from 'sentry/types/utils';
  22. import {trackAnalytics} from 'sentry/utils/analytics';
  23. import {browserHistory} from 'sentry/utils/browserHistory';
  24. import {generateLinkToEventInTraceView} from 'sentry/utils/discover/urls';
  25. import {getShortEventId} from 'sentry/utils/events';
  26. import {isEmptyObject} from 'sentry/utils/object/isEmptyObject';
  27. import type {CanvasScheduler} from 'sentry/utils/profiling/canvasScheduler';
  28. import {
  29. CanvasPoolManager,
  30. useCanvasScheduler,
  31. } from 'sentry/utils/profiling/canvasScheduler';
  32. import type {FlamegraphState} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/flamegraphContext';
  33. import {FlamegraphStateProvider} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/flamegraphContextProvider';
  34. import {FlamegraphThemeProvider} from 'sentry/utils/profiling/flamegraph/flamegraphThemeProvider';
  35. import type {Frame} from 'sentry/utils/profiling/frame';
  36. import {isEventedProfile, isSampledProfile} from 'sentry/utils/profiling/guards/profile';
  37. import {useAggregateFlamegraphQuery} from 'sentry/utils/profiling/hooks/useAggregateFlamegraphQuery';
  38. import type {ProfilingFieldType} from 'sentry/utils/profiling/hooks/useProfileEvents';
  39. import {useProfileEvents} from 'sentry/utils/profiling/hooks/useProfileEvents';
  40. import {decodeScalar} from 'sentry/utils/queryString';
  41. import {useLocalStorageState} from 'sentry/utils/useLocalStorageState';
  42. import {useLocation} from 'sentry/utils/useLocation';
  43. import useOrganization from 'sentry/utils/useOrganization';
  44. import {
  45. FlamegraphProvider,
  46. useFlamegraph,
  47. } from 'sentry/views/profiling/flamegraphProvider';
  48. import {ProfileGroupProvider} from 'sentry/views/profiling/profileGroupProvider';
  49. import {TraceViewSources} from '../../newTraceDetails/traceHeader/breadcrumbs';
  50. import {generateProfileLink} from '../utils';
  51. const DEFAULT_FLAMEGRAPH_PREFERENCES: DeepPartial<FlamegraphState> = {
  52. preferences: {
  53. sorting: 'left heavy' satisfies FlamegraphState['preferences']['sorting'],
  54. },
  55. };
  56. const noop = () => void 0;
  57. interface TransactionProfilesContentProps {
  58. query: string;
  59. transaction: string;
  60. }
  61. export function TransactionProfilesContent(props: TransactionProfilesContentProps) {
  62. return (
  63. <TransactionProfilesContentContainer>
  64. <ProfileVisualization {...props} />
  65. <ProfileSidebarContainer>
  66. <ProfileDigest {...props} />
  67. <ProfileList {...props} />
  68. </ProfileSidebarContainer>
  69. </TransactionProfilesContentContainer>
  70. );
  71. }
  72. function isEmpty(resp: Profiling.Schema) {
  73. const profile = resp.profiles[0];
  74. if (!profile) {
  75. return true;
  76. }
  77. if (
  78. resp.profiles.length === 1 &&
  79. isSampledProfile(profile) &&
  80. profile.startValue === 0 &&
  81. profile.endValue === 0
  82. ) {
  83. return true;
  84. }
  85. if (
  86. resp.profiles.length === 1 &&
  87. isEventedProfile(profile) &&
  88. profile.startValue === 0 &&
  89. profile.endValue === 0
  90. ) {
  91. return true;
  92. }
  93. return false;
  94. }
  95. function ProfileVisualization(props: TransactionProfilesContentProps) {
  96. const {data, status} = useAggregateFlamegraphQuery({
  97. query: props.query,
  98. });
  99. const [frameFilter, setFrameFilter] = useLocalStorageState<
  100. 'system' | 'application' | 'all'
  101. >('flamegraph-frame-filter', 'application');
  102. const onFrameFilterChange = useCallback(
  103. (value: 'system' | 'application' | 'all') => {
  104. setFrameFilter(value);
  105. },
  106. [setFrameFilter]
  107. );
  108. const onResetFrameFilter = useCallback(() => {
  109. setFrameFilter('all');
  110. }, [setFrameFilter]);
  111. const flamegraphFrameFilter: ((frame: Frame) => boolean) | undefined = useMemo(() => {
  112. if (frameFilter === 'all') {
  113. return () => true;
  114. }
  115. if (frameFilter === 'application') {
  116. return frame => frame.is_application;
  117. }
  118. return frame => !frame.is_application;
  119. }, [frameFilter]);
  120. const [visualization, setVisualization] = useLocalStorageState<
  121. 'flamegraph' | 'call tree'
  122. >('flamegraph-visualization', 'flamegraph');
  123. const onVisualizationChange = useCallback(
  124. (value: 'flamegraph' | 'call tree') => {
  125. setVisualization(value);
  126. },
  127. [setVisualization]
  128. );
  129. const canvasPoolManager = useMemo(() => new CanvasPoolManager(), []);
  130. const scheduler = useCanvasScheduler(canvasPoolManager);
  131. return (
  132. <ProfileVisualizationContainer>
  133. <ProfileGroupProvider
  134. traceID=""
  135. type="flamegraph"
  136. input={data ?? null}
  137. frameFilter={flamegraphFrameFilter}
  138. >
  139. <FlamegraphStateProvider initialState={DEFAULT_FLAMEGRAPH_PREFERENCES}>
  140. <FlamegraphThemeProvider>
  141. <FlamegraphProvider>
  142. <AggregateFlamegraphToolbar
  143. scheduler={scheduler}
  144. canvasPoolManager={canvasPoolManager}
  145. visualization={visualization}
  146. onVisualizationChange={onVisualizationChange}
  147. frameFilter={frameFilter}
  148. onFrameFilterChange={onFrameFilterChange}
  149. hideSystemFrames={false}
  150. setHideSystemFrames={noop}
  151. />
  152. <FlamegraphContainer>
  153. {visualization === 'flamegraph' ? (
  154. <AggregateFlamegraph
  155. status={status}
  156. filter={frameFilter}
  157. onResetFilter={onResetFrameFilter}
  158. canvasPoolManager={canvasPoolManager}
  159. scheduler={scheduler}
  160. />
  161. ) : (
  162. <AggregateFlamegraphTreeTable
  163. recursion={null}
  164. expanded={false}
  165. frameFilter={frameFilter}
  166. canvasPoolManager={canvasPoolManager}
  167. withoutBorders
  168. />
  169. )}
  170. </FlamegraphContainer>
  171. {status === 'pending' ? (
  172. <RequestStateMessageContainer>
  173. <LoadingIndicator />
  174. </RequestStateMessageContainer>
  175. ) : status === 'error' ? (
  176. <RequestStateMessageContainer>
  177. {t('There was an error loading the flamegraph.')}
  178. </RequestStateMessageContainer>
  179. ) : isEmpty(data) ? (
  180. <RequestStateMessageContainer>
  181. {t('No profiling data found')}
  182. </RequestStateMessageContainer>
  183. ) : null}
  184. </FlamegraphProvider>
  185. </FlamegraphThemeProvider>
  186. </FlamegraphStateProvider>
  187. </ProfileGroupProvider>
  188. </ProfileVisualizationContainer>
  189. );
  190. }
  191. interface AggregateFlamegraphToolbarProps {
  192. canvasPoolManager: CanvasPoolManager;
  193. frameFilter: 'system' | 'application' | 'all';
  194. hideSystemFrames: boolean;
  195. onFrameFilterChange: (value: 'system' | 'application' | 'all') => void;
  196. onVisualizationChange: (value: 'flamegraph' | 'call tree') => void;
  197. scheduler: CanvasScheduler;
  198. setHideSystemFrames: (value: boolean) => void;
  199. visualization: 'flamegraph' | 'call tree';
  200. }
  201. function AggregateFlamegraphToolbar(props: AggregateFlamegraphToolbarProps) {
  202. const flamegraph = useFlamegraph();
  203. const flamegraphs = useMemo(() => [flamegraph], [flamegraph]);
  204. const spans = useMemo(() => [], []);
  205. const frameSelectOptions: SelectOption<'system' | 'application' | 'all'>[] =
  206. useMemo(() => {
  207. return [
  208. {value: 'system', label: t('System Frames')},
  209. {value: 'application', label: t('Application Frames')},
  210. {value: 'all', label: t('All Frames')},
  211. ];
  212. }, []);
  213. const onResetZoom = useCallback(() => {
  214. props.scheduler.dispatch('reset zoom');
  215. }, [props.scheduler]);
  216. const onFrameFilterChange = useCallback(
  217. (value: {value: 'application' | 'system' | 'all'}) => {
  218. props.onFrameFilterChange(value.value);
  219. },
  220. [props]
  221. );
  222. return (
  223. <AggregateFlamegraphToolbarContainer>
  224. <ViewSelectContainer>
  225. <SegmentedControl
  226. aria-label={t('View')}
  227. size="xs"
  228. value={props.visualization}
  229. onChange={props.onVisualizationChange}
  230. >
  231. <SegmentedControl.Item key="flamegraph">
  232. {t('Flamegraph')}
  233. </SegmentedControl.Item>
  234. <SegmentedControl.Item key="call tree">{t('Call Tree')}</SegmentedControl.Item>
  235. </SegmentedControl>
  236. </ViewSelectContainer>
  237. <AggregateFlamegraphSearch
  238. spans={spans}
  239. canvasPoolManager={props.canvasPoolManager}
  240. flamegraphs={flamegraphs}
  241. />
  242. <Button size="xs" onClick={onResetZoom}>
  243. {t('Reset Zoom')}
  244. </Button>
  245. <CompactSelect
  246. onChange={onFrameFilterChange}
  247. value={props.frameFilter}
  248. size="xs"
  249. options={frameSelectOptions}
  250. />
  251. </AggregateFlamegraphToolbarContainer>
  252. );
  253. }
  254. const PERCENTILE_DIGESTS = [
  255. 'p50()',
  256. 'p75()',
  257. 'p95()',
  258. 'p99()',
  259. ] satisfies ProfilingFieldType[];
  260. const ALL_DIGESTS = [
  261. ...PERCENTILE_DIGESTS,
  262. 'last_seen()',
  263. 'count()',
  264. ] satisfies ProfilingFieldType[];
  265. function ProfileDigest({query}: TransactionProfilesContentProps) {
  266. const profilesSummary = useProfileEvents<ProfilingFieldType>({
  267. fields: ALL_DIGESTS,
  268. query,
  269. sort: {key: 'last_seen()', order: 'desc'},
  270. referrer: 'api.profiling.profile-summary-table',
  271. });
  272. const digestData = profilesSummary.data?.data?.[0];
  273. return (
  274. <ProfileDigestContainer>
  275. <ProfileDigestLabel>{t('Last Seen')}</ProfileDigestLabel>
  276. <ProfileDigestValue align="right">
  277. {profilesSummary.isPending ? (
  278. ''
  279. ) : profilesSummary.isError ? (
  280. ''
  281. ) : (
  282. <DateTime date={new Date(digestData?.['last_seen()'] as string)} />
  283. )}
  284. </ProfileDigestValue>
  285. <ProfileDigestLabel>{t('Count')}</ProfileDigestLabel>
  286. <ProfileDigestValue align="right">
  287. {profilesSummary.isPending ? (
  288. ''
  289. ) : profilesSummary.isError ? (
  290. ''
  291. ) : (
  292. <Count value={digestData?.['count()'] as number} />
  293. )}
  294. </ProfileDigestValue>
  295. {PERCENTILE_DIGESTS.map(percentile => (
  296. <Fragment key={percentile}>
  297. <ProfileDigestLabel>
  298. {percentile.substring(0, percentile.length - 2)}
  299. </ProfileDigestLabel>
  300. <ProfileDigestValue align="right">
  301. {profilesSummary.isPending ? (
  302. ''
  303. ) : profilesSummary.isError ? (
  304. ''
  305. ) : (
  306. <PerformanceDuration
  307. milliseconds={digestData?.[percentile] as number}
  308. abbreviation
  309. />
  310. )}
  311. </ProfileDigestValue>
  312. </Fragment>
  313. ))}
  314. </ProfileDigestContainer>
  315. );
  316. }
  317. const ALLOWED_SORTS = [
  318. '-timestamp',
  319. 'timestamp',
  320. '-transaction.duration',
  321. 'transaction.duration',
  322. ] as const;
  323. type SortOption = (typeof ALLOWED_SORTS)[number];
  324. const sortOptions: SelectOption<SortOption>[] = [
  325. {value: '-timestamp', label: t('Newest Events')},
  326. {value: 'timestamp', label: t('Oldest Events')},
  327. {value: '-transaction.duration', label: t('Slowest Events')},
  328. {value: 'transaction.duration', label: t('Fastest Events')},
  329. ];
  330. const PROFILES_SORT = 'profilesSort';
  331. const PROFILES_CURSOR = 'profilesCursor';
  332. function ProfileList({query: userQuery, transaction}: TransactionProfilesContentProps) {
  333. const location = useLocation();
  334. const organization = useOrganization();
  335. const sortValue = useMemo(() => {
  336. const rawSort = decodeScalar(location.query[PROFILES_SORT]);
  337. if (ALLOWED_SORTS.includes(rawSort as any)) {
  338. return rawSort as SortOption;
  339. }
  340. return '-timestamp' as const;
  341. }, [location.query]);
  342. const sort = useMemo(() => {
  343. if (sortValue === '-timestamp') {
  344. return {key: 'timestamp', order: 'desc'} as const;
  345. }
  346. if (sortValue === 'timestamp') {
  347. return {key: 'timestamp', order: 'asc'} as const;
  348. }
  349. if (sortValue === '-transaction.duration') {
  350. return {key: 'transaction.duration', order: 'desc'} as const;
  351. }
  352. if (sortValue === 'transaction.duration') {
  353. return {key: 'transaction.duration', order: 'asc'} as const;
  354. }
  355. throw new Error(`Unsupport sort: ${sortValue}`);
  356. }, [sortValue]);
  357. const cursor = useMemo(
  358. () => decodeScalar(location.query[PROFILES_CURSOR]),
  359. [location.query]
  360. );
  361. const profilesList = useProfileEvents<ProfilingFieldType>({
  362. fields: [
  363. 'id',
  364. 'project.name',
  365. 'trace',
  366. 'transaction.duration',
  367. 'profile.id',
  368. 'profiler.id',
  369. 'thread.id',
  370. 'precise.start_ts',
  371. 'precise.finish_ts',
  372. 'timestamp',
  373. ],
  374. query: userQuery,
  375. sort,
  376. referrer: 'api.profiling.profile-summary-table',
  377. cursor,
  378. limit: 10,
  379. });
  380. const handleSort = useCallback(
  381. (value: {value: SortOption}) => {
  382. browserHistory.push({
  383. ...location,
  384. query: {
  385. ...location.query,
  386. [PROFILES_SORT]: value.value,
  387. [PROFILES_CURSOR]: undefined,
  388. },
  389. });
  390. },
  391. [location]
  392. );
  393. const handleCursor = useCallback((newCursor, pathname, query) => {
  394. browserHistory.push({
  395. pathname,
  396. query: {...query, [PROFILES_CURSOR]: newCursor},
  397. });
  398. }, []);
  399. return (
  400. <ProfileListContainer>
  401. <ProfileListControls>
  402. <CompactSelect
  403. onChange={handleSort}
  404. value={sortValue}
  405. size="xs"
  406. options={sortOptions}
  407. />
  408. <StyledPagination
  409. pageLinks={profilesList.getResponseHeader?.('Link')}
  410. onCursor={handleCursor}
  411. size="xs"
  412. />
  413. </ProfileListControls>
  414. {profilesList.isPending ? (
  415. <LoadingIndicator />
  416. ) : profilesList.isError ? (
  417. <ErrorPanel>
  418. <IconWarning color="gray300" size="lg" />
  419. </ErrorPanel>
  420. ) : (
  421. <ProfileListResultsContainer>
  422. <ProfileDigestLabel>{t('Event ID')}</ProfileDigestLabel>
  423. <ProfileDigestLabel align="right">{t('Duration')}</ProfileDigestLabel>
  424. <ProfileDigestLabel align="right">{t('Profile')}</ProfileDigestLabel>
  425. {profilesList.data?.data?.map(row => {
  426. const traceTarget = generateLinkToEventInTraceView({
  427. eventId: row.id as string,
  428. timestamp: row.timestamp as string,
  429. traceSlug: row.trace as string,
  430. projectSlug: row['project.name'] as string,
  431. location,
  432. organization,
  433. transactionName: transaction,
  434. source: TraceViewSources.PERFORMANCE_TRANSACTION_SUMMARY_PROFILES,
  435. });
  436. const profileTarget = generateProfileLink()(
  437. organization,
  438. {
  439. id: row.id as string,
  440. 'project.name': row['project.name'] as string,
  441. 'profile.id': (row['profile.id'] as string) || '',
  442. 'profiler.id': (row['profiler.id'] as string) || '',
  443. 'thread.id': (row['thread.id'] as string) || '',
  444. 'precise.start_ts': row['precise.start_ts'] as number,
  445. 'precise.finish_ts': row['precise.finish_ts'] as number,
  446. trace: row.trace as string,
  447. },
  448. location
  449. );
  450. return (
  451. <Fragment key={row.id as string}>
  452. <ProfileDigestValue align="left">
  453. <Link to={traceTarget}>{getShortEventId(row.id as string)}</Link>
  454. </ProfileDigestValue>
  455. <ProfileDigestValue align="right">
  456. <PerformanceDuration
  457. milliseconds={(row?.['transaction.duration'] as number) ?? 0}
  458. abbreviation
  459. />
  460. </ProfileDigestValue>
  461. <ProfileDigestValue align="right">
  462. <LinkButton
  463. disabled={!profileTarget || isEmptyObject(profileTarget)}
  464. to={profileTarget || {}}
  465. onClick={() => {
  466. trackAnalytics('profiling_views.go_to_flamegraph', {
  467. organization,
  468. source: 'profiling_transaction.profiles_table',
  469. });
  470. }}
  471. size="xs"
  472. >
  473. <IconProfiling size="xs" />
  474. </LinkButton>
  475. </ProfileDigestValue>
  476. </Fragment>
  477. );
  478. })}
  479. </ProfileListResultsContainer>
  480. )}
  481. </ProfileListContainer>
  482. );
  483. }
  484. const TransactionProfilesContentContainer = styled('div')`
  485. display: grid;
  486. /* false positive for grid layout */
  487. /* stylelint-disable */
  488. grid-template-areas: 'visualization digest';
  489. grid-template-columns: 1fr 250px;
  490. flex: 1;
  491. border: 1px solid ${p => p.theme.border};
  492. border-radius: ${p => p.theme.borderRadius};
  493. overflow: hidden;
  494. `;
  495. const ProfileVisualizationContainer = styled('div')`
  496. grid-area: visualization;
  497. display: grid;
  498. grid-template-rows: min-content 1fr;
  499. height: 100%;
  500. position: relative;
  501. `;
  502. const FlamegraphContainer = styled('div')`
  503. overflow: hidden;
  504. display: flex;
  505. `;
  506. const RequestStateMessageContainer = styled('div')`
  507. position: absolute;
  508. left: 0;
  509. right: 0;
  510. top: 0;
  511. bottom: 0;
  512. display: flex;
  513. justify-content: center;
  514. align-items: center;
  515. color: ${p => p.theme.subText};
  516. pointer-events: none;
  517. `;
  518. const AggregateFlamegraphToolbarContainer = styled('div')`
  519. display: flex;
  520. justify-content: space-between;
  521. gap: ${space(1)};
  522. padding: ${space(1)};
  523. background-color: ${p => p.theme.background};
  524. /*
  525. force height to be the same as profile digest header,
  526. but subtract 1px for the border that doesnt exist on the header
  527. */
  528. height: 41px;
  529. border-bottom: 1px solid ${p => p.theme.border};
  530. `;
  531. const ViewSelectContainer = styled('div')`
  532. min-width: 160px;
  533. `;
  534. const AggregateFlamegraphSearch = styled(FlamegraphSearch)`
  535. max-width: 300px;
  536. `;
  537. const ProfileSidebarContainer = styled('div')`
  538. grid-area: digest;
  539. border-left: 1px solid ${p => p.theme.border};
  540. background-color: ${p => p.theme.background};
  541. position: relative;
  542. overflow: hidden;
  543. display: grid;
  544. grid-template-rows: min-content 1fr;
  545. `;
  546. const ProfileDigestContainer = styled('div')`
  547. display: grid;
  548. grid-template-columns: min-content 1fr;
  549. padding: ${space(2)};
  550. gap: ${space(1)};
  551. `;
  552. const ProfileListContainer = styled('div')`
  553. padding: ${space(2)};
  554. border-top: 1px solid ${p => p.theme.border};
  555. `;
  556. const ProfileListControls = styled('div')`
  557. display: flex;
  558. justify-content: space-between;
  559. margin-bottom: ${space(2)};
  560. `;
  561. const StyledPagination = styled(Pagination)`
  562. margin: 0;
  563. `;
  564. const ProfileListResultsContainer = styled('div')`
  565. display: grid;
  566. grid-template-columns: min-content 1fr min-content;
  567. gap: ${space(1)};
  568. `;
  569. const ProfileDigestLabel = styled(SectionHeading)<{align?: 'left' | 'right'}>`
  570. margin: 0;
  571. text-transform: uppercase;
  572. text-wrap: nowrap;
  573. text-align: ${p => p.align ?? 'left'};
  574. `;
  575. const ProfileDigestValue = styled('div')<{align: 'left' | 'right'}>`
  576. text-align: ${p => p.align};
  577. `;