fieldRenderers.tsx 16 KB

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