fieldRenderers.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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 {IndexedResponse, SpanIndexedField} 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. trace={trace}
  120. theme={theme}
  121. offset={index}
  122. onMouseEnter={() => {
  123. setHoveredIndex(index);
  124. breakdown.project
  125. ? setHighlightedSliceName(
  126. getStylingSliceName(breakdown.project, breakdown.sdkName) ?? ''
  127. )
  128. : null;
  129. }}
  130. />
  131. );
  132. })}
  133. </TraceBreakdownContainer>
  134. );
  135. }
  136. const BREAKDOWN_BAR_SIZE = 200;
  137. const BREAKDOWN_QUANTIZE_STEP = 1;
  138. const BREAKDOWN_NUM_SLICES = BREAKDOWN_BAR_SIZE / BREAKDOWN_QUANTIZE_STEP; // 200
  139. export function SpanBreakdownSliceRenderer({
  140. trace,
  141. theme,
  142. sliceName,
  143. sliceStart,
  144. sliceEnd,
  145. sliceDurationReal,
  146. sliceSecondaryName,
  147. onMouseEnter,
  148. offset,
  149. }: {
  150. onMouseEnter: () => void;
  151. sliceEnd: number;
  152. sliceName: string | null;
  153. sliceSecondaryName: string | null;
  154. sliceStart: number;
  155. theme: Theme;
  156. trace: TraceResult<Field>;
  157. offset?: number;
  158. sliceDurationReal?: number;
  159. }) {
  160. const traceSliceSize = (trace.end - trace.start) / BREAKDOWN_NUM_SLICES;
  161. const traceDuration = BREAKDOWN_NUM_SLICES * traceSliceSize;
  162. const sliceDuration = sliceEnd - sliceStart;
  163. if (sliceDuration <= 0) {
  164. return null;
  165. }
  166. const stylingSliceName = getStylingSliceName(sliceName, sliceSecondaryName);
  167. const sliceColor = stylingSliceName ? pickBarColor(stylingSliceName) : theme.gray100;
  168. const sliceWidth =
  169. BREAKDOWN_QUANTIZE_STEP *
  170. Math.ceil(BREAKDOWN_NUM_SLICES * (sliceDuration / traceDuration));
  171. const relativeSliceStart = sliceStart - trace.start;
  172. const sliceOffset =
  173. BREAKDOWN_QUANTIZE_STEP *
  174. Math.floor((BREAKDOWN_NUM_SLICES * relativeSliceStart) / traceDuration);
  175. return (
  176. <BreakdownSlice
  177. sliceName={sliceName}
  178. sliceOffset={sliceOffset}
  179. sliceWidth={sliceWidth}
  180. onMouseEnter={onMouseEnter}
  181. >
  182. <Tooltip
  183. title={
  184. <div>
  185. <FlexContainer>
  186. {sliceName ? <ProjectRenderer projectSlug={sliceName} hideName /> : null}
  187. <strong>{sliceName}</strong>
  188. <Subtext>({getShortenedSdkName(sliceSecondaryName)})</Subtext>
  189. </FlexContainer>
  190. <div>
  191. <PerformanceDuration
  192. milliseconds={sliceDurationReal ?? sliceDuration}
  193. abbreviation
  194. />
  195. </div>
  196. </div>
  197. }
  198. containerDisplayMode="block"
  199. >
  200. <RectangleTraceBreakdown
  201. sliceColor={sliceColor}
  202. sliceName={stylingSliceName}
  203. offset={offset}
  204. />
  205. </Tooltip>
  206. </BreakdownSlice>
  207. );
  208. }
  209. const Subtext = styled('span')`
  210. font-weight: ${p => p.theme.fontWeightNormal};
  211. color: ${p => p.theme.gray300};
  212. `;
  213. const FlexContainer = styled('div')`
  214. display: flex;
  215. flex-direction: row;
  216. align-items: center;
  217. gap: ${space(0.5)};
  218. padding-bottom: ${space(0.5)};
  219. `;
  220. const BreakdownSlice = styled('div')<{
  221. sliceName: string | null;
  222. sliceOffset: number;
  223. sliceWidth: number;
  224. }>`
  225. position: absolute;
  226. width: max(3px, ${p => p.sliceWidth}px);
  227. left: ${p => p.sliceOffset}px;
  228. ${p => (p.sliceName ? null : 'z-index: -1;')}
  229. `;
  230. interface SpanIdRendererProps {
  231. projectSlug: string;
  232. spanId: string;
  233. timestamp: string;
  234. traceId: string;
  235. transactionId: string;
  236. }
  237. export function SpanIdRenderer({
  238. projectSlug,
  239. spanId,
  240. timestamp,
  241. traceId,
  242. transactionId,
  243. }: SpanIdRendererProps) {
  244. const location = useLocation();
  245. const organization = useOrganization();
  246. const target = generateLinkToEventInTraceView({
  247. projectSlug,
  248. traceSlug: traceId,
  249. timestamp,
  250. eventId: transactionId,
  251. organization,
  252. location,
  253. spanId,
  254. });
  255. return <Link to={target}>{getShortEventId(spanId)}</Link>;
  256. }
  257. interface TraceIdRendererProps {
  258. traceId: string;
  259. timestamp?: DateString;
  260. transactionId?: string;
  261. }
  262. export function TraceIdRenderer({
  263. traceId,
  264. timestamp,
  265. transactionId,
  266. }: TraceIdRendererProps) {
  267. const organization = useOrganization();
  268. const {selection} = usePageFilters();
  269. const stringOrNumberTimestamp =
  270. timestamp instanceof Date ? timestamp.toISOString() : timestamp ?? '';
  271. const target = getTraceDetailsUrl(
  272. organization,
  273. traceId,
  274. {
  275. start: selection.datetime.start,
  276. end: selection.datetime.end,
  277. statsPeriod: selection.datetime.period,
  278. },
  279. stringOrNumberTimestamp,
  280. transactionId
  281. );
  282. return (
  283. <Link to={target} style={{minWidth: '66px', textAlign: 'right'}}>
  284. {getShortEventId(traceId)}
  285. </Link>
  286. );
  287. }
  288. interface TransactionRendererProps {
  289. projectSlug: string;
  290. transaction: string;
  291. }
  292. export function TransactionRenderer({
  293. projectSlug,
  294. transaction,
  295. }: TransactionRendererProps) {
  296. const location = useLocation();
  297. const organization = useOrganization();
  298. const {projects} = useProjects({slugs: [projectSlug]});
  299. const target = transactionSummaryRouteWithQuery({
  300. orgSlug: organization.slug,
  301. transaction,
  302. query: {
  303. ...location.query,
  304. query: undefined,
  305. },
  306. projectID: String(projects[0]?.id ?? ''),
  307. });
  308. return <Link to={target}>{transaction}</Link>;
  309. }
  310. export function TraceIssuesRenderer({trace}: {trace: TraceResult<Field>}) {
  311. const organization = useOrganization();
  312. const issueCount = trace.numErrors + trace.numOccurrences;
  313. const issueText = issueCount >= 100 ? '99+' : issueCount === 0 ? '\u2014' : issueCount;
  314. return (
  315. <LinkButton
  316. to={normalizeUrl({
  317. pathname: `/organizations/${organization.slug}/issues`,
  318. query: {
  319. query: `trace:"${trace.trace}"`,
  320. },
  321. })}
  322. size="xs"
  323. icon={<IconIssues size="xs" />}
  324. disabled={issueCount === 0}
  325. style={{minHeight: '24px', height: '24px', minWidth: '44px'}}
  326. >
  327. {issueText}
  328. </LinkButton>
  329. );
  330. }
  331. export function SpanTimeRenderer({
  332. timestamp,
  333. tooltipShowSeconds,
  334. }: {
  335. timestamp: number;
  336. tooltipShowSeconds?: boolean;
  337. }) {
  338. const date = new Date(timestamp);
  339. return (
  340. <TimeSince
  341. unitStyle="extraShort"
  342. date={date}
  343. tooltipShowSeconds={tooltipShowSeconds}
  344. />
  345. );
  346. }
  347. type SpanStatus = IndexedResponse[SpanIndexedField.SPAN_STATUS];
  348. const STATUS_TO_TAG_TYPE: Record<SpanStatus, keyof Theme['tag']> = {
  349. ok: 'success',
  350. cancelled: 'warning',
  351. unknown: 'info',
  352. invalid_argument: 'warning',
  353. deadline_exceeded: 'error',
  354. not_found: 'warning',
  355. already_exists: 'warning',
  356. permission_denied: 'warning',
  357. resource_exhausted: 'warning',
  358. failed_precondition: 'warning',
  359. aborted: 'warning',
  360. out_of_range: 'warning',
  361. unimplemented: 'error',
  362. internal_error: 'error',
  363. unavailable: 'error',
  364. data_loss: 'error',
  365. unauthenticated: 'warning',
  366. };
  367. function statusToTagType(status: string) {
  368. return STATUS_TO_TAG_TYPE[status];
  369. }
  370. const OMITTED_SPAN_STATUS = ['unknown'];
  371. /**
  372. * This display a tag for the status (not to be confused with 'status_code' which has values like '200', '429').
  373. */
  374. export function StatusTag({status, onClick}: {status: string; onClick?: () => void}) {
  375. const tagType = statusToTagType(status);
  376. if (!tagType) {
  377. return null;
  378. }
  379. if (OMITTED_SPAN_STATUS.includes(status)) {
  380. return null;
  381. }
  382. return (
  383. <StyledTag type={tagType} onClick={onClick} borderStyle="solid">
  384. {status}
  385. </StyledTag>
  386. );
  387. }
  388. const StyledTag = styled(Tag)`
  389. cursor: ${p => (p.onClick ? 'pointer' : 'default')};
  390. `;
  391. const Description = styled('div')`
  392. ${p => p.theme.overflowEllipsis};
  393. display: flex;
  394. flex-direction: row;
  395. align-items: center;
  396. gap: ${space(1)};
  397. `;