transactionBar.tsx 20 KB

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