transaction.tsx 16 KB

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