sampleTable.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. import {Fragment, useCallback} from 'react';
  2. import {Link} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {PlatformIcon} from 'platformicons';
  5. import * as qs from 'query-string';
  6. import {LinkButton} from 'sentry/components/button';
  7. import DateTime from 'sentry/components/dateTime';
  8. import Duration from 'sentry/components/duration';
  9. import type {GridColumnHeader, GridColumnOrder} from 'sentry/components/gridEditable';
  10. import GridEditable, {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  11. import {extractSelectionParameters} from 'sentry/components/organizations/pageFilters/utils';
  12. import TextOverflow from 'sentry/components/textOverflow';
  13. import {Tooltip} from 'sentry/components/tooltip';
  14. import {CHART_PALETTE} from 'sentry/constants/chartPalette';
  15. import {IconArrow, IconProfiling} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import type {MRI} from 'sentry/types';
  19. import {generateEventSlug} from 'sentry/utils/discover/urls';
  20. import {getDuration} from 'sentry/utils/formatters';
  21. import type {MetricCorrelation, MetricRange} from 'sentry/utils/metrics/types';
  22. import {useCorrelatedSamples} from 'sentry/utils/metrics/useMetricsCodeLocations';
  23. import {getTransactionDetailsUrl} from 'sentry/utils/performance/urls';
  24. import {useLocation} from 'sentry/utils/useLocation';
  25. import useOrganization from 'sentry/utils/useOrganization';
  26. import useProjects from 'sentry/utils/useProjects';
  27. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  28. import ColorBar from 'sentry/views/performance/vitalDetail/colorBar';
  29. /**
  30. * Limits the number of spans to the top n + an "other" entry
  31. */
  32. function sortAndLimitSpans(samples: MetricCorrelation['spansSummary'], limit: number) {
  33. if (!samples) {
  34. return [];
  35. }
  36. const sortedSpans = [...samples].sort((a, b) => b.spanDuration - a.spanDuration);
  37. return sortedSpans.slice(0, limit).concat([
  38. {
  39. spanDuration: sortedSpans
  40. .slice(limit)
  41. .reduce((acc, span) => acc + span.spanDuration, 0),
  42. spanOp: `+${sortedSpans.length - limit} more`,
  43. },
  44. ]);
  45. }
  46. interface SamplesTableProps extends MetricRange {
  47. highlightedRow?: string | null;
  48. mri?: MRI;
  49. onRowHover?: (sampleId?: string) => void;
  50. query?: string;
  51. }
  52. type Column = GridColumnHeader<keyof MetricCorrelation>;
  53. const columnOrder: GridColumnOrder<keyof MetricCorrelation>[] = [
  54. {key: 'transactionId', width: COL_WIDTH_UNDEFINED, name: 'Event ID'},
  55. {key: 'segmentName', width: COL_WIDTH_UNDEFINED, name: 'Transaction'},
  56. {key: 'spansNumber', width: COL_WIDTH_UNDEFINED, name: 'Number of Spans'},
  57. {key: 'spansSummary', width: COL_WIDTH_UNDEFINED, name: 'Spans Summary'},
  58. {key: 'duration', width: COL_WIDTH_UNDEFINED, name: 'Duration'},
  59. {key: 'traceId', width: COL_WIDTH_UNDEFINED, name: 'Trace ID'},
  60. {key: 'timestamp', width: COL_WIDTH_UNDEFINED, name: 'Timestamp'},
  61. {key: 'profileId', width: COL_WIDTH_UNDEFINED, name: 'Profile'},
  62. ];
  63. export function SampleTable({
  64. mri,
  65. highlightedRow,
  66. onRowHover,
  67. ...metricMetaOptions
  68. }: SamplesTableProps) {
  69. const location = useLocation();
  70. const organization = useOrganization();
  71. const {projects} = useProjects();
  72. const {data, isFetching} = useCorrelatedSamples(mri, metricMetaOptions);
  73. const rows = data?.metrics
  74. .map(m => m.metricSpans)
  75. .flat()
  76. .filter(Boolean)
  77. // We only want to show the first 10 correlations
  78. .slice(0, 10) as MetricCorrelation[];
  79. function renderHeadCell(col: Column) {
  80. if (col.key === 'profileId') {
  81. return <AlignCenter>{col.name}</AlignCenter>;
  82. }
  83. if (col.key === 'duration') {
  84. return (
  85. <DurationHeadCell>
  86. {col.name}
  87. <IconArrow size="xs" direction="down" />
  88. </DurationHeadCell>
  89. );
  90. }
  91. return <span>{col.name}</span>;
  92. }
  93. function renderBodyCell(col: Column, row: MetricCorrelation) {
  94. const {key} = col;
  95. if (!row[key]) {
  96. return <AlignCenter>{'\u2014'}</AlignCenter>;
  97. }
  98. const project = projects.find(p => parseInt(p.id, 10) === row.projectId);
  99. const eventSlug = generateEventSlug({
  100. id: row.transactionId,
  101. project: project?.slug,
  102. });
  103. const highlighted = row.transactionId === highlightedRow;
  104. if (key === 'transactionId') {
  105. return (
  106. <BodyCell
  107. rowId={row.transactionId}
  108. onHover={onRowHover}
  109. highlighted={highlighted}
  110. >
  111. <Link
  112. to={getTransactionDetailsUrl(
  113. organization.slug,
  114. eventSlug,
  115. undefined,
  116. {referrer: 'metrics', openPanel: 'open'},
  117. row.spansDetails[0]?.spanId
  118. )}
  119. target="_blank"
  120. >
  121. {row.transactionId.slice(0, 8)}
  122. </Link>
  123. </BodyCell>
  124. );
  125. }
  126. if (key === 'segmentName') {
  127. return (
  128. <BodyCell
  129. rowId={row.transactionId}
  130. onHover={onRowHover}
  131. highlighted={highlighted}
  132. >
  133. <TextOverflow>
  134. <Tooltip title={project?.slug}>
  135. <StyledPlatformIcon platform={project?.platform || 'default'} />
  136. </Tooltip>
  137. <Link
  138. to={normalizeUrl(
  139. `/organizations/${organization.slug}/performance/summary/?${qs.stringify({
  140. ...extractSelectionParameters(location.query),
  141. project: project?.id,
  142. transaction: row.segmentName,
  143. referrer: 'metrics',
  144. })}`
  145. )}
  146. >
  147. {row.segmentName}
  148. </Link>
  149. </TextOverflow>
  150. </BodyCell>
  151. );
  152. }
  153. if (key === 'duration') {
  154. // We get duration in miliseconds, but getDuration expects seconds
  155. return (
  156. <BodyCell
  157. rowId={row.transactionId}
  158. onHover={onRowHover}
  159. highlighted={highlighted}
  160. >
  161. {getDuration(row.duration / 1000, 2, true)}
  162. </BodyCell>
  163. );
  164. }
  165. if (key === 'traceId') {
  166. return (
  167. <BodyCell
  168. rowId={row.transactionId}
  169. onHover={onRowHover}
  170. highlighted={highlighted}
  171. >
  172. <Link
  173. to={normalizeUrl(
  174. `/organizations/${organization.slug}/performance/trace/${row.traceId}/`
  175. )}
  176. >
  177. {row.traceId.slice(0, 8)}
  178. </Link>
  179. </BodyCell>
  180. );
  181. }
  182. if (key === 'spansSummary') {
  183. const totalDuration =
  184. row.spansSummary?.reduce(
  185. (acc, spanSummary) => acc + spanSummary.spanDuration,
  186. 0
  187. ) ?? 0;
  188. if (totalDuration === 0) {
  189. return <NoValue>{t('(no value)')}</NoValue>;
  190. }
  191. const preparedSpans = sortAndLimitSpans(row.spansSummary, 5);
  192. return (
  193. <StyledColorBar
  194. colorStops={preparedSpans.map((spanSummary, i) => {
  195. return {
  196. color: CHART_PALETTE[4][i % CHART_PALETTE.length],
  197. percent: (spanSummary.spanDuration / totalDuration) * 100,
  198. renderBarStatus: (barStatus, barKey) => (
  199. <Tooltip
  200. title={
  201. <Fragment>
  202. <div>{spanSummary.spanOp}</div>
  203. <div>
  204. <Duration
  205. seconds={spanSummary.spanDuration / 1000}
  206. fixedDigits={2}
  207. abbreviation
  208. />
  209. </div>
  210. </Fragment>
  211. }
  212. key={barKey}
  213. skipWrapper
  214. >
  215. {barStatus}
  216. </Tooltip>
  217. ),
  218. };
  219. })}
  220. />
  221. );
  222. }
  223. if (key === 'timestamp') {
  224. return (
  225. <BodyCell
  226. rowId={row.transactionId}
  227. onHover={onRowHover}
  228. highlighted={highlighted}
  229. >
  230. <DateTime date={row.timestamp} />
  231. </BodyCell>
  232. );
  233. }
  234. if (key === 'profileId') {
  235. return (
  236. <AlignCenter>
  237. <Tooltip title={t('View Profile')}>
  238. <LinkButton
  239. to={normalizeUrl(
  240. `/organizations/${organization.slug}/profiling/profile/${project?.slug}/${row.profileId}/flamegraph/`
  241. )}
  242. size="xs"
  243. >
  244. <IconProfiling size="xs" />
  245. </LinkButton>
  246. </Tooltip>
  247. </AlignCenter>
  248. );
  249. }
  250. return (
  251. <BodyCell rowId={row.transactionId} onHover={onRowHover} highlighted={highlighted}>
  252. {row[col.key]}
  253. </BodyCell>
  254. );
  255. }
  256. return (
  257. <Wrapper>
  258. <GridEditable
  259. isLoading={isFetching}
  260. columnOrder={columnOrder}
  261. columnSortBy={[]}
  262. data={rows}
  263. grid={{
  264. renderHeadCell,
  265. renderBodyCell,
  266. }}
  267. emptyMessage={mri ? t('No samples found') : t('Choose a metric to display data.')}
  268. location={location}
  269. />
  270. </Wrapper>
  271. );
  272. }
  273. function BodyCell({children, rowId, highlighted, onHover}: any) {
  274. const handleMouseOver = useCallback(() => {
  275. onHover(rowId);
  276. }, [onHover, rowId]);
  277. const handleMouseOut = useCallback(() => {
  278. onHover(null);
  279. }, [onHover]);
  280. return (
  281. <BodyCellWrapper
  282. onMouseOver={handleMouseOver}
  283. onMouseOut={handleMouseOut}
  284. highlighted={highlighted}
  285. >
  286. {children}
  287. </BodyCellWrapper>
  288. );
  289. }
  290. const Wrapper = styled('div')`
  291. tr:hover {
  292. td {
  293. background: ${p => p.theme.backgroundSecondary};
  294. }
  295. }
  296. `;
  297. const BodyCellWrapper = styled('span')<{highlighted?: boolean}>``;
  298. const AlignCenter = styled('span')`
  299. display: block;
  300. margin: auto;
  301. text-align: center;
  302. width: 100%;
  303. `;
  304. const DurationHeadCell = styled('span')`
  305. display: flex;
  306. gap: ${space(0.25)};
  307. `;
  308. const StyledPlatformIcon = styled(PlatformIcon)`
  309. margin-right: ${space(1)};
  310. height: ${space(3)};
  311. `;
  312. const StyledColorBar = styled(ColorBar)`
  313. margin-bottom: 0px;
  314. `;
  315. const NoValue = styled('span')`
  316. color: ${p => p.theme.gray300};
  317. `;