fieldRenderers.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. import {useState} from 'react';
  2. import {css, type Theme, useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import type {Location} from 'history';
  5. import Tag from 'sentry/components/badge/tag';
  6. import {LinkButton} from 'sentry/components/button';
  7. import ProjectBadge from 'sentry/components/idBadge/projectBadge';
  8. import Link from 'sentry/components/links/link';
  9. import {RowRectangle} from 'sentry/components/performance/waterfall/rowBar';
  10. import {pickBarColor} from 'sentry/components/performance/waterfall/utils';
  11. import PerformanceDuration from 'sentry/components/performanceDuration';
  12. import TimeSince from 'sentry/components/timeSince';
  13. import {Tooltip} from 'sentry/components/tooltip';
  14. import {IconIssues} from 'sentry/icons';
  15. import {t, tn} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import {generateLinkToEventInTraceView} from 'sentry/utils/discover/urls';
  18. import {getShortEventId} from 'sentry/utils/events';
  19. import Projects from 'sentry/utils/projects';
  20. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  21. import {useLocation} from 'sentry/utils/useLocation';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import usePageFilters from 'sentry/utils/usePageFilters';
  24. import useProjects from 'sentry/utils/useProjects';
  25. import type {SpanIndexedField, SpanIndexedResponse} from 'sentry/views/insights/types';
  26. import {getTraceDetailsUrl} from 'sentry/views/performance/traceDetails/utils';
  27. import {transactionSummaryRouteWithQuery} from 'sentry/views/performance/transactionSummary/utils';
  28. import {TraceViewSources} from '../performance/newTraceDetails/traceHeader/breadcrumbs';
  29. import type {TraceResult} from './hooks/useTraces';
  30. import {BREAKDOWN_SLICES} from './hooks/useTraces';
  31. import type {SpanResult} from './hooks/useTraceSpans';
  32. import type {Field} from './data';
  33. import {getShortenedSdkName, getStylingSliceName} from './utils';
  34. export const ProjectBadgeWrapper = styled('span')`
  35. /**
  36. * Max of 2 visible projects, 16px each, 2px border, 8px overlap.
  37. */
  38. width: 32px;
  39. min-width: 32px;
  40. `;
  41. export function SpanDescriptionRenderer({span}: {span: SpanResult<Field>}) {
  42. return (
  43. <Description data-test-id="span-description">
  44. <ProjectBadgeWrapper>
  45. <ProjectRenderer projectSlug={span.project} hideName />
  46. </ProjectBadgeWrapper>
  47. <strong>{span['span.op']}</strong>
  48. <em>{'\u2014'}</em>
  49. <WrappingText>{span['span.description']}</WrappingText>
  50. {<StatusTag status={span['span.status']} />}
  51. </Description>
  52. );
  53. }
  54. interface ProjectsRendererProps {
  55. projectSlugs: string[];
  56. maxVisibleProjects?: number;
  57. }
  58. export function ProjectsRenderer({
  59. projectSlugs,
  60. maxVisibleProjects = 2,
  61. }: ProjectsRendererProps) {
  62. const organization = useOrganization();
  63. return (
  64. <Projects orgId={organization.slug} slugs={projectSlugs}>
  65. {({projects}) => {
  66. const projectAvatars =
  67. projects.length > 0 ? projects : projectSlugs.map(slug => ({slug}));
  68. const numProjects = projectAvatars.length;
  69. const numVisibleProjects =
  70. maxVisibleProjects - numProjects >= 0 ? numProjects : maxVisibleProjects - 1;
  71. const visibleProjectAvatars = projectAvatars
  72. .slice(0, numVisibleProjects)
  73. .reverse();
  74. const collapsedProjectAvatars = projectAvatars.slice(numVisibleProjects);
  75. const numCollapsedProjects = collapsedProjectAvatars.length;
  76. return (
  77. <ProjectList>
  78. {numCollapsedProjects > 0 && (
  79. <Tooltip
  80. skipWrapper
  81. title={
  82. <CollapsedProjects>
  83. {tn(
  84. 'This trace contains %s more project.',
  85. 'This trace contains %s more projects.',
  86. numCollapsedProjects
  87. )}
  88. {collapsedProjectAvatars.map(project => (
  89. <ProjectBadge
  90. key={project.slug}
  91. project={project}
  92. avatarSize={16}
  93. />
  94. ))}
  95. </CollapsedProjects>
  96. }
  97. >
  98. <CollapsedBadge
  99. size={20}
  100. fontSize={10}
  101. data-test-id="collapsed-projects-badge"
  102. >
  103. +{numCollapsedProjects}
  104. </CollapsedBadge>
  105. </Tooltip>
  106. )}
  107. {visibleProjectAvatars.map(project => (
  108. <StyledProjectBadge
  109. key={project.slug}
  110. hideName
  111. project={project}
  112. avatarSize={16}
  113. avatarProps={{hasTooltip: true, tooltip: project.slug}}
  114. />
  115. ))}
  116. </ProjectList>
  117. );
  118. }}
  119. </Projects>
  120. );
  121. }
  122. const ProjectList = styled('div')`
  123. display: flex;
  124. align-items: center;
  125. flex-direction: row-reverse;
  126. justify-content: flex-end;
  127. padding-right: 8px;
  128. `;
  129. const CollapsedProjects = styled('div')`
  130. width: 200px;
  131. display: flex;
  132. flex-direction: column;
  133. gap: ${space(0.5)};
  134. `;
  135. const AvatarStyle = p => css`
  136. border: 2px solid ${p.theme.background};
  137. margin-right: -8px;
  138. cursor: default;
  139. &:hover {
  140. z-index: 1;
  141. }
  142. `;
  143. const StyledProjectBadge = styled(ProjectBadge)`
  144. overflow: hidden;
  145. z-index: 0;
  146. ${AvatarStyle}
  147. `;
  148. const CollapsedBadge = styled('div')<{fontSize: number; size: number}>`
  149. display: flex;
  150. align-items: center;
  151. justify-content: center;
  152. position: relative;
  153. text-align: center;
  154. font-weight: ${p => p.theme.fontWeightBold};
  155. background-color: ${p => p.theme.gray200};
  156. color: ${p => p.theme.gray300};
  157. font-size: ${p => p.fontSize}px;
  158. width: ${p => p.size}px;
  159. height: ${p => p.size}px;
  160. border-radius: ${p => p.theme.borderRadius};
  161. ${AvatarStyle}
  162. `;
  163. interface ProjectRendererProps {
  164. projectSlug: string;
  165. hideName?: boolean;
  166. }
  167. export function ProjectRenderer({projectSlug, hideName}: ProjectRendererProps) {
  168. const organization = useOrganization();
  169. return (
  170. <Projects orgId={organization.slug} slugs={[projectSlug]}>
  171. {({projects}) => {
  172. const project = projects.find(p => p.slug === projectSlug);
  173. return (
  174. <ProjectBadge
  175. hideName={hideName}
  176. project={project ? project : {slug: projectSlug}}
  177. avatarSize={16}
  178. avatarProps={{hasTooltip: true, tooltip: projectSlug}}
  179. />
  180. );
  181. }}
  182. </Projects>
  183. );
  184. }
  185. const WrappingText = styled('div')`
  186. ${p => p.theme.overflowEllipsis};
  187. width: auto;
  188. `;
  189. export const TraceBreakdownContainer = styled('div')<{hoveredIndex?: number}>`
  190. position: relative;
  191. display: flex;
  192. min-width: 200px;
  193. height: 15px;
  194. background-color: ${p => p.theme.gray100};
  195. ${p => `--hoveredSlice-${p.hoveredIndex ?? -1}-translateY: translateY(-3px)`};
  196. `;
  197. const RectangleTraceBreakdown = styled(RowRectangle)<{
  198. sliceColor: string;
  199. sliceName: string | null;
  200. offset?: number;
  201. }>`
  202. background-color: ${p => p.sliceColor};
  203. position: relative;
  204. width: 100%;
  205. height: 15px;
  206. ${p => `
  207. filter: var(--highlightedSlice-${p.sliceName}-saturate, var(--defaultSlice-saturate));
  208. `}
  209. ${p => `
  210. opacity: var(--highlightedSlice-${p.sliceName ?? ''}-opacity, var(--defaultSlice-opacity, 1.0));
  211. `}
  212. ${p => `
  213. transform: var(--hoveredSlice-${p.offset}-translateY, var(--highlightedSlice-${p.sliceName ?? ''}-transform, var(--defaultSlice-transform, 1.0)));
  214. `}
  215. transition: filter,opacity,transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  216. `;
  217. export function TraceBreakdownRenderer({
  218. trace,
  219. setHighlightedSliceName,
  220. }: {
  221. setHighlightedSliceName: (sliceName: string) => void;
  222. trace: TraceResult;
  223. }) {
  224. const theme = useTheme();
  225. const [hoveredIndex, setHoveredIndex] = useState(-1);
  226. return (
  227. <TraceBreakdownContainer
  228. data-test-id="relative-ops-breakdown"
  229. hoveredIndex={hoveredIndex}
  230. onMouseLeave={() => setHoveredIndex(-1)}
  231. >
  232. {trace.breakdowns.map((breakdown, index) => {
  233. return (
  234. <SpanBreakdownSliceRenderer
  235. key={breakdown.start + (breakdown.project ?? t('missing instrumentation'))}
  236. sliceName={breakdown.project}
  237. sliceStart={breakdown.start}
  238. sliceEnd={breakdown.end}
  239. sliceDurationReal={breakdown.duration}
  240. sliceSecondaryName={breakdown.sdkName}
  241. sliceNumberStart={breakdown.sliceStart}
  242. sliceNumberWidth={breakdown.sliceWidth}
  243. trace={trace}
  244. theme={theme}
  245. offset={index}
  246. onMouseEnter={() => {
  247. setHoveredIndex(index);
  248. breakdown.project
  249. ? setHighlightedSliceName(
  250. getStylingSliceName(breakdown.project, breakdown.sdkName) ?? ''
  251. )
  252. : null;
  253. }}
  254. />
  255. );
  256. })}
  257. </TraceBreakdownContainer>
  258. );
  259. }
  260. const BREAKDOWN_SIZE_PX = 200;
  261. /**
  262. * This renders slices in two different ways;
  263. * - Slices in the breakdown for the trace. These have slice numbers returned for quantization from the backend.
  264. * - Slices derived from span timings. Spans aren't quantized into slices.
  265. */
  266. export function SpanBreakdownSliceRenderer({
  267. trace,
  268. theme,
  269. sliceName,
  270. sliceStart,
  271. sliceEnd,
  272. sliceNumberStart,
  273. sliceNumberWidth,
  274. sliceDurationReal,
  275. sliceSecondaryName,
  276. onMouseEnter,
  277. offset,
  278. }: {
  279. onMouseEnter: () => void;
  280. sliceEnd: number;
  281. sliceName: string | null;
  282. sliceSecondaryName: string | null;
  283. sliceStart: number;
  284. theme: Theme;
  285. trace: TraceResult;
  286. offset?: number;
  287. sliceDurationReal?: number;
  288. sliceNumberStart?: number;
  289. sliceNumberWidth?: number;
  290. }) {
  291. const traceDuration = trace.end - trace.start;
  292. const sliceDuration = sliceEnd - sliceStart;
  293. const pixelsPerSlice = BREAKDOWN_SIZE_PX / BREAKDOWN_SLICES;
  294. const relativeSliceStart = sliceStart - trace.start;
  295. const stylingSliceName = getStylingSliceName(sliceName, sliceSecondaryName);
  296. const sliceColor = stylingSliceName ? pickBarColor(stylingSliceName) : theme.gray100;
  297. const sliceWidth =
  298. sliceNumberWidth !== undefined
  299. ? pixelsPerSlice * sliceNumberWidth
  300. : pixelsPerSlice * Math.ceil(BREAKDOWN_SLICES * (sliceDuration / traceDuration));
  301. const sliceOffset =
  302. sliceNumberStart !== undefined
  303. ? pixelsPerSlice * sliceNumberStart
  304. : pixelsPerSlice *
  305. Math.floor((BREAKDOWN_SLICES * relativeSliceStart) / traceDuration);
  306. return (
  307. <BreakdownSlice
  308. sliceName={sliceName}
  309. sliceOffset={sliceOffset}
  310. sliceWidth={sliceWidth}
  311. onMouseEnter={onMouseEnter}
  312. >
  313. <Tooltip
  314. title={
  315. <div>
  316. <FlexContainer>
  317. {sliceName ? <ProjectRenderer projectSlug={sliceName} hideName /> : null}
  318. <strong>{sliceName}</strong>
  319. <Subtext>({getShortenedSdkName(sliceSecondaryName)})</Subtext>
  320. </FlexContainer>
  321. <div>
  322. <PerformanceDuration
  323. milliseconds={sliceDurationReal ?? sliceDuration}
  324. abbreviation
  325. />
  326. </div>
  327. </div>
  328. }
  329. containerDisplayMode="block"
  330. >
  331. <RectangleTraceBreakdown
  332. sliceColor={sliceColor}
  333. sliceName={stylingSliceName}
  334. offset={offset}
  335. />
  336. </Tooltip>
  337. </BreakdownSlice>
  338. );
  339. }
  340. const Subtext = styled('span')`
  341. font-weight: ${p => p.theme.fontWeightNormal};
  342. color: ${p => p.theme.gray300};
  343. `;
  344. const FlexContainer = styled('div')`
  345. display: flex;
  346. flex-direction: row;
  347. align-items: center;
  348. gap: ${space(0.5)};
  349. padding-bottom: ${space(0.5)};
  350. `;
  351. const BreakdownSlice = styled('div')<{
  352. sliceName: string | null;
  353. sliceOffset: number;
  354. sliceWidth: number;
  355. }>`
  356. position: absolute;
  357. width: max(3px, ${p => p.sliceWidth}px);
  358. left: ${p => p.sliceOffset}px;
  359. ${p => (p.sliceName ? null : 'z-index: -1;')}
  360. `;
  361. interface SpanIdRendererProps {
  362. projectSlug: string;
  363. spanId: string;
  364. timestamp: string;
  365. traceId: string;
  366. transactionId: string;
  367. onClick?: () => void;
  368. }
  369. export function SpanIdRenderer({
  370. projectSlug,
  371. spanId,
  372. timestamp,
  373. traceId,
  374. transactionId,
  375. onClick,
  376. }: SpanIdRendererProps) {
  377. const location = useLocation();
  378. const organization = useOrganization();
  379. const target = generateLinkToEventInTraceView({
  380. projectSlug,
  381. traceSlug: traceId,
  382. timestamp,
  383. eventId: transactionId,
  384. organization,
  385. location,
  386. spanId,
  387. source: TraceViewSources.TRACES,
  388. });
  389. return (
  390. <Link to={target} onClick={onClick}>
  391. {getShortEventId(spanId)}
  392. </Link>
  393. );
  394. }
  395. interface TraceIdRendererProps {
  396. location: Location;
  397. timestamp: number; // in milliseconds
  398. traceId: string;
  399. onClick?: () => void;
  400. transactionId?: string;
  401. }
  402. export function TraceIdRenderer({
  403. traceId,
  404. timestamp,
  405. transactionId,
  406. location,
  407. onClick,
  408. }: TraceIdRendererProps) {
  409. const organization = useOrganization();
  410. const {selection} = usePageFilters();
  411. const target = getTraceDetailsUrl({
  412. organization,
  413. traceSlug: traceId,
  414. dateSelection: {
  415. start: selection.datetime.start,
  416. end: selection.datetime.end,
  417. statsPeriod: selection.datetime.period,
  418. },
  419. timestamp: timestamp / 1000,
  420. eventId: transactionId,
  421. location,
  422. source: TraceViewSources.TRACES,
  423. });
  424. return (
  425. <Link to={target} style={{minWidth: '66px', textAlign: 'right'}} onClick={onClick}>
  426. {getShortEventId(traceId)}
  427. </Link>
  428. );
  429. }
  430. interface TransactionRendererProps {
  431. projectSlug: string;
  432. transaction: string;
  433. }
  434. export function TransactionRenderer({
  435. projectSlug,
  436. transaction,
  437. }: TransactionRendererProps) {
  438. const location = useLocation();
  439. const organization = useOrganization();
  440. const {projects} = useProjects({slugs: [projectSlug]});
  441. const target = transactionSummaryRouteWithQuery({
  442. orgSlug: organization.slug,
  443. transaction,
  444. query: {
  445. ...location.query,
  446. query: undefined,
  447. },
  448. projectID: String(projects[0]?.id ?? ''),
  449. });
  450. return <Link to={target}>{transaction}</Link>;
  451. }
  452. export function TraceIssuesRenderer({
  453. trace,
  454. onClick,
  455. }: {
  456. trace: TraceResult;
  457. onClick?: () => void;
  458. }) {
  459. const organization = useOrganization();
  460. const issueCount = trace.numErrors + trace.numOccurrences;
  461. const issueText = issueCount >= 100 ? '99+' : issueCount === 0 ? '\u2014' : issueCount;
  462. return (
  463. <LinkButton
  464. to={normalizeUrl({
  465. pathname: `/organizations/${organization.slug}/issues`,
  466. query: {
  467. query: `trace:"${trace.trace}"`,
  468. },
  469. })}
  470. onClick={onClick}
  471. size="xs"
  472. icon={<IconIssues size="xs" />}
  473. disabled={issueCount === 0}
  474. style={{minHeight: '24px', height: '24px', minWidth: '44px'}}
  475. >
  476. {issueText}
  477. </LinkButton>
  478. );
  479. }
  480. export function SpanTimeRenderer({
  481. timestamp,
  482. tooltipShowSeconds,
  483. }: {
  484. timestamp: number;
  485. tooltipShowSeconds?: boolean;
  486. }) {
  487. const date = new Date(timestamp);
  488. return (
  489. <TimeSince
  490. unitStyle="extraShort"
  491. date={date}
  492. tooltipShowSeconds={tooltipShowSeconds}
  493. />
  494. );
  495. }
  496. type SpanStatus = SpanIndexedResponse[SpanIndexedField.SPAN_STATUS];
  497. const STATUS_TO_TAG_TYPE: Record<SpanStatus, keyof Theme['tag']> = {
  498. ok: 'success',
  499. cancelled: 'warning',
  500. unknown: 'info',
  501. invalid_argument: 'warning',
  502. deadline_exceeded: 'error',
  503. not_found: 'warning',
  504. already_exists: 'warning',
  505. permission_denied: 'warning',
  506. resource_exhausted: 'warning',
  507. failed_precondition: 'warning',
  508. aborted: 'warning',
  509. out_of_range: 'warning',
  510. unimplemented: 'error',
  511. internal_error: 'error',
  512. unavailable: 'error',
  513. data_loss: 'error',
  514. unauthenticated: 'warning',
  515. };
  516. function statusToTagType(status: string) {
  517. return STATUS_TO_TAG_TYPE[status];
  518. }
  519. const OMITTED_SPAN_STATUS = ['unknown'];
  520. /**
  521. * This display a tag for the status (not to be confused with 'status_code' which has values like '200', '429').
  522. */
  523. export function StatusTag({status, onClick}: {status: string; onClick?: () => void}) {
  524. const tagType = statusToTagType(status);
  525. if (!tagType) {
  526. return null;
  527. }
  528. if (OMITTED_SPAN_STATUS.includes(status)) {
  529. return null;
  530. }
  531. return (
  532. <StyledTag type={tagType} onClick={onClick} borderStyle="solid">
  533. {status}
  534. </StyledTag>
  535. );
  536. }
  537. const StyledTag = styled(Tag)`
  538. cursor: ${p => (p.onClick ? 'pointer' : 'default')};
  539. `;
  540. export const Description = styled('div')`
  541. ${p => p.theme.overflowEllipsis};
  542. display: flex;
  543. flex-direction: row;
  544. align-items: center;
  545. gap: ${space(1)};
  546. `;