traceViewDetailPanel.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612
  1. import {createRef, Fragment, useEffect, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import omit from 'lodash/omit';
  5. import Alert from 'sentry/components/alert';
  6. import {LinkButton} from 'sentry/components/button';
  7. import {CopyToClipboardButton} from 'sentry/components/copyToClipboardButton';
  8. import {DateTime} from 'sentry/components/dateTime';
  9. import {EventAttachments} from 'sentry/components/events/eventAttachments';
  10. import {
  11. isNotMarkMeasurement,
  12. isNotPerformanceScoreMeasurement,
  13. TraceEventCustomPerformanceMetric,
  14. } from 'sentry/components/events/eventCustomPerformanceMetrics';
  15. import {Entries} from 'sentry/components/events/eventEntries';
  16. import {EventEvidence} from 'sentry/components/events/eventEvidence';
  17. import {EventExtraData} from 'sentry/components/events/eventExtraData';
  18. import {EventSdk} from 'sentry/components/events/eventSdk';
  19. import {EventViewHierarchy} from 'sentry/components/events/eventViewHierarchy';
  20. import {Breadcrumbs} from 'sentry/components/events/interfaces/breadcrumbs';
  21. import type {SpanDetailProps} from 'sentry/components/events/interfaces/spans/newTraceDetailsSpanDetails';
  22. import NewTraceDetailsSpanDetail, {
  23. SpanDetailContainer,
  24. SpanDetails,
  25. } from 'sentry/components/events/interfaces/spans/newTraceDetailsSpanDetails';
  26. import {
  27. getFormattedTimeRangeWithLeadingAndTrailingZero,
  28. getSpanOperation,
  29. } from 'sentry/components/events/interfaces/spans/utils';
  30. import {generateStats} from 'sentry/components/events/opsBreakdown';
  31. import {EventRRWebIntegration} from 'sentry/components/events/rrwebIntegration';
  32. import {DataSection} from 'sentry/components/events/styles';
  33. import FileSize from 'sentry/components/fileSize';
  34. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  35. import Link from 'sentry/components/links/link';
  36. import LoadingIndicator from 'sentry/components/loadingIndicator';
  37. import {CustomMetricsEventData} from 'sentry/components/metrics/customMetricsEventData';
  38. import {
  39. ErrorDot,
  40. ErrorLevel,
  41. ErrorMessageContent,
  42. ErrorMessageTitle,
  43. ErrorTitle,
  44. } from 'sentry/components/performance/waterfall/rowDetails';
  45. import PerformanceDuration from 'sentry/components/performanceDuration';
  46. import QuestionTooltip from 'sentry/components/questionTooltip';
  47. import {generateIssueEventTarget} from 'sentry/components/quickTrace/utils';
  48. import {Tooltip} from 'sentry/components/tooltip';
  49. import {PAGE_URL_PARAM} from 'sentry/constants/pageFilters';
  50. import {IconChevron, IconOpen} from 'sentry/icons';
  51. import {t, tn} from 'sentry/locale';
  52. import {space} from 'sentry/styles/space';
  53. import type {EntryBreadcrumbs, EventTransaction} from 'sentry/types/event';
  54. import {EntryType} from 'sentry/types/event';
  55. import type {Organization} from 'sentry/types/organization';
  56. import {trackAnalytics} from 'sentry/utils/analytics';
  57. import getDynamicText from 'sentry/utils/getDynamicText';
  58. import {PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  59. import {WEB_VITAL_DETAILS} from 'sentry/utils/performance/vitals/constants';
  60. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  61. import {useLocation} from 'sentry/utils/useLocation';
  62. import useOrganization from 'sentry/utils/useOrganization';
  63. import useProjects from 'sentry/utils/useProjects';
  64. import {isCustomMeasurement} from 'sentry/views/dashboards/utils';
  65. import DetailPanel from 'sentry/views/insights/common/components/detailPanel';
  66. import {ProfileGroupProvider} from 'sentry/views/profiling/profileGroupProvider';
  67. import {ProfileContext, ProfilesProvider} from 'sentry/views/profiling/profilesProvider';
  68. import {transactionSummaryRouteWithQuery} from '../transactionSummary/utils';
  69. import type {EventDetail} from './newTraceDetailsContent';
  70. import {Row, Tags} from './styles';
  71. type DetailPanelProps = {
  72. detail: EventDetail | SpanDetailProps | undefined;
  73. onClose: () => void;
  74. };
  75. type EventDetailProps = {
  76. detail: EventDetail;
  77. location: Location;
  78. organization: Organization;
  79. };
  80. function OpsBreakdown({event}: {event: EventTransaction}) {
  81. const [showingAll, setShowingAll] = useState(false);
  82. const breakdown = event && generateStats(event, {type: 'no_filter'});
  83. if (!breakdown) {
  84. return null;
  85. }
  86. const renderText = showingAll ? t('Show less') : t('Show more') + '...';
  87. return (
  88. breakdown && (
  89. <Row
  90. title={
  91. <FlexBox style={{gap: '5px'}}>
  92. {t('Ops Breakdown')}
  93. <QuestionTooltip
  94. title={t('Applicable to the children of this event only')}
  95. size="xs"
  96. />
  97. </FlexBox>
  98. }
  99. >
  100. <div style={{display: 'flex', flexDirection: 'column', gap: space(0.25)}}>
  101. {breakdown.slice(0, showingAll ? breakdown.length : 5).map(currOp => {
  102. const {name, percentage, totalInterval} = currOp;
  103. const operationName = typeof name === 'string' ? name : t('Other');
  104. const pctLabel = isFinite(percentage) ? Math.round(percentage * 100) : '∞';
  105. return (
  106. <div key={operationName}>
  107. {operationName}:{' '}
  108. <PerformanceDuration seconds={totalInterval} abbreviation /> ({pctLabel}%)
  109. </div>
  110. );
  111. })}
  112. {breakdown.length > 5 && (
  113. <a onClick={() => setShowingAll(prev => !prev)}>{renderText}</a>
  114. )}
  115. </div>
  116. </Row>
  117. )
  118. );
  119. }
  120. function BreadCrumbsSection({
  121. event,
  122. organization,
  123. }: {
  124. event: EventTransaction;
  125. organization: Organization;
  126. }) {
  127. const [showBreadCrumbs, setShowBreadCrumbs] = useState(false);
  128. const breadCrumbsContainerRef = createRef<HTMLDivElement>();
  129. useEffect(() => {
  130. setTimeout(() => {
  131. if (showBreadCrumbs) {
  132. breadCrumbsContainerRef.current?.scrollIntoView({
  133. behavior: 'smooth',
  134. block: 'end',
  135. });
  136. }
  137. }, 100);
  138. }, [showBreadCrumbs, breadCrumbsContainerRef]);
  139. const matchingEntry: EntryBreadcrumbs | undefined = event?.entries.find(
  140. (entry): entry is EntryBreadcrumbs => entry.type === EntryType.BREADCRUMBS
  141. );
  142. if (!matchingEntry) {
  143. return null;
  144. }
  145. const renderText = showBreadCrumbs ? t('Hide Breadcrumbs') : t('Show Breadcrumbs');
  146. const chevron = <IconChevron size="xs" direction={showBreadCrumbs ? 'up' : 'down'} />;
  147. return (
  148. <Fragment>
  149. <a
  150. style={{display: 'flex', alignItems: 'center', gap: space(0.5)}}
  151. onClick={() => {
  152. setShowBreadCrumbs(prev => !prev);
  153. }}
  154. >
  155. {renderText} {chevron}
  156. </a>
  157. <div ref={breadCrumbsContainerRef}>
  158. {showBreadCrumbs && (
  159. <Breadcrumbs
  160. hideTitle
  161. data={matchingEntry.data}
  162. event={event}
  163. organization={organization}
  164. />
  165. )}
  166. </div>
  167. </Fragment>
  168. );
  169. }
  170. function EventDetails({detail, organization, location}: EventDetailProps) {
  171. const {projects} = useProjects();
  172. if (!detail.event) {
  173. return <LoadingIndicator />;
  174. }
  175. const {projectSlug} = detail.event;
  176. const eventJsonUrl = `/api/0/projects/${organization.slug}/${detail.traceFullDetailedEvent.project_slug}/events/${detail.traceFullDetailedEvent.event_id}/json/`;
  177. const project = projects.find(proj => proj.slug === detail.event?.projectSlug);
  178. const {errors, performance_issues} = detail.traceFullDetailedEvent;
  179. const hasIssues = errors.length + performance_issues.length > 0;
  180. const startTimestamp = Math.min(
  181. detail.traceFullDetailedEvent.start_timestamp,
  182. detail.traceFullDetailedEvent.timestamp
  183. );
  184. const endTimestamp = Math.max(
  185. detail.traceFullDetailedEvent.start_timestamp,
  186. detail.traceFullDetailedEvent.timestamp
  187. );
  188. const {start: startTimeWithLeadingZero, end: endTimeWithLeadingZero} =
  189. getFormattedTimeRangeWithLeadingAndTrailingZero(startTimestamp, endTimestamp);
  190. const duration = (endTimestamp - startTimestamp) * 1000;
  191. const durationString = `${Number(duration.toFixed(3)).toLocaleString()}ms`;
  192. const measurementNames = Object.keys(detail.traceFullDetailedEvent.measurements ?? {})
  193. .filter(name => isCustomMeasurement(`measurements.${name}`))
  194. .filter(isNotMarkMeasurement)
  195. .filter(isNotPerformanceScoreMeasurement)
  196. .sort();
  197. const renderMeasurements = () => {
  198. if (!detail.event) {
  199. return null;
  200. }
  201. const {measurements} = detail.event;
  202. const measurementKeys = Object.keys(measurements ?? {})
  203. .filter(name => Boolean(WEB_VITAL_DETAILS[`measurements.${name}`]))
  204. .sort();
  205. if (!measurements || measurementKeys.length <= 0) {
  206. return null;
  207. }
  208. return (
  209. <Fragment>
  210. {measurementKeys.map(measurement => (
  211. <Row
  212. key={measurement}
  213. title={WEB_VITAL_DETAILS[`measurements.${measurement}`]?.name}
  214. >
  215. <PerformanceDuration
  216. milliseconds={Number(measurements[measurement].value.toFixed(3))}
  217. abbreviation
  218. />
  219. </Row>
  220. ))}
  221. </Fragment>
  222. );
  223. };
  224. const renderGoToProfileButton = () => {
  225. if (!detail.traceFullDetailedEvent.profile_id) {
  226. return null;
  227. }
  228. const target = generateProfileFlamechartRoute({
  229. orgSlug: organization.slug,
  230. projectSlug: detail.traceFullDetailedEvent.project_slug,
  231. profileId: detail.traceFullDetailedEvent.profile_id,
  232. });
  233. function handleOnClick() {
  234. trackAnalytics('profiling_views.go_to_flamegraph', {
  235. organization,
  236. source: 'performance.trace_view',
  237. });
  238. }
  239. return (
  240. <StyledButton size="xs" to={target} onClick={handleOnClick}>
  241. {t('View Profile')}
  242. </StyledButton>
  243. );
  244. };
  245. return (
  246. <Wrapper>
  247. <Actions>
  248. <LinkButton
  249. size="sm"
  250. icon={<IconOpen />}
  251. href={eventJsonUrl}
  252. external
  253. onClick={() =>
  254. trackAnalytics('performance_views.event_details.json_button_click', {
  255. organization,
  256. })
  257. }
  258. >
  259. {t('JSON')} (<FileSize bytes={detail.event?.size} />)
  260. </LinkButton>
  261. </Actions>
  262. <Title>
  263. <Tooltip title={detail.traceFullDetailedEvent.project_slug}>
  264. <ProjectBadge
  265. project={
  266. project ? project : {slug: detail.traceFullDetailedEvent.project_slug}
  267. }
  268. avatarSize={50}
  269. hideName
  270. />
  271. </Tooltip>
  272. <div>
  273. <div>{t('Event')}</div>
  274. <TransactionOp>
  275. {' '}
  276. {detail.traceFullDetailedEvent['transaction.op']}
  277. </TransactionOp>
  278. </div>
  279. </Title>
  280. {hasIssues && (
  281. <Alert
  282. system
  283. defaultExpanded
  284. type="error"
  285. expand={[
  286. ...detail.traceFullDetailedEvent.errors,
  287. ...detail.traceFullDetailedEvent.performance_issues,
  288. ].map(error => (
  289. <ErrorMessageContent key={error.event_id}>
  290. <ErrorDot level={error.level} />
  291. <ErrorLevel>{error.level}</ErrorLevel>
  292. <ErrorTitle>
  293. <Link to={generateIssueEventTarget(error, organization)}>
  294. {error.title}
  295. </Link>
  296. </ErrorTitle>
  297. </ErrorMessageContent>
  298. ))}
  299. >
  300. <ErrorMessageTitle>
  301. {tn(
  302. '%s issue occurred in this transaction.',
  303. '%s issues occurred in this transaction.',
  304. detail.traceFullDetailedEvent.errors.length +
  305. detail.traceFullDetailedEvent.performance_issues.length
  306. )}
  307. </ErrorMessageTitle>
  308. </Alert>
  309. )}
  310. <StyledTable className="table key-value">
  311. <tbody>
  312. <Row title={<TransactionIdTitle>{t('Event ID')}</TransactionIdTitle>}>
  313. {detail.traceFullDetailedEvent.event_id}
  314. <CopyToClipboardButton
  315. borderless
  316. size="zero"
  317. iconSize="xs"
  318. text={`${window.location.href.replace(window.location.hash, '')}#txn-${
  319. detail.traceFullDetailedEvent.event_id
  320. }`}
  321. />
  322. </Row>
  323. <Row title={t('Description')}>
  324. <Link
  325. to={transactionSummaryRouteWithQuery({
  326. orgSlug: organization.slug,
  327. transaction: detail.traceFullDetailedEvent.transaction,
  328. query: omit(location.query, Object.values(PAGE_URL_PARAM)),
  329. projectID: String(detail.traceFullDetailedEvent.project_id),
  330. })}
  331. >
  332. {detail.traceFullDetailedEvent.transaction}
  333. </Link>
  334. </Row>
  335. {detail.traceFullDetailedEvent.profile_id && (
  336. <Row title="Profile ID" extra={renderGoToProfileButton()}>
  337. {detail.traceFullDetailedEvent.profile_id}
  338. </Row>
  339. )}
  340. <Row title="Duration">{durationString}</Row>
  341. <Row title="Date Range">
  342. {getDynamicText({
  343. fixed: 'Mar 19, 2021 11:06:27 AM UTC',
  344. value: (
  345. <Fragment>
  346. <DateTime date={startTimestamp * 1000} />
  347. {` (${startTimeWithLeadingZero})`}
  348. </Fragment>
  349. ),
  350. })}
  351. <br />
  352. {getDynamicText({
  353. fixed: 'Mar 19, 2021 11:06:28 AM UTC',
  354. value: (
  355. <Fragment>
  356. <DateTime date={endTimestamp * 1000} />
  357. {` (${endTimeWithLeadingZero})`}
  358. </Fragment>
  359. ),
  360. })}
  361. </Row>
  362. <OpsBreakdown event={detail.event} />
  363. {renderMeasurements()}
  364. <Tags
  365. enableHiding
  366. location={location}
  367. organization={organization}
  368. tags={detail.traceFullDetailedEvent.tags ?? []}
  369. event={detail.traceFullDetailedEvent}
  370. />
  371. {measurementNames.length > 0 && (
  372. <tr>
  373. <td className="key">{t('Measurements')}</td>
  374. <td className="value">
  375. <Measurements>
  376. {measurementNames.map(name => {
  377. return (
  378. detail.event && (
  379. <TraceEventCustomPerformanceMetric
  380. key={name}
  381. event={detail.event}
  382. name={name}
  383. location={location}
  384. organization={organization}
  385. source={undefined}
  386. isHomepage={false}
  387. />
  388. )
  389. );
  390. })}
  391. </Measurements>
  392. </td>
  393. </tr>
  394. )}
  395. </tbody>
  396. </StyledTable>
  397. {project && <EventEvidence event={detail.event} project={project} />}
  398. {projectSlug && (
  399. <Entries
  400. definedEvent={detail.event}
  401. projectSlug={projectSlug}
  402. group={undefined}
  403. organization={organization}
  404. isShare={false}
  405. hideBeforeReplayEntries
  406. hideBreadCrumbs
  407. />
  408. )}
  409. <EventExtraData event={detail.event} />
  410. <EventSdk sdk={detail.event.sdk} meta={detail.event._meta?.sdk} />
  411. {detail.event._metrics_summary ? (
  412. <CustomMetricsEventData
  413. projectId={detail.event.projectID}
  414. metricsSummary={detail.event._metrics_summary}
  415. startTimestamp={detail.event.startTimestamp}
  416. />
  417. ) : null}
  418. <BreadCrumbsSection event={detail.event} organization={organization} />
  419. {project && (
  420. <EventAttachments event={detail.event} project={project} group={undefined} />
  421. )}
  422. {project && <EventViewHierarchy event={detail.event} project={project} />}
  423. {projectSlug && (
  424. <EventRRWebIntegration
  425. event={detail.event}
  426. orgId={organization.slug}
  427. projectSlug={projectSlug}
  428. />
  429. )}
  430. </Wrapper>
  431. );
  432. }
  433. function SpanDetailsBody({
  434. detail,
  435. organization,
  436. }: {
  437. detail: SpanDetailProps;
  438. organization: Organization;
  439. }) {
  440. const {projects} = useProjects();
  441. const project = projects.find(proj => proj.slug === detail.event?.projectSlug);
  442. const profileId = detail?.event?.contexts?.profile?.profile_id ?? null;
  443. return (
  444. <Wrapper>
  445. <Title>
  446. <Tooltip title={detail.event.projectSlug}>
  447. <ProjectBadge
  448. project={project ? project : {slug: detail.event.projectSlug || ''}}
  449. avatarSize={50}
  450. hideName
  451. />
  452. </Tooltip>
  453. <div>
  454. <div>{t('Span')}</div>
  455. <TransactionOp> {getSpanOperation(detail.node.value)}</TransactionOp>
  456. </div>
  457. </Title>
  458. {detail.event.projectSlug && (
  459. <ProfilesProvider
  460. orgSlug={organization.slug}
  461. projectSlug={detail.event.projectSlug}
  462. profileId={profileId || ''}
  463. >
  464. <ProfileContext.Consumer>
  465. {profiles => (
  466. <ProfileGroupProvider
  467. type="flamechart"
  468. input={profiles?.type === 'resolved' ? profiles.data : null}
  469. traceID={profileId || ''}
  470. >
  471. <NewTraceDetailsSpanDetail {...detail} />
  472. </ProfileGroupProvider>
  473. )}
  474. </ProfileContext.Consumer>
  475. </ProfilesProvider>
  476. )}
  477. </Wrapper>
  478. );
  479. }
  480. export function isEventDetail(
  481. detail: EventDetail | SpanDetailProps
  482. ): detail is EventDetail {
  483. return !('span' in detail);
  484. }
  485. function TraceViewDetailPanel({detail, onClose}: DetailPanelProps) {
  486. const organization = useOrganization();
  487. const location = useLocation();
  488. return (
  489. <PageAlertProvider>
  490. <DetailPanel
  491. detailKey={detail && detail.openPanel === 'open' ? 'open' : undefined}
  492. onClose={onClose}
  493. >
  494. {detail &&
  495. (isEventDetail(detail) ? (
  496. <EventDetails
  497. location={location}
  498. organization={organization}
  499. detail={detail}
  500. />
  501. ) : (
  502. <SpanDetailsBody organization={organization} detail={detail} />
  503. ))}
  504. </DetailPanel>
  505. </PageAlertProvider>
  506. );
  507. }
  508. const Wrapper = styled('div')`
  509. display: flex;
  510. flex-direction: column;
  511. gap: ${space(2)};
  512. ${DataSection} {
  513. padding: 0;
  514. }
  515. ${SpanDetails} {
  516. padding: 0;
  517. }
  518. ${SpanDetailContainer} {
  519. border-bottom: none;
  520. }
  521. `;
  522. const FlexBox = styled('div')`
  523. display: flex;
  524. align-items: center;
  525. `;
  526. const Actions = styled('div')`
  527. display: flex;
  528. align-items: center;
  529. justify-content: flex-end;
  530. `;
  531. const Title = styled(FlexBox)`
  532. gap: ${space(2)};
  533. `;
  534. const TransactionOp = styled('div')`
  535. font-size: 25px;
  536. font-weight: ${p => p.theme.fontWeightBold};
  537. max-width: 600px;
  538. ${p => p.theme.overflowEllipsis}
  539. `;
  540. const TransactionIdTitle = styled('a')`
  541. display: flex;
  542. color: ${p => p.theme.textColor};
  543. :hover {
  544. color: ${p => p.theme.textColor};
  545. }
  546. `;
  547. const Measurements = styled('div')`
  548. display: flex;
  549. flex-wrap: wrap;
  550. gap: ${space(1)};
  551. padding-top: 10px;
  552. `;
  553. const StyledButton = styled(LinkButton)`
  554. position: absolute;
  555. top: ${space(0.75)};
  556. right: ${space(0.5)};
  557. `;
  558. const StyledTable = styled('table')`
  559. margin-bottom: 0 !important;
  560. `;
  561. export default TraceViewDetailPanel;