content.tsx 20 KB

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