fieldRenderers.tsx 12 KB

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