traceViewDetailPanel.tsx 19 KB

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