fieldRenderers.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. import {useState} from 'react';
  2. import {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} 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 {useLocation} from 'sentry/utils/useLocation';
  21. import useOrganization from 'sentry/utils/useOrganization';
  22. import usePageFilters from 'sentry/utils/usePageFilters';
  23. import useProjects from 'sentry/utils/useProjects';
  24. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  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/traceMetadataHeader';
  29. import type {SpanResult, TraceResult} from './content';
  30. import type {Field} from './data';
  31. import {getShortenedSdkName, getStylingSliceName} from './utils';
  32. interface ProjectRendererProps {
  33. projectSlug: string;
  34. hideName?: boolean;
  35. }
  36. export function SpanDescriptionRenderer({span}: {span: SpanResult<Field>}) {
  37. return (
  38. <Description>
  39. <ProjectRenderer projectSlug={span.project} hideName />
  40. <strong>{span['span.op']}</strong>
  41. <em>{'\u2014'}</em>
  42. <WrappingText>{span['span.description']}</WrappingText>
  43. {<StatusTag status={span['span.status']} />}
  44. </Description>
  45. );
  46. }
  47. export function ProjectRenderer({projectSlug, hideName}: ProjectRendererProps) {
  48. const organization = useOrganization();
  49. return (
  50. <Projects orgId={organization.slug} slugs={[projectSlug]}>
  51. {({projects}) => {
  52. const project = projects.find(p => p.slug === projectSlug);
  53. return (
  54. <ProjectBadge
  55. hideName={hideName}
  56. project={project ? project : {slug: projectSlug}}
  57. avatarSize={16}
  58. />
  59. );
  60. }}
  61. </Projects>
  62. );
  63. }
  64. const WrappingText = styled('div')`
  65. ${p => p.theme.overflowEllipsis};
  66. width: auto;
  67. `;
  68. export const TraceBreakdownContainer = styled('div')<{hoveredIndex?: number}>`
  69. position: relative;
  70. display: flex;
  71. min-width: 200px;
  72. height: 15px;
  73. background-color: ${p => p.theme.gray100};
  74. ${p => `--hoveredSlice-${p.hoveredIndex ?? -1}-translateY: translateY(-3px)`};
  75. `;
  76. const RectangleTraceBreakdown = styled(RowRectangle)<{
  77. sliceColor: string;
  78. sliceName: string | null;
  79. offset?: number;
  80. }>`
  81. background-color: ${p => p.sliceColor};
  82. position: relative;
  83. width: 100%;
  84. height: 15px;
  85. ${p => `
  86. filter: var(--highlightedSlice-${p.sliceName}-saturate, var(--defaultSlice-saturate));
  87. `}
  88. ${p => `
  89. opacity: var(--highlightedSlice-${p.sliceName ?? ''}-opacity, var(--defaultSlice-opacity, 1.0));
  90. `}
  91. ${p => `
  92. transform: var(--hoveredSlice-${p.offset}-translateY, var(--highlightedSlice-${p.sliceName ?? ''}-transform, var(--defaultSlice-transform, 1.0)));
  93. `}
  94. transition: filter,opacity,transform 0.2s cubic-bezier(0.4, 0, 0.2, 1);
  95. `;
  96. export function TraceBreakdownRenderer({
  97. trace,
  98. setHighlightedSliceName,
  99. }: {
  100. setHighlightedSliceName: (sliceName: string) => void;
  101. trace: TraceResult;
  102. }) {
  103. const theme = useTheme();
  104. const [hoveredIndex, setHoveredIndex] = useState(-1);
  105. return (
  106. <TraceBreakdownContainer
  107. data-test-id="relative-ops-breakdown"
  108. hoveredIndex={hoveredIndex}
  109. onMouseLeave={() => setHoveredIndex(-1)}
  110. >
  111. {trace.breakdowns.map((breakdown, index) => {
  112. return (
  113. <SpanBreakdownSliceRenderer
  114. key={breakdown.start + (breakdown.project ?? t('missing instrumentation'))}
  115. sliceName={breakdown.project}
  116. sliceStart={breakdown.start}
  117. sliceEnd={breakdown.end}
  118. sliceDurationReal={breakdown.duration}
  119. sliceSecondaryName={breakdown.sdkName}
  120. sliceNumberStart={breakdown.sliceStart}
  121. sliceNumberWidth={breakdown.sliceWidth}
  122. trace={trace}
  123. theme={theme}
  124. offset={index}
  125. onMouseEnter={() => {
  126. setHoveredIndex(index);
  127. breakdown.project
  128. ? setHighlightedSliceName(
  129. getStylingSliceName(breakdown.project, breakdown.sdkName) ?? ''
  130. )
  131. : null;
  132. }}
  133. />
  134. );
  135. })}
  136. </TraceBreakdownContainer>
  137. );
  138. }
  139. const BREAKDOWN_SIZE_PX = 200;
  140. export const BREAKDOWN_SLICES = 40;
  141. /**
  142. * This renders slices in two different ways;
  143. * - Slices in the breakdown for the trace. These have slice numbers returned for quantization from the backend.
  144. * - Slices derived from span timings. Spans aren't quantized into slices.
  145. */
  146. export function SpanBreakdownSliceRenderer({
  147. trace,
  148. theme,
  149. sliceName,
  150. sliceStart,
  151. sliceEnd,
  152. sliceNumberStart,
  153. sliceNumberWidth,
  154. sliceDurationReal,
  155. sliceSecondaryName,
  156. onMouseEnter,
  157. offset,
  158. }: {
  159. onMouseEnter: () => void;
  160. sliceEnd: number;
  161. sliceName: string | null;
  162. sliceSecondaryName: string | null;
  163. sliceStart: number;
  164. theme: Theme;
  165. trace: TraceResult;
  166. offset?: number;
  167. sliceDurationReal?: number;
  168. sliceNumberStart?: number;
  169. sliceNumberWidth?: number;
  170. }) {
  171. const traceDuration = trace.end - trace.start;
  172. const sliceDuration = sliceEnd - sliceStart;
  173. const pixelsPerSlice = BREAKDOWN_SIZE_PX / BREAKDOWN_SLICES;
  174. const relativeSliceStart = sliceStart - trace.start;
  175. const stylingSliceName = getStylingSliceName(sliceName, sliceSecondaryName);
  176. const sliceColor = stylingSliceName ? pickBarColor(stylingSliceName) : theme.gray100;
  177. const sliceWidth =
  178. sliceNumberWidth !== undefined
  179. ? pixelsPerSlice * sliceNumberWidth
  180. : pixelsPerSlice * Math.ceil(BREAKDOWN_SLICES * (sliceDuration / traceDuration));
  181. const sliceOffset =
  182. sliceNumberStart !== undefined
  183. ? pixelsPerSlice * sliceNumberStart
  184. : pixelsPerSlice *
  185. Math.floor((BREAKDOWN_SLICES * relativeSliceStart) / traceDuration);
  186. return (
  187. <BreakdownSlice
  188. sliceName={sliceName}
  189. sliceOffset={sliceOffset}
  190. sliceWidth={sliceWidth}
  191. onMouseEnter={onMouseEnter}
  192. >
  193. <Tooltip
  194. title={
  195. <div>
  196. <FlexContainer>
  197. {sliceName ? <ProjectRenderer projectSlug={sliceName} hideName /> : null}
  198. <strong>{sliceName}</strong>
  199. <Subtext>({getShortenedSdkName(sliceSecondaryName)})</Subtext>
  200. </FlexContainer>
  201. <div>
  202. <PerformanceDuration
  203. milliseconds={sliceDurationReal ?? sliceDuration}
  204. abbreviation
  205. />
  206. </div>
  207. </div>
  208. }
  209. containerDisplayMode="block"
  210. >
  211. <RectangleTraceBreakdown
  212. sliceColor={sliceColor}
  213. sliceName={stylingSliceName}
  214. offset={offset}
  215. />
  216. </Tooltip>
  217. </BreakdownSlice>
  218. );
  219. }
  220. const Subtext = styled('span')`
  221. font-weight: ${p => p.theme.fontWeightNormal};
  222. color: ${p => p.theme.gray300};
  223. `;
  224. const FlexContainer = styled('div')`
  225. display: flex;
  226. flex-direction: row;
  227. align-items: center;
  228. gap: ${space(0.5)};
  229. padding-bottom: ${space(0.5)};
  230. `;
  231. const BreakdownSlice = styled('div')<{
  232. sliceName: string | null;
  233. sliceOffset: number;
  234. sliceWidth: number;
  235. }>`
  236. position: absolute;
  237. width: max(3px, ${p => p.sliceWidth}px);
  238. left: ${p => p.sliceOffset}px;
  239. ${p => (p.sliceName ? null : 'z-index: -1;')}
  240. `;
  241. interface SpanIdRendererProps {
  242. projectSlug: string;
  243. spanId: string;
  244. timestamp: string;
  245. traceId: string;
  246. transactionId: string;
  247. onClick?: () => void;
  248. }
  249. export function SpanIdRenderer({
  250. projectSlug,
  251. spanId,
  252. timestamp,
  253. traceId,
  254. transactionId,
  255. onClick,
  256. }: SpanIdRendererProps) {
  257. const location = useLocation();
  258. const organization = useOrganization();
  259. const target = generateLinkToEventInTraceView({
  260. projectSlug,
  261. traceSlug: traceId,
  262. timestamp,
  263. eventId: transactionId,
  264. organization,
  265. location,
  266. spanId,
  267. source: TraceViewSources.TRACES,
  268. });
  269. return (
  270. <Link to={target} onClick={onClick}>
  271. {getShortEventId(spanId)}
  272. </Link>
  273. );
  274. }
  275. interface TraceIdRendererProps {
  276. location: Location;
  277. timestamp: number; // in milliseconds
  278. traceId: string;
  279. onClick?: () => void;
  280. transactionId?: string;
  281. }
  282. export function TraceIdRenderer({
  283. traceId,
  284. timestamp,
  285. transactionId,
  286. location,
  287. onClick,
  288. }: TraceIdRendererProps) {
  289. const organization = useOrganization();
  290. const {selection} = usePageFilters();
  291. const target = getTraceDetailsUrl({
  292. organization,
  293. traceSlug: traceId,
  294. dateSelection: {
  295. start: selection.datetime.start,
  296. end: selection.datetime.end,
  297. statsPeriod: selection.datetime.period,
  298. },
  299. timestamp: timestamp / 1000,
  300. eventId: transactionId,
  301. location,
  302. source: TraceViewSources.TRACES,
  303. });
  304. return (
  305. <Link to={target} style={{minWidth: '66px', textAlign: 'right'}} onClick={onClick}>
  306. {getShortEventId(traceId)}
  307. </Link>
  308. );
  309. }
  310. interface TransactionRendererProps {
  311. projectSlug: string;
  312. transaction: string;
  313. }
  314. export function TransactionRenderer({
  315. projectSlug,
  316. transaction,
  317. }: TransactionRendererProps) {
  318. const location = useLocation();
  319. const organization = useOrganization();
  320. const {projects} = useProjects({slugs: [projectSlug]});
  321. const target = transactionSummaryRouteWithQuery({
  322. orgSlug: organization.slug,
  323. transaction,
  324. query: {
  325. ...location.query,
  326. query: undefined,
  327. },
  328. projectID: String(projects[0]?.id ?? ''),
  329. });
  330. return <Link to={target}>{transaction}</Link>;
  331. }
  332. export function TraceIssuesRenderer({
  333. trace,
  334. onClick,
  335. }: {
  336. trace: TraceResult;
  337. onClick?: () => void;
  338. }) {
  339. const organization = useOrganization();
  340. const issueCount = trace.numErrors + trace.numOccurrences;
  341. const issueText = issueCount >= 100 ? '99+' : issueCount === 0 ? '\u2014' : issueCount;
  342. return (
  343. <LinkButton
  344. to={normalizeUrl({
  345. pathname: `/organizations/${organization.slug}/issues`,
  346. query: {
  347. query: `trace:"${trace.trace}"`,
  348. },
  349. })}
  350. onClick={onClick}
  351. size="xs"
  352. icon={<IconIssues size="xs" />}
  353. disabled={issueCount === 0}
  354. style={{minHeight: '24px', height: '24px', minWidth: '44px'}}
  355. >
  356. {issueText}
  357. </LinkButton>
  358. );
  359. }
  360. export function SpanTimeRenderer({
  361. timestamp,
  362. tooltipShowSeconds,
  363. }: {
  364. timestamp: number;
  365. tooltipShowSeconds?: boolean;
  366. }) {
  367. const date = new Date(timestamp);
  368. return (
  369. <TimeSince
  370. unitStyle="extraShort"
  371. date={date}
  372. tooltipShowSeconds={tooltipShowSeconds}
  373. />
  374. );
  375. }
  376. type SpanStatus = SpanIndexedResponse[SpanIndexedField.SPAN_STATUS];
  377. const STATUS_TO_TAG_TYPE: Record<SpanStatus, keyof Theme['tag']> = {
  378. ok: 'success',
  379. cancelled: 'warning',
  380. unknown: 'info',
  381. invalid_argument: 'warning',
  382. deadline_exceeded: 'error',
  383. not_found: 'warning',
  384. already_exists: 'warning',
  385. permission_denied: 'warning',
  386. resource_exhausted: 'warning',
  387. failed_precondition: 'warning',
  388. aborted: 'warning',
  389. out_of_range: 'warning',
  390. unimplemented: 'error',
  391. internal_error: 'error',
  392. unavailable: 'error',
  393. data_loss: 'error',
  394. unauthenticated: 'warning',
  395. };
  396. function statusToTagType(status: string) {
  397. return STATUS_TO_TAG_TYPE[status];
  398. }
  399. const OMITTED_SPAN_STATUS = ['unknown'];
  400. /**
  401. * This display a tag for the status (not to be confused with 'status_code' which has values like '200', '429').
  402. */
  403. export function StatusTag({status, onClick}: {status: string; onClick?: () => void}) {
  404. const tagType = statusToTagType(status);
  405. if (!tagType) {
  406. return null;
  407. }
  408. if (OMITTED_SPAN_STATUS.includes(status)) {
  409. return null;
  410. }
  411. return (
  412. <StyledTag type={tagType} onClick={onClick} borderStyle="solid">
  413. {status}
  414. </StyledTag>
  415. );
  416. }
  417. const StyledTag = styled(Tag)`
  418. cursor: ${p => (p.onClick ? 'pointer' : 'default')};
  419. `;
  420. const Description = styled('div')`
  421. ${p => p.theme.overflowEllipsis};
  422. display: flex;
  423. flex-direction: row;
  424. align-items: center;
  425. gap: ${space(1)};
  426. `;