transaction.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578
  1. import {createRef, Fragment, useLayoutEffect, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import omit from 'lodash/omit';
  4. import {Button} from 'sentry/components/button';
  5. import {CopyToClipboardButton} from 'sentry/components/copyToClipboardButton';
  6. import {DateTime} from 'sentry/components/dateTime';
  7. import {Chunk} from 'sentry/components/events/contexts/chunk';
  8. import {EventAttachments} from 'sentry/components/events/eventAttachments';
  9. import {
  10. isNotMarkMeasurement,
  11. isNotPerformanceScoreMeasurement,
  12. TraceEventCustomPerformanceMetric,
  13. } from 'sentry/components/events/eventCustomPerformanceMetrics';
  14. import {Entries} from 'sentry/components/events/eventEntries';
  15. import {EventEvidence} from 'sentry/components/events/eventEvidence';
  16. import {EventExtraData} from 'sentry/components/events/eventExtraData';
  17. import {REPLAY_CLIP_OFFSETS} from 'sentry/components/events/eventReplay';
  18. import ReplayClipPreview from 'sentry/components/events/eventReplay/replayClipPreview';
  19. import {EventSdk} from 'sentry/components/events/eventSdk';
  20. import NewTagsUI from 'sentry/components/events/eventTagsAndScreenshot/tags';
  21. import {EventViewHierarchy} from 'sentry/components/events/eventViewHierarchy';
  22. import {Breadcrumbs} from 'sentry/components/events/interfaces/breadcrumbs';
  23. import {getFormattedTimeRangeWithLeadingAndTrailingZero} from 'sentry/components/events/interfaces/spans/utils';
  24. import {generateStats} from 'sentry/components/events/opsBreakdown';
  25. import {EventRRWebIntegration} from 'sentry/components/events/rrwebIntegration';
  26. import FileSize from 'sentry/components/fileSize';
  27. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  28. import {LazyRender, type LazyRenderProps} from 'sentry/components/lazyRender';
  29. import Link from 'sentry/components/links/link';
  30. import LoadingError from 'sentry/components/loadingError';
  31. import LoadingIndicator from 'sentry/components/loadingIndicator';
  32. import PerformanceDuration from 'sentry/components/performanceDuration';
  33. import QuestionTooltip from 'sentry/components/questionTooltip';
  34. import {Tooltip} from 'sentry/components/tooltip';
  35. import {PAGE_URL_PARAM} from 'sentry/constants/pageFilters';
  36. import {IconChevron, IconOpen} from 'sentry/icons';
  37. import {t} from 'sentry/locale';
  38. import {space} from 'sentry/styles/space';
  39. import {
  40. type EntryBreadcrumbs,
  41. EntryType,
  42. type EventTransaction,
  43. type Organization,
  44. } from 'sentry/types';
  45. import {objectIsEmpty} from 'sentry/utils';
  46. import {trackAnalytics} from 'sentry/utils/analytics';
  47. import {getAnalyticsDataForEvent} from 'sentry/utils/events';
  48. import getDynamicText from 'sentry/utils/getDynamicText';
  49. import {WEB_VITAL_DETAILS} from 'sentry/utils/performance/vitals/constants';
  50. import {generateProfileFlamechartRoute} from 'sentry/utils/profiling/routes';
  51. import {getReplayIdFromEvent} from 'sentry/utils/replays/getReplayIdFromEvent';
  52. import {useLocation} from 'sentry/utils/useLocation';
  53. import useProjects from 'sentry/utils/useProjects';
  54. import {isCustomMeasurement} from 'sentry/views/dashboards/utils';
  55. import {CustomMetricsEventData} from 'sentry/views/metrics/customMetricsEventData';
  56. import {useTransaction} from 'sentry/views/performance/newTraceDetails/traceApi/useTransaction';
  57. import type {TraceTreeNodeDetailsProps} from 'sentry/views/performance/newTraceDetails/traceDrawer/tabs/traceTreeNodeDetails';
  58. import type {
  59. TraceTree,
  60. TraceTreeNode,
  61. } from 'sentry/views/performance/newTraceDetails/traceModels/traceTree';
  62. import {getTraceTabTitle} from 'sentry/views/performance/newTraceDetails/traceState/traceTabs';
  63. import {Row, Tags} from 'sentry/views/performance/traceDetails/styles';
  64. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  65. import {useTraceAverageTransactionDuration} from '../../traceApi/useTraceAverageTransactionDuration';
  66. import {IssueList} from './issues/issues';
  67. import {TraceDrawerComponents} from './styles';
  68. function OpsBreakdown({event}: {event: EventTransaction}) {
  69. const [showingAll, setShowingAll] = useState(false);
  70. const breakdown = event && generateStats(event, {type: 'no_filter'});
  71. if (!breakdown) {
  72. return null;
  73. }
  74. const renderText = showingAll ? t('Show less') : t('Show more') + '...';
  75. return (
  76. breakdown && (
  77. <Row
  78. title={
  79. <TraceDrawerComponents.FlexBox style={{gap: '5px'}}>
  80. {t('Ops Breakdown')}
  81. <QuestionTooltip
  82. title={t('Applicable to the children of this event only')}
  83. size="xs"
  84. />
  85. </TraceDrawerComponents.FlexBox>
  86. }
  87. >
  88. <div style={{display: 'flex', flexDirection: 'column', gap: space(0.25)}}>
  89. {breakdown.slice(0, showingAll ? breakdown.length : 5).map(currOp => {
  90. const {name, percentage, totalInterval} = currOp;
  91. const operationName = typeof name === 'string' ? name : t('Other');
  92. const pctLabel = isFinite(percentage) ? Math.round(percentage * 100) : '∞';
  93. return (
  94. <div key={operationName}>
  95. {operationName}:{' '}
  96. <PerformanceDuration seconds={totalInterval} abbreviation /> ({pctLabel}%)
  97. </div>
  98. );
  99. })}
  100. {breakdown.length > 5 && (
  101. <a onClick={() => setShowingAll(prev => !prev)}>{renderText}</a>
  102. )}
  103. </div>
  104. </Row>
  105. )
  106. );
  107. }
  108. function BreadCrumbsSection({
  109. event,
  110. organization,
  111. }: {
  112. event: EventTransaction;
  113. organization: Organization;
  114. }) {
  115. const [showBreadCrumbs, setShowBreadCrumbs] = useState(false);
  116. const breadCrumbsContainerRef = createRef<HTMLDivElement>();
  117. useLayoutEffect(() => {
  118. setTimeout(() => {
  119. if (showBreadCrumbs) {
  120. breadCrumbsContainerRef.current?.scrollIntoView({
  121. behavior: 'smooth',
  122. block: 'end',
  123. });
  124. }
  125. }, 100);
  126. }, [showBreadCrumbs, breadCrumbsContainerRef]);
  127. const matchingEntry: EntryBreadcrumbs | undefined = event?.entries?.find(
  128. (entry): entry is EntryBreadcrumbs => entry.type === EntryType.BREADCRUMBS
  129. );
  130. if (!matchingEntry) {
  131. return null;
  132. }
  133. const renderText = showBreadCrumbs ? t('Hide Breadcrumbs') : t('Show Breadcrumbs');
  134. const chevron = <IconChevron size="xs" direction={showBreadCrumbs ? 'up' : 'down'} />;
  135. return (
  136. <Fragment>
  137. <a
  138. style={{display: 'flex', alignItems: 'center', gap: space(0.5)}}
  139. onClick={() => {
  140. setShowBreadCrumbs(prev => !prev);
  141. }}
  142. >
  143. {renderText} {chevron}
  144. </a>
  145. <div ref={breadCrumbsContainerRef}>
  146. {showBreadCrumbs && (
  147. <Breadcrumbs
  148. hideTitle
  149. data={matchingEntry.data}
  150. event={event}
  151. organization={organization}
  152. />
  153. )}
  154. </div>
  155. </Fragment>
  156. );
  157. }
  158. function ReplaySection({
  159. event,
  160. organization,
  161. }: {
  162. event: EventTransaction;
  163. organization: Organization;
  164. }) {
  165. const replayId = getReplayIdFromEvent(event);
  166. const startTimestampMS =
  167. event && 'startTimestamp' in event ? event.startTimestamp * 1000 : undefined;
  168. const timeOfEvent = event.dateCreated ?? startTimestampMS ?? event.dateReceived;
  169. const eventTimestampMs = timeOfEvent ? Math.floor(new Date(timeOfEvent).getTime()) : 0;
  170. return replayId ? (
  171. <ReplaySectionContainer>
  172. <ReplaySectionTitle>{t('Session Replay')}</ReplaySectionTitle>
  173. <ReplayClipPreview
  174. analyticsContext="trace-view"
  175. replaySlug={replayId}
  176. orgSlug={organization.slug}
  177. eventTimestampMs={eventTimestampMs}
  178. clipOffsets={REPLAY_CLIP_OFFSETS}
  179. fullReplayButtonProps={{
  180. analyticsEventKey: 'trace-view.drawer-open-replay-details-clicked',
  181. analyticsEventName: 'Trace View: Open Replay Details Clicked',
  182. analyticsParams: {
  183. ...getAnalyticsDataForEvent(event),
  184. organization,
  185. },
  186. }}
  187. />
  188. </ReplaySectionContainer>
  189. ) : null;
  190. }
  191. function AdditionalMobileEventContexts({event}: {event: EventTransaction}) {
  192. if (!event.contexts) {
  193. return null;
  194. }
  195. return (
  196. <Fragment>
  197. {Object.entries(omit(event.contexts ?? {}, ['feedback', 'response'])).map(
  198. ([key, value]) => {
  199. // Ignore profile as it's handled separately in the drawer.
  200. if (key === 'profile') {
  201. return null;
  202. }
  203. return (
  204. <Chunk
  205. key={key}
  206. type={value?.type ?? ''}
  207. alias={key}
  208. group={undefined}
  209. event={event}
  210. value={value}
  211. />
  212. );
  213. }
  214. )}
  215. </Fragment>
  216. );
  217. }
  218. const LAZY_RENDER_PROPS: Partial<LazyRenderProps> = {
  219. observerOptions: {rootMargin: '50px'},
  220. };
  221. export function TransactionNodeDetails({
  222. node,
  223. organization,
  224. onTabScrollToNode,
  225. onParentClick,
  226. }: TraceTreeNodeDetailsProps<TraceTreeNode<TraceTree.Transaction>>) {
  227. const location = useLocation();
  228. const {projects} = useProjects();
  229. const issues = useMemo(() => {
  230. return [...node.errors, ...node.performance_issues];
  231. }, [node.errors, node.performance_issues]);
  232. const {data: averageDurationQueryResult} = useTraceAverageTransactionDuration({
  233. node,
  234. location,
  235. organization,
  236. });
  237. const avgDurationInSeconds: number = useMemo(() => {
  238. return (
  239. Number(averageDurationQueryResult?.data?.[0]?.['avg(transaction.duration)']) / 1000
  240. );
  241. }, [averageDurationQueryResult]);
  242. const {
  243. data: event,
  244. isError,
  245. isLoading,
  246. } = useTransaction({
  247. node,
  248. organization,
  249. });
  250. if (isLoading) {
  251. return <LoadingIndicator />;
  252. }
  253. if (isError) {
  254. return <LoadingError message={t('Failed to fetch transaction details')} />;
  255. }
  256. const project = projects.find(proj => proj.slug === event?.projectSlug);
  257. const startTimestamp = Math.min(node.value.start_timestamp, node.value.timestamp);
  258. const endTimestamp = Math.max(node.value.start_timestamp, node.value.timestamp);
  259. const {start: startTimeWithLeadingZero, end: endTimeWithLeadingZero} =
  260. getFormattedTimeRangeWithLeadingAndTrailingZero(startTimestamp, endTimestamp);
  261. const durationInSeconds = endTimestamp - startTimestamp;
  262. const measurementNames = Object.keys(node.value.measurements ?? {})
  263. .filter(name => isCustomMeasurement(`measurements.${name}`))
  264. .filter(isNotMarkMeasurement)
  265. .filter(isNotPerformanceScoreMeasurement)
  266. .sort();
  267. const measurementKeys = Object.keys(event?.measurements ?? {})
  268. .filter(name => Boolean(WEB_VITAL_DETAILS[`measurements.${name}`]))
  269. .sort();
  270. const parentTransaction = node.parent_transaction;
  271. return (
  272. <TraceDrawerComponents.DetailContainer>
  273. <TraceDrawerComponents.HeaderContainer>
  274. <TraceDrawerComponents.Title>
  275. <Tooltip title={node.value.project_slug}>
  276. <ProjectBadge
  277. project={project ? project : {slug: node.value.project_slug}}
  278. avatarSize={30}
  279. hideName
  280. />
  281. </Tooltip>
  282. <TraceDrawerComponents.TitleText>
  283. <div>{t('transaction')}</div>
  284. <TraceDrawerComponents.TitleOp>
  285. {' '}
  286. {node.value['transaction.op'] + ' - ' + node.value.transaction}
  287. </TraceDrawerComponents.TitleOp>
  288. </TraceDrawerComponents.TitleText>
  289. </TraceDrawerComponents.Title>
  290. <TraceDrawerComponents.Actions>
  291. <Button size="xs" onClick={_e => onTabScrollToNode(node)}>
  292. {t('Show in view')}
  293. </Button>
  294. <TraceDrawerComponents.EventDetailsLink
  295. node={node}
  296. organization={organization}
  297. />
  298. <Button
  299. size="xs"
  300. icon={<IconOpen />}
  301. href={`/api/0/projects/${organization.slug}/${node.value.project_slug}/events/${node.value.event_id}/json/`}
  302. external
  303. >
  304. {t('JSON')} (<FileSize bytes={event?.size} />)
  305. </Button>
  306. </TraceDrawerComponents.Actions>
  307. </TraceDrawerComponents.HeaderContainer>
  308. <IssueList node={node} organization={organization} issues={issues} />
  309. <TraceDrawerComponents.Table className="table key-value">
  310. <tbody>
  311. <Row title="Duration">
  312. <TraceDrawerComponents.Duration
  313. duration={durationInSeconds}
  314. baseline={avgDurationInSeconds}
  315. baseDescription={
  316. 'Average duration for this transaction over the last 24 hours'
  317. }
  318. />
  319. </Row>
  320. {parentTransaction ? (
  321. <Row title="Parent Transaction">
  322. <td className="value">
  323. <a onClick={() => onParentClick(parentTransaction)}>
  324. {getTraceTabTitle(parentTransaction)}
  325. </a>
  326. </td>
  327. </Row>
  328. ) : null}
  329. <Row title={t('Event ID')}>
  330. {node.value.event_id}
  331. <CopyToClipboardButton
  332. borderless
  333. size="zero"
  334. iconSize="xs"
  335. text={node.value.event_id}
  336. />
  337. </Row>
  338. <Row title={t('Description')}>
  339. <Link
  340. to={transactionSummaryRouteWithQuery({
  341. orgSlug: organization.slug,
  342. transaction: node.value.transaction,
  343. query: omit(location.query, Object.values(PAGE_URL_PARAM)),
  344. projectID: String(node.value.project_id),
  345. })}
  346. >
  347. {node.value.transaction}
  348. </Link>
  349. </Row>
  350. {node.value.profile_id ? (
  351. <Row
  352. title="Profile ID"
  353. extra={
  354. <TraceDrawerComponents.Button
  355. size="xs"
  356. to={generateProfileFlamechartRoute({
  357. orgSlug: organization.slug,
  358. projectSlug: node.value.project_slug,
  359. profileId: node.value.profile_id,
  360. })}
  361. onClick={function handleOnClick() {
  362. trackAnalytics('profiling_views.go_to_flamegraph', {
  363. organization,
  364. source: 'performance.trace_view',
  365. });
  366. }}
  367. >
  368. {t('View Profile')}
  369. </TraceDrawerComponents.Button>
  370. }
  371. >
  372. {node.value.profile_id}
  373. </Row>
  374. ) : null}
  375. <Row title="Date Range">
  376. {getDynamicText({
  377. fixed: 'Mar 19, 2021 11:06:27 AM UTC',
  378. value: (
  379. <Fragment>
  380. <DateTime date={startTimestamp * node.multiplier} />
  381. {` (${startTimeWithLeadingZero})`}
  382. </Fragment>
  383. ),
  384. })}
  385. <br />
  386. {getDynamicText({
  387. fixed: 'Mar 19, 2021 11:06:28 AM UTC',
  388. value: (
  389. <Fragment>
  390. <DateTime date={endTimestamp * node.multiplier} />
  391. {` (${endTimeWithLeadingZero})`}
  392. </Fragment>
  393. ),
  394. })}
  395. </Row>
  396. <OpsBreakdown event={event} />
  397. {!event || !event.measurements || measurementKeys.length <= 0 ? null : (
  398. <Fragment>
  399. {measurementKeys.map(measurement => (
  400. <Row
  401. key={measurement}
  402. title={WEB_VITAL_DETAILS[`measurements.${measurement}`]?.name}
  403. >
  404. <PerformanceDuration
  405. milliseconds={Number(
  406. event.measurements?.[measurement].value.toFixed(3)
  407. )}
  408. abbreviation
  409. />
  410. </Row>
  411. ))}
  412. </Fragment>
  413. )}
  414. {measurementNames.length > 0 && (
  415. <tr>
  416. <td className="key">{t('Measurements')}</td>
  417. <td className="value">
  418. <Measurements>
  419. {measurementNames.map(name => {
  420. return (
  421. event && (
  422. <TraceEventCustomPerformanceMetric
  423. key={name}
  424. event={event}
  425. name={name}
  426. location={location}
  427. organization={organization}
  428. source={undefined}
  429. isHomepage={false}
  430. />
  431. )
  432. );
  433. })}
  434. </Measurements>
  435. </td>
  436. </tr>
  437. )}
  438. </tbody>
  439. </TraceDrawerComponents.Table>
  440. <LazyRender {...LAZY_RENDER_PROPS} containerHeight={200}>
  441. {organization.features.includes('event-tags-tree-ui') ? (
  442. <TagsWrapper>
  443. <NewTagsUI event={event} projectSlug={node.value.project_slug} />
  444. </TagsWrapper>
  445. ) : (
  446. <TraceDrawerComponents.Table className="table key-value">
  447. <tbody>
  448. <Tags
  449. enableHiding
  450. location={location}
  451. organization={organization}
  452. tags={event.tags}
  453. event={node.value}
  454. />
  455. </tbody>
  456. </TraceDrawerComponents.Table>
  457. )}
  458. </LazyRender>
  459. {project ? <EventEvidence event={event} project={project} /> : null}
  460. <LazyRender {...LAZY_RENDER_PROPS} containerHeight={480}>
  461. <ReplaySection event={event} organization={organization} />
  462. </LazyRender>
  463. {event.projectSlug ? (
  464. <Entries
  465. definedEvent={event}
  466. projectSlug={event.projectSlug}
  467. group={undefined}
  468. organization={organization}
  469. isShare
  470. hideBeforeReplayEntries
  471. hideBreadCrumbs
  472. />
  473. ) : null}
  474. {!objectIsEmpty(event.contexts?.feedback ?? {}) ? (
  475. <Chunk
  476. key="feedback"
  477. type="feedback"
  478. alias="feedback"
  479. group={undefined}
  480. event={event}
  481. value={event.contexts?.feedback ?? {}}
  482. />
  483. ) : null}
  484. {event.user && !objectIsEmpty(event.user) ? (
  485. <Chunk
  486. key="user"
  487. type="user"
  488. alias="user"
  489. group={undefined}
  490. event={event}
  491. value={event.user}
  492. />
  493. ) : null}
  494. <AdditionalMobileEventContexts event={event} />
  495. <EventExtraData event={event} />
  496. <EventSdk sdk={event.sdk} meta={event._meta?.sdk} />
  497. {event._metrics_summary ? (
  498. <CustomMetricsEventData
  499. metricsSummary={event._metrics_summary}
  500. startTimestamp={event.startTimestamp}
  501. />
  502. ) : null}
  503. <BreadCrumbsSection event={event} organization={organization} />
  504. {event.projectSlug ? (
  505. <EventAttachments event={event} projectSlug={event.projectSlug} />
  506. ) : null}
  507. {project ? <EventViewHierarchy event={event} project={project} /> : null}
  508. {event.projectSlug ? (
  509. <EventRRWebIntegration
  510. event={event}
  511. orgId={organization.slug}
  512. projectSlug={event.projectSlug}
  513. />
  514. ) : null}
  515. </TraceDrawerComponents.DetailContainer>
  516. );
  517. }
  518. const ReplaySectionContainer = styled('div')`
  519. display: flex;
  520. flex-direction: column;
  521. `;
  522. const ReplaySectionTitle = styled('div')`
  523. font-size: ${p => p.theme.fontSizeMedium};
  524. font-weight: 600;
  525. margin-bottom: ${space(2)};
  526. `;
  527. const Measurements = styled('div')`
  528. display: flex;
  529. flex-wrap: wrap;
  530. gap: ${space(1)};
  531. padding-top: 10px;
  532. `;
  533. const TagsWrapper = styled('div')`
  534. h3 {
  535. color: ${p => p.theme.textColor};
  536. }
  537. `;