transaction.tsx 17 KB

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