transactionBar.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  1. import {createRef, Fragment, useCallback, useEffect, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Location} from 'history';
  5. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  6. import Count from 'sentry/components/count';
  7. import * as DividerHandlerManager from 'sentry/components/events/interfaces/spans/dividerHandlerManager';
  8. import * as ScrollbarManager from 'sentry/components/events/interfaces/spans/scrollbarManager';
  9. import {MeasurementMarker} from 'sentry/components/events/interfaces/spans/styles';
  10. import {
  11. getMeasurementBounds,
  12. SpanBoundsType,
  13. SpanGeneratedBoundsType,
  14. transactionTargetHash,
  15. VerticalMark,
  16. } from 'sentry/components/events/interfaces/spans/utils';
  17. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  18. import Link from 'sentry/components/links/link';
  19. import {ROW_HEIGHT, SpanBarType} from 'sentry/components/performance/waterfall/constants';
  20. import {
  21. Row,
  22. RowCell,
  23. RowCellContainer,
  24. RowReplayTimeIndicators,
  25. } from 'sentry/components/performance/waterfall/row';
  26. import {DurationPill, RowRectangle} from 'sentry/components/performance/waterfall/rowBar';
  27. import {
  28. DividerContainer,
  29. DividerLine,
  30. DividerLineGhostContainer,
  31. ErrorBadge,
  32. } from 'sentry/components/performance/waterfall/rowDivider';
  33. import {
  34. RowTitle,
  35. RowTitleContainer,
  36. RowTitleContent,
  37. } from 'sentry/components/performance/waterfall/rowTitle';
  38. import {
  39. ConnectorBar,
  40. TOGGLE_BORDER_BOX,
  41. TreeConnector,
  42. TreeToggle,
  43. TreeToggleContainer,
  44. TreeToggleIcon,
  45. } from 'sentry/components/performance/waterfall/treeConnector';
  46. import {
  47. getDurationDisplay,
  48. getHumanDuration,
  49. } from 'sentry/components/performance/waterfall/utils';
  50. import {generateIssueEventTarget} from 'sentry/components/quickTrace/utils';
  51. import {Tooltip} from 'sentry/components/tooltip';
  52. import {Organization} from 'sentry/types';
  53. import {defined} from 'sentry/utils';
  54. import toPercent from 'sentry/utils/number/toPercent';
  55. import {TraceError, TraceFullDetailed} from 'sentry/utils/performance/quickTrace/types';
  56. import {
  57. isTraceError,
  58. isTraceRoot,
  59. isTraceTransaction,
  60. } from 'sentry/utils/performance/quickTrace/utils';
  61. import Projects from 'sentry/utils/projects';
  62. import {ProjectBadgeContainer} from './styles';
  63. import TransactionDetail from './transactionDetail';
  64. import {TraceInfo, TraceRoot, TreeDepth} from './types';
  65. import {shortenErrorTitle} from './utils';
  66. const MARGIN_LEFT = 0;
  67. type Props = {
  68. addContentSpanBarRef: (instance: HTMLDivElement | null) => void;
  69. continuingDepths: TreeDepth[];
  70. generateBounds: (bounds: SpanBoundsType) => SpanGeneratedBoundsType;
  71. hasGuideAnchor: boolean;
  72. index: number;
  73. isExpanded: boolean;
  74. isLast: boolean;
  75. isOrphan: boolean;
  76. isVisible: boolean;
  77. location: Location;
  78. onWheel: (deltaX: number) => void;
  79. organization: Organization;
  80. removeContentSpanBarRef: (instance: HTMLDivElement | null) => void;
  81. toggleExpandedState: () => void;
  82. traceInfo: TraceInfo;
  83. transaction: TraceRoot | TraceFullDetailed | TraceError;
  84. barColor?: string;
  85. isOrphanError?: boolean;
  86. measurements?: Map<number, VerticalMark>;
  87. numOfOrphanErrors?: number;
  88. onlyOrphanErrors?: boolean;
  89. };
  90. function TransactionBar(props: Props) {
  91. const [showDetail, setShowDetail] = useState(false);
  92. const transactionRowDOMRef = createRef<HTMLDivElement>();
  93. const transactionTitleRef = createRef<HTMLDivElement>();
  94. let spanContentRef: HTMLDivElement | null = null;
  95. const handleWheel = useCallback(
  96. (event: WheelEvent) => {
  97. // https://stackoverflow.com/q/57358640
  98. // https://github.com/facebook/react/issues/14856
  99. if (Math.abs(event.deltaY) > Math.abs(event.deltaX)) {
  100. return;
  101. }
  102. event.preventDefault();
  103. event.stopPropagation();
  104. if (Math.abs(event.deltaY) === Math.abs(event.deltaX)) {
  105. return;
  106. }
  107. const {onWheel} = props;
  108. onWheel(event.deltaX);
  109. },
  110. [props]
  111. );
  112. const scrollIntoView = useCallback(() => {
  113. const element = transactionRowDOMRef.current;
  114. if (!element) {
  115. return;
  116. }
  117. const boundingRect = element.getBoundingClientRect();
  118. const offset = boundingRect.top + window.scrollY;
  119. setShowDetail(true);
  120. window.scrollTo(0, offset);
  121. }, [transactionRowDOMRef]);
  122. useEffect(() => {
  123. const {location, transaction} = props;
  124. const transactionTitleRefCurrentCopy = transactionTitleRef.current;
  125. if (
  126. 'event_id' in transaction &&
  127. transactionTargetHash(transaction.event_id) === location.hash
  128. ) {
  129. scrollIntoView();
  130. }
  131. if (transactionTitleRefCurrentCopy) {
  132. transactionTitleRefCurrentCopy.addEventListener('wheel', handleWheel, {
  133. passive: false,
  134. });
  135. }
  136. return () => {
  137. if (transactionTitleRefCurrentCopy) {
  138. transactionTitleRefCurrentCopy.removeEventListener('wheel', handleWheel);
  139. }
  140. };
  141. }, [handleWheel, props, scrollIntoView, transactionTitleRef]);
  142. const handleRowCellClick = () => {
  143. const {transaction, organization} = props;
  144. if (isTraceError(transaction)) {
  145. browserHistory.push(generateIssueEventTarget(transaction, organization));
  146. }
  147. if (isTraceTransaction<TraceFullDetailed>(transaction)) {
  148. setShowDetail(prev => !prev);
  149. }
  150. };
  151. const getCurrentOffset = () => {
  152. const {transaction} = props;
  153. const {generation} = transaction;
  154. return getOffset(generation);
  155. };
  156. const renderMeasurements = () => {
  157. const {measurements, generateBounds} = props;
  158. if (!measurements) {
  159. return null;
  160. }
  161. return (
  162. <Fragment>
  163. {Array.from(measurements.values()).map(verticalMark => {
  164. const mark = Object.values(verticalMark.marks)[0];
  165. const {timestamp} = mark;
  166. const bounds = getMeasurementBounds(timestamp, generateBounds);
  167. const shouldDisplay = defined(bounds.left) && defined(bounds.width);
  168. if (!shouldDisplay || !bounds.isSpanVisibleInView) {
  169. return null;
  170. }
  171. return (
  172. <MeasurementMarker
  173. key={String(timestamp)}
  174. style={{
  175. left: `clamp(0%, ${toPercent(bounds.left || 0)}, calc(100% - 1px))`,
  176. }}
  177. failedThreshold={verticalMark.failedThreshold}
  178. />
  179. );
  180. })}
  181. </Fragment>
  182. );
  183. };
  184. const renderConnector = (hasToggle: boolean) => {
  185. const {continuingDepths, isExpanded, isOrphan, isLast, transaction} = props;
  186. const {generation = 0} = transaction;
  187. const eventId =
  188. isTraceTransaction<TraceFullDetailed>(transaction) || isTraceError(transaction)
  189. ? transaction.event_id
  190. : transaction.traceSlug;
  191. if (generation === 0) {
  192. if (hasToggle) {
  193. return (
  194. <ConnectorBar
  195. style={{right: '15px', height: '10px', bottom: '-5px', top: 'auto'}}
  196. orphanBranch={false}
  197. />
  198. );
  199. }
  200. return null;
  201. }
  202. const connectorBars: Array<React.ReactNode> = continuingDepths.map(
  203. ({depth, isOrphanDepth}) => {
  204. if (generation - depth <= 1) {
  205. // If the difference is less than or equal to 1, then it means that the continued
  206. // bar is from its direct parent. In this case, do not render a connector bar
  207. // because the tree connector below will suffice.
  208. return null;
  209. }
  210. const left = -1 * getOffset(generation - depth - 1) - 2;
  211. return (
  212. <ConnectorBar
  213. style={{left}}
  214. key={`${eventId}-${depth}`}
  215. orphanBranch={isOrphanDepth}
  216. />
  217. );
  218. }
  219. );
  220. if (hasToggle && isExpanded) {
  221. connectorBars.push(
  222. <ConnectorBar
  223. style={{
  224. right: '15px',
  225. height: '10px',
  226. bottom: isLast ? `-${ROW_HEIGHT / 2 + 1}px` : '0',
  227. top: 'auto',
  228. }}
  229. key={`${eventId}-last`}
  230. orphanBranch={false}
  231. />
  232. );
  233. }
  234. return (
  235. <TreeConnector isLast={isLast} hasToggler={hasToggle} orphanBranch={isOrphan}>
  236. {connectorBars}
  237. </TreeConnector>
  238. );
  239. };
  240. const renderToggle = (errored: boolean) => {
  241. const {isExpanded, transaction, toggleExpandedState, numOfOrphanErrors} = props;
  242. const left = getCurrentOffset();
  243. const hasOrphanErrors = numOfOrphanErrors && numOfOrphanErrors > 0;
  244. const childrenLength =
  245. (!isTraceError(transaction) && transaction.children?.length) || 0;
  246. const generation = transaction.generation || 0;
  247. if (childrenLength <= 0 && !hasOrphanErrors) {
  248. return (
  249. <TreeToggleContainer style={{left: `${left}px`}}>
  250. {renderConnector(false)}
  251. </TreeToggleContainer>
  252. );
  253. }
  254. const isRoot = generation === 0;
  255. return (
  256. <TreeToggleContainer style={{left: `${left}px`}} hasToggler>
  257. {renderConnector(true)}
  258. <TreeToggle
  259. disabled={isRoot}
  260. isExpanded={isExpanded}
  261. errored={errored}
  262. onClick={event => {
  263. event.stopPropagation();
  264. if (isRoot) {
  265. return;
  266. }
  267. toggleExpandedState();
  268. }}
  269. >
  270. <Count value={childrenLength + (numOfOrphanErrors ?? 0)} />
  271. {!isRoot && (
  272. <div>
  273. <TreeToggleIcon direction={isExpanded ? 'up' : 'down'} />
  274. </div>
  275. )}
  276. </TreeToggle>
  277. </TreeToggleContainer>
  278. );
  279. };
  280. const renderTitle = (_: ScrollbarManager.ScrollbarManagerChildrenProps) => {
  281. const {organization, transaction, addContentSpanBarRef, removeContentSpanBarRef} =
  282. props;
  283. const left = getCurrentOffset();
  284. const errored = isTraceTransaction<TraceFullDetailed>(transaction)
  285. ? transaction.errors &&
  286. transaction.errors.length + transaction.performance_issues.length > 0
  287. : false;
  288. const projectBadge = (isTraceTransaction<TraceFullDetailed>(transaction) ||
  289. isTraceError(transaction)) && (
  290. <Projects orgId={organization.slug} slugs={[transaction.project_slug]}>
  291. {({projects}) => {
  292. const project = projects.find(p => p.slug === transaction.project_slug);
  293. return (
  294. <ProjectBadgeContainer>
  295. <Tooltip title={transaction.project_slug}>
  296. <ProjectBadge
  297. project={project ? project : {slug: transaction.project_slug}}
  298. avatarSize={16}
  299. hideName
  300. />
  301. </Tooltip>
  302. </ProjectBadgeContainer>
  303. );
  304. }}
  305. </Projects>
  306. );
  307. const content = isTraceError(transaction) ? (
  308. <Fragment>
  309. {projectBadge}
  310. <RowTitleContent errored>
  311. <ErrorLink to={generateIssueEventTarget(transaction, organization)}>
  312. <strong>{'Unknown \u2014 '}</strong>
  313. {shortenErrorTitle(transaction.title)}
  314. </ErrorLink>
  315. </RowTitleContent>
  316. </Fragment>
  317. ) : isTraceTransaction<TraceFullDetailed>(transaction) ? (
  318. <Fragment>
  319. {projectBadge}
  320. <RowTitleContent errored={errored}>
  321. <strong>
  322. {transaction['transaction.op']}
  323. {' \u2014 '}
  324. </strong>
  325. {transaction.transaction}
  326. </RowTitleContent>
  327. </Fragment>
  328. ) : (
  329. <RowTitleContent errored={false}>
  330. <strong>{'Trace \u2014 '}</strong>
  331. {transaction.traceSlug}
  332. </RowTitleContent>
  333. );
  334. return (
  335. <RowTitleContainer
  336. ref={ref => {
  337. if (!ref) {
  338. removeContentSpanBarRef(spanContentRef);
  339. return;
  340. }
  341. addContentSpanBarRef(ref);
  342. spanContentRef = ref;
  343. }}
  344. >
  345. {renderToggle(errored)}
  346. <RowTitle
  347. style={{
  348. left: `${left}px`,
  349. width: '100%',
  350. }}
  351. >
  352. {content}
  353. </RowTitle>
  354. </RowTitleContainer>
  355. );
  356. };
  357. const renderDivider = (
  358. dividerHandlerChildrenProps: DividerHandlerManager.DividerHandlerManagerChildrenProps
  359. ) => {
  360. if (showDetail) {
  361. // Mock component to preserve layout spacing
  362. return (
  363. <DividerLine
  364. showDetail
  365. style={{
  366. position: 'absolute',
  367. }}
  368. />
  369. );
  370. }
  371. const {addDividerLineRef} = dividerHandlerChildrenProps;
  372. return (
  373. <DividerLine
  374. ref={addDividerLineRef()}
  375. style={{
  376. position: 'absolute',
  377. }}
  378. onMouseEnter={() => {
  379. dividerHandlerChildrenProps.setHover(true);
  380. }}
  381. onMouseLeave={() => {
  382. dividerHandlerChildrenProps.setHover(false);
  383. }}
  384. onMouseOver={() => {
  385. dividerHandlerChildrenProps.setHover(true);
  386. }}
  387. onMouseDown={dividerHandlerChildrenProps.onDragStart}
  388. onClick={event => {
  389. // we prevent the propagation of the clicks from this component to prevent
  390. // the span detail from being opened.
  391. event.stopPropagation();
  392. }}
  393. />
  394. );
  395. };
  396. const renderGhostDivider = (
  397. dividerHandlerChildrenProps: DividerHandlerManager.DividerHandlerManagerChildrenProps
  398. ) => {
  399. const {dividerPosition, addGhostDividerLineRef} = dividerHandlerChildrenProps;
  400. return (
  401. <DividerLineGhostContainer
  402. style={{
  403. width: `calc(${toPercent(dividerPosition)} + 0.5px)`,
  404. display: 'none',
  405. }}
  406. >
  407. <DividerLine
  408. ref={addGhostDividerLineRef()}
  409. style={{
  410. right: 0,
  411. }}
  412. className="hovering"
  413. onClick={event => {
  414. // the ghost divider line should not be interactive.
  415. // we prevent the propagation of the clicks from this component to prevent
  416. // the span detail from being opened.
  417. event.stopPropagation();
  418. }}
  419. />
  420. </DividerLineGhostContainer>
  421. );
  422. };
  423. const renderErrorBadge = () => {
  424. const {transaction} = props;
  425. if (
  426. isTraceRoot(transaction) ||
  427. isTraceError(transaction) ||
  428. !(transaction.errors.length + transaction.performance_issues.length)
  429. ) {
  430. return null;
  431. }
  432. return <ErrorBadge />;
  433. };
  434. const renderRectangle = () => {
  435. const {transaction, traceInfo, barColor} = props;
  436. // Use 1 as the difference in the case that startTimestamp === endTimestamp
  437. const delta = Math.abs(traceInfo.endTimestamp - traceInfo.startTimestamp) || 1;
  438. const start_timestamp = isTraceError(transaction)
  439. ? transaction.timestamp
  440. : transaction.start_timestamp;
  441. if (!(start_timestamp && transaction.timestamp)) {
  442. return null;
  443. }
  444. const startPosition = Math.abs(start_timestamp - traceInfo.startTimestamp);
  445. const startPercentage = startPosition / delta;
  446. const duration = Math.abs(transaction.timestamp - start_timestamp);
  447. const widthPercentage = duration / delta;
  448. return (
  449. <StyledRowRectangle
  450. style={{
  451. backgroundColor: barColor,
  452. left: `min(${toPercent(startPercentage || 0)}, calc(100% - 1px))`,
  453. width: toPercent(widthPercentage || 0),
  454. }}
  455. >
  456. {renderPerformanceIssues()}
  457. {isTraceError(transaction) ? (
  458. <ErrorBadge />
  459. ) : (
  460. <Fragment>
  461. {renderErrorBadge()}
  462. <DurationPill
  463. durationDisplay={getDurationDisplay({
  464. left: startPercentage,
  465. width: widthPercentage,
  466. })}
  467. showDetail={showDetail}
  468. >
  469. {getHumanDuration(duration)}
  470. </DurationPill>
  471. </Fragment>
  472. )}
  473. </StyledRowRectangle>
  474. );
  475. };
  476. const renderPerformanceIssues = () => {
  477. const {transaction, barColor} = props;
  478. if (isTraceError(transaction) || isTraceRoot(transaction)) {
  479. return null;
  480. }
  481. const rows: React.ReactElement[] = [];
  482. // Use 1 as the difference in the case that startTimestamp === endTimestamp
  483. const delta = Math.abs(transaction.timestamp - transaction.start_timestamp) || 1;
  484. for (let i = 0; i < transaction.performance_issues.length; i++) {
  485. const issue = transaction.performance_issues[i];
  486. const startPosition = Math.abs(issue.start - transaction.start_timestamp);
  487. const startPercentage = startPosition / delta;
  488. const duration = Math.abs(issue.end - issue.start);
  489. const widthPercentage = duration / delta;
  490. rows.push(
  491. <RowRectangle
  492. style={{
  493. backgroundColor: barColor,
  494. left: `min(${toPercent(startPercentage || 0)}, calc(100% - 1px))`,
  495. width: toPercent(widthPercentage || 0),
  496. }}
  497. spanBarType={SpanBarType.AFFECTED}
  498. />
  499. );
  500. }
  501. return rows;
  502. };
  503. const renderHeader = ({
  504. dividerHandlerChildrenProps,
  505. scrollbarManagerChildrenProps,
  506. }: {
  507. dividerHandlerChildrenProps: DividerHandlerManager.DividerHandlerManagerChildrenProps;
  508. scrollbarManagerChildrenProps: ScrollbarManager.ScrollbarManagerChildrenProps;
  509. }) => {
  510. const {hasGuideAnchor, index, transaction, onlyOrphanErrors = false} = props;
  511. const {dividerPosition} = dividerHandlerChildrenProps;
  512. const hideDurationRectangle = isTraceRoot(transaction) && onlyOrphanErrors;
  513. return (
  514. <RowCellContainer showDetail={showDetail}>
  515. <RowCell
  516. data-test-id="transaction-row-title"
  517. data-type="span-row-cell"
  518. style={{
  519. width: `calc(${toPercent(dividerPosition)} - 0.5px)`,
  520. paddingTop: 0,
  521. }}
  522. showDetail={showDetail}
  523. onClick={handleRowCellClick}
  524. ref={transactionTitleRef}
  525. >
  526. <GuideAnchor target="trace_view_guide_row" disabled={!hasGuideAnchor}>
  527. {renderTitle(scrollbarManagerChildrenProps)}
  528. </GuideAnchor>
  529. </RowCell>
  530. <DividerContainer>{renderDivider(dividerHandlerChildrenProps)}</DividerContainer>
  531. <RowCell
  532. data-test-id="transaction-row-duration"
  533. data-type="span-row-cell"
  534. showStriping={index % 2 !== 0}
  535. style={{
  536. width: `calc(${toPercent(1 - dividerPosition)} - 0.5px)`,
  537. paddingTop: 0,
  538. overflow: 'visible',
  539. }}
  540. showDetail={showDetail}
  541. onClick={handleRowCellClick}
  542. >
  543. <RowReplayTimeIndicators />
  544. <GuideAnchor target="trace_view_guide_row_details" disabled={!hasGuideAnchor}>
  545. {!hideDurationRectangle && renderRectangle()}
  546. {renderMeasurements()}
  547. </GuideAnchor>
  548. </RowCell>
  549. {!showDetail && renderGhostDivider(dividerHandlerChildrenProps)}
  550. </RowCellContainer>
  551. );
  552. };
  553. const renderDetail = () => {
  554. const {location, organization, isVisible, transaction} = props;
  555. if (isTraceError(transaction) || isTraceRoot(transaction)) {
  556. return null;
  557. }
  558. if (!isVisible || !showDetail) {
  559. return null;
  560. }
  561. return (
  562. <TransactionDetail
  563. location={location}
  564. organization={organization}
  565. transaction={transaction}
  566. scrollIntoView={scrollIntoView}
  567. />
  568. );
  569. };
  570. const {isVisible, transaction} = props;
  571. return (
  572. <StyledRow
  573. ref={transactionRowDOMRef}
  574. visible={isVisible}
  575. showBorder={showDetail}
  576. cursor={isTraceTransaction<TraceFullDetailed>(transaction) ? 'pointer' : 'default'}
  577. >
  578. <ScrollbarManager.Consumer>
  579. {scrollbarManagerChildrenProps => (
  580. <DividerHandlerManager.Consumer>
  581. {dividerHandlerChildrenProps =>
  582. renderHeader({
  583. dividerHandlerChildrenProps,
  584. scrollbarManagerChildrenProps,
  585. })
  586. }
  587. </DividerHandlerManager.Consumer>
  588. )}
  589. </ScrollbarManager.Consumer>
  590. {renderDetail()}
  591. </StyledRow>
  592. );
  593. }
  594. function getOffset(generation) {
  595. return generation * (TOGGLE_BORDER_BOX / 2) + MARGIN_LEFT;
  596. }
  597. export default TransactionBar;
  598. const StyledRow = styled(Row)`
  599. &,
  600. ${RowCellContainer} {
  601. overflow: visible;
  602. }
  603. `;
  604. const ErrorLink = styled(Link)`
  605. color: ${p => p.theme.error};
  606. `;
  607. const StyledRowRectangle = styled(RowRectangle)`
  608. display: flex;
  609. align-items: center;
  610. `;