sampleTable.tsx 9.8 KB

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