traceViewDetailPanel.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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. {projectSlug && <EventAttachments event={detail.event} projectSlug={projectSlug} />}
  443. {project && <EventViewHierarchy event={detail.event} project={project} />}
  444. {projectSlug && (
  445. <EventRRWebIntegration
  446. event={detail.event}
  447. orgId={organization.slug}
  448. projectSlug={projectSlug}
  449. />
  450. )}
  451. </Wrapper>
  452. );
  453. }
  454. function SpanDetailsBody({
  455. detail,
  456. organization,
  457. }: {
  458. detail: SpanDetailProps;
  459. organization: Organization;
  460. }) {
  461. const {projects} = useProjects();
  462. const project = projects.find(proj => proj.slug === detail.event?.projectSlug);
  463. const profileId = detail?.event?.contexts?.profile?.profile_id ?? null;
  464. return (
  465. <Wrapper>
  466. <Title>
  467. <Tooltip title={detail.event.projectSlug}>
  468. <ProjectBadge
  469. project={project ? project : {slug: detail.event.projectSlug || ''}}
  470. avatarSize={50}
  471. hideName
  472. />
  473. </Tooltip>
  474. <div>
  475. <div>{t('Span')}</div>
  476. <TransactionOp> {getSpanOperation(detail.node.value)}</TransactionOp>
  477. </div>
  478. </Title>
  479. {detail.event.projectSlug && (
  480. <ProfilesProvider
  481. orgSlug={organization.slug}
  482. projectSlug={detail.event.projectSlug}
  483. profileId={profileId || ''}
  484. >
  485. <ProfileContext.Consumer>
  486. {profiles => (
  487. <ProfileGroupProvider
  488. type="flamechart"
  489. input={profiles?.type === 'resolved' ? profiles.data : null}
  490. traceID={profileId || ''}
  491. >
  492. <NewTraceDetailsSpanDetail {...detail} />
  493. </ProfileGroupProvider>
  494. )}
  495. </ProfileContext.Consumer>
  496. </ProfilesProvider>
  497. )}
  498. </Wrapper>
  499. );
  500. }
  501. export function isEventDetail(
  502. detail: EventDetail | SpanDetailProps
  503. ): detail is EventDetail {
  504. return !('span' in detail);
  505. }
  506. function TraceViewDetailPanel({detail, onClose}: DetailPanelProps) {
  507. const organization = useOrganization();
  508. const location = useLocation();
  509. return (
  510. <PageAlertProvider>
  511. <DetailPanel
  512. detailKey={detail && detail.openPanel === 'open' ? 'open' : undefined}
  513. onClose={onClose}
  514. >
  515. {detail &&
  516. (isEventDetail(detail) ? (
  517. <EventDetails
  518. location={location}
  519. organization={organization}
  520. detail={detail}
  521. />
  522. ) : (
  523. <SpanDetailsBody organization={organization} detail={detail} />
  524. ))}
  525. </DetailPanel>
  526. </PageAlertProvider>
  527. );
  528. }
  529. const Wrapper = styled('div')`
  530. display: flex;
  531. flex-direction: column;
  532. gap: ${space(2)};
  533. ${DataSection} {
  534. padding: 0;
  535. }
  536. ${SpanDetails} {
  537. padding: 0;
  538. }
  539. ${SpanDetailContainer} {
  540. border-bottom: none;
  541. }
  542. `;
  543. const FlexBox = styled('div')`
  544. display: flex;
  545. align-items: center;
  546. `;
  547. const Actions = styled('div')`
  548. display: flex;
  549. align-items: center;
  550. justify-content: flex-end;
  551. `;
  552. const Title = styled(FlexBox)`
  553. gap: ${space(2)};
  554. `;
  555. const TransactionOp = styled('div')`
  556. font-size: 25px;
  557. font-weight: ${p => p.theme.fontWeightBold};
  558. max-width: 600px;
  559. ${p => p.theme.overflowEllipsis}
  560. `;
  561. const TransactionIdTitle = styled('a')`
  562. display: flex;
  563. color: ${p => p.theme.textColor};
  564. :hover {
  565. color: ${p => p.theme.textColor};
  566. }
  567. `;
  568. const Measurements = styled('div')`
  569. display: flex;
  570. flex-wrap: wrap;
  571. gap: ${space(1)};
  572. padding-top: 10px;
  573. `;
  574. const StyledButton = styled(LinkButton)`
  575. position: absolute;
  576. top: ${space(0.75)};
  577. right: ${space(0.5)};
  578. `;
  579. const StyledTable = styled('table')`
  580. margin-bottom: 0 !important;
  581. `;
  582. export default TraceViewDetailPanel;