fieldRenderers.tsx 15 KB

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