traceViewDetailPanel.tsx 20 KB

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