transaction.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  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 {useApiQuery} from 'sentry/utils/queryClient';
  52. import {getReplayIdFromEvent} from 'sentry/utils/replays/getReplayIdFromEvent';
  53. import {useLocation} from 'sentry/utils/useLocation';
  54. import useProjects from 'sentry/utils/useProjects';
  55. import {isCustomMeasurement} from 'sentry/views/dashboards/utils';
  56. import {CustomMetricsEventData} from 'sentry/views/metrics/customMetricsEventData';
  57. import type {TraceTreeNodeDetailsProps} from 'sentry/views/performance/newTraceDetails/traceDrawer/tabs/traceTreeNodeDetails';
  58. import {getTraceTabTitle} from 'sentry/views/performance/newTraceDetails/traceTabs';
  59. import type {
  60. TraceTree,
  61. TraceTreeNode,
  62. } from 'sentry/views/performance/newTraceDetails/traceTree';
  63. import {Row, Tags} from 'sentry/views/performance/traceDetails/styles';
  64. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  65. import {useTraceAverageTransactionDuration} from '../../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. '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. const LAZY_RENDER_PROPS: Partial<LazyRenderProps> = {
  192. observerOptions: {rootMargin: '50px'},
  193. };
  194. export function TransactionNodeDetails({
  195. node,
  196. organization,
  197. scrollToNode,
  198. onParentClick,
  199. }: TraceTreeNodeDetailsProps<TraceTreeNode<TraceTree.Transaction>>) {
  200. const location = useLocation();
  201. const {projects} = useProjects();
  202. const issues = useMemo(() => {
  203. return [...node.errors, ...node.performance_issues];
  204. }, [node.errors, node.performance_issues]);
  205. const {data: averageDurationQueryResult} = useTraceAverageTransactionDuration({
  206. node,
  207. location,
  208. organization,
  209. });
  210. const avgDurationInSeconds: number = useMemo(() => {
  211. return (
  212. Number(averageDurationQueryResult?.data[0]?.['avg(transaction.duration)']) / 1000
  213. );
  214. }, [averageDurationQueryResult]);
  215. const {
  216. data: event,
  217. isError,
  218. isLoading,
  219. } = useApiQuery<EventTransaction>(
  220. [
  221. `/organizations/${organization.slug}/events/${node.value.project_slug}:${node.value.event_id}/`,
  222. {
  223. query: {
  224. referrer: 'trace-details-summary',
  225. },
  226. },
  227. ],
  228. {
  229. staleTime: 0,
  230. enabled: !!node,
  231. }
  232. );
  233. if (isLoading) {
  234. return <LoadingIndicator />;
  235. }
  236. if (isError) {
  237. return <LoadingError message={t('Failed to fetch transaction details')} />;
  238. }
  239. const project = projects.find(proj => proj.slug === event?.projectSlug);
  240. const startTimestamp = Math.min(node.value.start_timestamp, node.value.timestamp);
  241. const endTimestamp = Math.max(node.value.start_timestamp, node.value.timestamp);
  242. const {start: startTimeWithLeadingZero, end: endTimeWithLeadingZero} =
  243. getFormattedTimeRangeWithLeadingAndTrailingZero(startTimestamp, endTimestamp);
  244. const durationInSeconds = endTimestamp - startTimestamp;
  245. const measurementNames = Object.keys(node.value.measurements ?? {})
  246. .filter(name => isCustomMeasurement(`measurements.${name}`))
  247. .filter(isNotMarkMeasurement)
  248. .filter(isNotPerformanceScoreMeasurement)
  249. .sort();
  250. const measurementKeys = Object.keys(event?.measurements ?? {})
  251. .filter(name => Boolean(WEB_VITAL_DETAILS[`measurements.${name}`]))
  252. .sort();
  253. const parentTransaction = node.parent_transaction;
  254. return (
  255. <TraceDrawerComponents.DetailContainer>
  256. <TraceDrawerComponents.HeaderContainer>
  257. <TraceDrawerComponents.Title>
  258. <Tooltip title={node.value.project_slug}>
  259. <ProjectBadge
  260. project={project ? project : {slug: node.value.project_slug}}
  261. avatarSize={30}
  262. hideName
  263. />
  264. </Tooltip>
  265. <div>
  266. <div>{t('transaction')}</div>
  267. <TraceDrawerComponents.TitleOp>
  268. {' '}
  269. {node.value['transaction.op']}
  270. </TraceDrawerComponents.TitleOp>
  271. </div>
  272. </TraceDrawerComponents.Title>
  273. <TraceDrawerComponents.Actions>
  274. <Button size="xs" onClick={_e => scrollToNode(node)}>
  275. {t('Show in view')}
  276. </Button>
  277. <TraceDrawerComponents.EventDetailsLink
  278. eventId={node.value.event_id}
  279. projectSlug={node.metadata.project_slug}
  280. />
  281. <Button
  282. size="xs"
  283. icon={<IconOpen />}
  284. href={`/api/0/projects/${organization.slug}/${node.value.project_slug}/events/${node.value.event_id}/json/`}
  285. external
  286. >
  287. {t('JSON')} (<FileSize bytes={event?.size} />)
  288. </Button>
  289. </TraceDrawerComponents.Actions>
  290. </TraceDrawerComponents.HeaderContainer>
  291. <IssueList node={node} organization={organization} issues={issues} />
  292. <TraceDrawerComponents.Table className="table key-value">
  293. <tbody>
  294. <Row title="Duration">
  295. <TraceDrawerComponents.Duration
  296. duration={durationInSeconds}
  297. baseline={avgDurationInSeconds}
  298. />
  299. </Row>
  300. {parentTransaction ? (
  301. <Row title="Parent Transaction">
  302. <td className="value">
  303. <a href="#" onClick={() => onParentClick(parentTransaction)}>
  304. {getTraceTabTitle(parentTransaction)}
  305. </a>
  306. </td>
  307. </Row>
  308. ) : null}
  309. <Row title={t('Event ID')}>
  310. {node.value.event_id}
  311. <CopyToClipboardButton
  312. borderless
  313. size="zero"
  314. iconSize="xs"
  315. text={node.value.event_id}
  316. />
  317. </Row>
  318. <Row title={t('Description')}>
  319. <Link
  320. to={transactionSummaryRouteWithQuery({
  321. orgSlug: organization.slug,
  322. transaction: node.value.transaction,
  323. query: omit(location.query, Object.values(PAGE_URL_PARAM)),
  324. projectID: String(node.value.project_id),
  325. })}
  326. >
  327. {node.value.transaction}
  328. </Link>
  329. </Row>
  330. {node.value.profile_id ? (
  331. <Row
  332. title="Profile ID"
  333. extra={
  334. <TraceDrawerComponents.Button
  335. size="xs"
  336. to={generateProfileFlamechartRoute({
  337. orgSlug: organization.slug,
  338. projectSlug: node.value.project_slug,
  339. profileId: node.value.profile_id,
  340. })}
  341. onClick={function handleOnClick() {
  342. trackAnalytics('profiling_views.go_to_flamegraph', {
  343. organization,
  344. source: 'performance.trace_view',
  345. });
  346. }}
  347. >
  348. {t('View Profile')}
  349. </TraceDrawerComponents.Button>
  350. }
  351. >
  352. {node.value.profile_id}
  353. </Row>
  354. ) : null}
  355. <Row title="Date Range">
  356. {getDynamicText({
  357. fixed: 'Mar 19, 2021 11:06:27 AM UTC',
  358. value: (
  359. <Fragment>
  360. <DateTime date={startTimestamp * node.multiplier} />
  361. {` (${startTimeWithLeadingZero})`}
  362. </Fragment>
  363. ),
  364. })}
  365. <br />
  366. {getDynamicText({
  367. fixed: 'Mar 19, 2021 11:06:28 AM UTC',
  368. value: (
  369. <Fragment>
  370. <DateTime date={endTimestamp * node.multiplier} />
  371. {` (${endTimeWithLeadingZero})`}
  372. </Fragment>
  373. ),
  374. })}
  375. </Row>
  376. <OpsBreakdown event={event} />
  377. {!event || !event.measurements || measurementKeys.length <= 0 ? null : (
  378. <Fragment>
  379. {measurementKeys.map(measurement => (
  380. <Row
  381. key={measurement}
  382. title={WEB_VITAL_DETAILS[`measurements.${measurement}`]?.name}
  383. >
  384. <PerformanceDuration
  385. milliseconds={Number(
  386. event.measurements?.[measurement].value.toFixed(3)
  387. )}
  388. abbreviation
  389. />
  390. </Row>
  391. ))}
  392. </Fragment>
  393. )}
  394. {measurementNames.length > 0 && (
  395. <tr>
  396. <td className="key">{t('Measurements')}</td>
  397. <td className="value">
  398. <Measurements>
  399. {measurementNames.map(name => {
  400. return (
  401. event && (
  402. <TraceEventCustomPerformanceMetric
  403. key={name}
  404. event={event}
  405. name={name}
  406. location={location}
  407. organization={organization}
  408. source={undefined}
  409. isHomepage={false}
  410. />
  411. )
  412. );
  413. })}
  414. </Measurements>
  415. </td>
  416. </tr>
  417. )}
  418. </tbody>
  419. </TraceDrawerComponents.Table>
  420. <LazyRender {...LAZY_RENDER_PROPS} containerHeight={200}>
  421. {organization.features.includes('event-tags-tree-ui') ? (
  422. <TagsWrapper>
  423. <NewTagsUI event={event} projectSlug={node.value.project_slug} />
  424. </TagsWrapper>
  425. ) : (
  426. <TraceDrawerComponents.Table className="table key-value">
  427. <tbody>
  428. <Tags
  429. enableHiding
  430. location={location}
  431. organization={organization}
  432. tags={event.tags}
  433. event={node.value}
  434. />
  435. </tbody>
  436. </TraceDrawerComponents.Table>
  437. )}
  438. </LazyRender>
  439. {project ? <EventEvidence event={event} project={project} /> : null}
  440. <LazyRender {...LAZY_RENDER_PROPS} containerHeight={480}>
  441. <ReplaySection event={event} organization={organization} />
  442. </LazyRender>
  443. {event.projectSlug ? (
  444. <Entries
  445. definedEvent={event}
  446. projectSlug={event.projectSlug}
  447. group={undefined}
  448. organization={organization}
  449. isShare
  450. hideBeforeReplayEntries
  451. hideBreadCrumbs
  452. />
  453. ) : null}
  454. {!objectIsEmpty(event.contexts?.feedback ?? {}) ? (
  455. <Chunk
  456. key="feedback"
  457. type="feedback"
  458. alias="feedback"
  459. group={undefined}
  460. event={event}
  461. value={event.contexts?.feedback ?? {}}
  462. />
  463. ) : null}
  464. {event.user && !objectIsEmpty(event.user) ? (
  465. <Chunk
  466. key="user"
  467. type="user"
  468. alias="user"
  469. group={undefined}
  470. event={event}
  471. value={event.user}
  472. />
  473. ) : null}
  474. <EventExtraData event={event} />
  475. <EventSdk sdk={event.sdk} meta={event._meta?.sdk} />
  476. {event._metrics_summary ? (
  477. <CustomMetricsEventData
  478. metricsSummary={event._metrics_summary}
  479. startTimestamp={event.startTimestamp}
  480. />
  481. ) : null}
  482. <BreadCrumbsSection event={event} organization={organization} />
  483. {event.projectSlug ? (
  484. <EventAttachments event={event} projectSlug={event.projectSlug} />
  485. ) : null}
  486. {project ? <EventViewHierarchy event={event} project={project} /> : null}
  487. {event.projectSlug ? (
  488. <EventRRWebIntegration
  489. event={event}
  490. orgId={organization.slug}
  491. projectSlug={event.projectSlug}
  492. />
  493. ) : null}
  494. </TraceDrawerComponents.DetailContainer>
  495. );
  496. }
  497. const ReplaySectionContainer = styled('div')`
  498. display: flex;
  499. flex-direction: column;
  500. `;
  501. const ReplaySectionTitle = styled('div')`
  502. font-size: ${p => p.theme.fontSizeMedium};
  503. font-weight: 600;
  504. margin-bottom: ${space(2)};
  505. `;
  506. const Measurements = styled('div')`
  507. display: flex;
  508. flex-wrap: wrap;
  509. gap: ${space(1)};
  510. padding-top: 10px;
  511. `;
  512. const TagsWrapper = styled('div')`
  513. h3 {
  514. color: ${p => p.theme.textColor};
  515. }
  516. `;