transactionBar.tsx 20 KB

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