traceViewDetailPanel.tsx 20 KB

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