transaction.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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. <TraceDrawerComponents.TitleText>
  266. <div>{t('transaction')}</div>
  267. <TraceDrawerComponents.TitleOp>
  268. {' '}
  269. {node.value['transaction.op']}
  270. </TraceDrawerComponents.TitleOp>
  271. </TraceDrawerComponents.TitleText>
  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. baseDescription={
  299. 'Average duration for this transaction over the last 24 hours'
  300. }
  301. />
  302. </Row>
  303. {parentTransaction ? (
  304. <Row title="Parent Transaction">
  305. <td className="value">
  306. <a href="#" onClick={() => onParentClick(parentTransaction)}>
  307. {getTraceTabTitle(parentTransaction)}
  308. </a>
  309. </td>
  310. </Row>
  311. ) : null}
  312. <Row title={t('Event ID')}>
  313. {node.value.event_id}
  314. <CopyToClipboardButton
  315. borderless
  316. size="zero"
  317. iconSize="xs"
  318. text={node.value.event_id}
  319. />
  320. </Row>
  321. <Row title={t('Description')}>
  322. <Link
  323. to={transactionSummaryRouteWithQuery({
  324. orgSlug: organization.slug,
  325. transaction: node.value.transaction,
  326. query: omit(location.query, Object.values(PAGE_URL_PARAM)),
  327. projectID: String(node.value.project_id),
  328. })}
  329. >
  330. {node.value.transaction}
  331. </Link>
  332. </Row>
  333. {node.value.profile_id ? (
  334. <Row
  335. title="Profile ID"
  336. extra={
  337. <TraceDrawerComponents.Button
  338. size="xs"
  339. to={generateProfileFlamechartRoute({
  340. orgSlug: organization.slug,
  341. projectSlug: node.value.project_slug,
  342. profileId: node.value.profile_id,
  343. })}
  344. onClick={function handleOnClick() {
  345. trackAnalytics('profiling_views.go_to_flamegraph', {
  346. organization,
  347. source: 'performance.trace_view',
  348. });
  349. }}
  350. >
  351. {t('View Profile')}
  352. </TraceDrawerComponents.Button>
  353. }
  354. >
  355. {node.value.profile_id}
  356. </Row>
  357. ) : null}
  358. <Row title="Date Range">
  359. {getDynamicText({
  360. fixed: 'Mar 19, 2021 11:06:27 AM UTC',
  361. value: (
  362. <Fragment>
  363. <DateTime date={startTimestamp * node.multiplier} />
  364. {` (${startTimeWithLeadingZero})`}
  365. </Fragment>
  366. ),
  367. })}
  368. <br />
  369. {getDynamicText({
  370. fixed: 'Mar 19, 2021 11:06:28 AM UTC',
  371. value: (
  372. <Fragment>
  373. <DateTime date={endTimestamp * node.multiplier} />
  374. {` (${endTimeWithLeadingZero})`}
  375. </Fragment>
  376. ),
  377. })}
  378. </Row>
  379. <OpsBreakdown event={event} />
  380. {!event || !event.measurements || measurementKeys.length <= 0 ? null : (
  381. <Fragment>
  382. {measurementKeys.map(measurement => (
  383. <Row
  384. key={measurement}
  385. title={WEB_VITAL_DETAILS[`measurements.${measurement}`]?.name}
  386. >
  387. <PerformanceDuration
  388. milliseconds={Number(
  389. event.measurements?.[measurement].value.toFixed(3)
  390. )}
  391. abbreviation
  392. />
  393. </Row>
  394. ))}
  395. </Fragment>
  396. )}
  397. {measurementNames.length > 0 && (
  398. <tr>
  399. <td className="key">{t('Measurements')}</td>
  400. <td className="value">
  401. <Measurements>
  402. {measurementNames.map(name => {
  403. return (
  404. event && (
  405. <TraceEventCustomPerformanceMetric
  406. key={name}
  407. event={event}
  408. name={name}
  409. location={location}
  410. organization={organization}
  411. source={undefined}
  412. isHomepage={false}
  413. />
  414. )
  415. );
  416. })}
  417. </Measurements>
  418. </td>
  419. </tr>
  420. )}
  421. </tbody>
  422. </TraceDrawerComponents.Table>
  423. <LazyRender {...LAZY_RENDER_PROPS} containerHeight={200}>
  424. {organization.features.includes('event-tags-tree-ui') ? (
  425. <TagsWrapper>
  426. <NewTagsUI event={event} projectSlug={node.value.project_slug} />
  427. </TagsWrapper>
  428. ) : (
  429. <TraceDrawerComponents.Table className="table key-value">
  430. <tbody>
  431. <Tags
  432. enableHiding
  433. location={location}
  434. organization={organization}
  435. tags={event.tags}
  436. event={node.value}
  437. />
  438. </tbody>
  439. </TraceDrawerComponents.Table>
  440. )}
  441. </LazyRender>
  442. {project ? <EventEvidence event={event} project={project} /> : null}
  443. <LazyRender {...LAZY_RENDER_PROPS} containerHeight={480}>
  444. <ReplaySection event={event} organization={organization} />
  445. </LazyRender>
  446. {event.projectSlug ? (
  447. <Entries
  448. definedEvent={event}
  449. projectSlug={event.projectSlug}
  450. group={undefined}
  451. organization={organization}
  452. isShare
  453. hideBeforeReplayEntries
  454. hideBreadCrumbs
  455. />
  456. ) : null}
  457. {!objectIsEmpty(event.contexts?.feedback ?? {}) ? (
  458. <Chunk
  459. key="feedback"
  460. type="feedback"
  461. alias="feedback"
  462. group={undefined}
  463. event={event}
  464. value={event.contexts?.feedback ?? {}}
  465. />
  466. ) : null}
  467. {event.user && !objectIsEmpty(event.user) ? (
  468. <Chunk
  469. key="user"
  470. type="user"
  471. alias="user"
  472. group={undefined}
  473. event={event}
  474. value={event.user}
  475. />
  476. ) : null}
  477. <EventExtraData event={event} />
  478. <EventSdk sdk={event.sdk} meta={event._meta?.sdk} />
  479. {event._metrics_summary ? (
  480. <CustomMetricsEventData
  481. metricsSummary={event._metrics_summary}
  482. startTimestamp={event.startTimestamp}
  483. />
  484. ) : null}
  485. <BreadCrumbsSection event={event} organization={organization} />
  486. {event.projectSlug ? (
  487. <EventAttachments event={event} projectSlug={event.projectSlug} />
  488. ) : null}
  489. {project ? <EventViewHierarchy event={event} project={project} /> : null}
  490. {event.projectSlug ? (
  491. <EventRRWebIntegration
  492. event={event}
  493. orgId={organization.slug}
  494. projectSlug={event.projectSlug}
  495. />
  496. ) : null}
  497. </TraceDrawerComponents.DetailContainer>
  498. );
  499. }
  500. const ReplaySectionContainer = styled('div')`
  501. display: flex;
  502. flex-direction: column;
  503. `;
  504. const ReplaySectionTitle = styled('div')`
  505. font-size: ${p => p.theme.fontSizeMedium};
  506. font-weight: 600;
  507. margin-bottom: ${space(2)};
  508. `;
  509. const Measurements = styled('div')`
  510. display: flex;
  511. flex-wrap: wrap;
  512. gap: ${space(1)};
  513. padding-top: 10px;
  514. `;
  515. const TagsWrapper = styled('div')`
  516. h3 {
  517. color: ${p => p.theme.textColor};
  518. }
  519. `;