sampleTable.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  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 {trackAnalytics} from 'sentry/utils/analytics';
  20. import {getDuration} from 'sentry/utils/formatters';
  21. import {getMetricsCorrelationSpanUrl} from 'sentry/utils/metrics';
  22. import type {MetricCorrelation, SelectionRange} from 'sentry/utils/metrics/types';
  23. import {useCorrelatedSamples} from 'sentry/utils/metrics/useMetricsCodeLocations';
  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 SelectionRange {
  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 trackClick(target: 'event-id' | 'transaction' | 'trace-id' | 'profile') {
  80. trackAnalytics('ddm.sample-table-interaction', {
  81. organization,
  82. target,
  83. });
  84. }
  85. function renderHeadCell(col: Column) {
  86. if (col.key === 'profileId') {
  87. return <AlignCenter>{col.name}</AlignCenter>;
  88. }
  89. if (col.key === 'duration') {
  90. return (
  91. <DurationHeadCell>
  92. {col.name}
  93. <IconArrow size="xs" direction="down" />
  94. </DurationHeadCell>
  95. );
  96. }
  97. return <span>{col.name}</span>;
  98. }
  99. function renderBodyCell(col: Column, row: MetricCorrelation) {
  100. const {key} = col;
  101. if (!row[key]) {
  102. return <AlignCenter>{'\u2014'}</AlignCenter>;
  103. }
  104. const project = projects.find(p => parseInt(p.id, 10) === row.projectId);
  105. const highlighted = row.transactionId === highlightedRow;
  106. if (key === 'transactionId') {
  107. return (
  108. <BodyCell
  109. rowId={row.transactionId}
  110. onHover={onRowHover}
  111. highlighted={highlighted}
  112. >
  113. <Link
  114. to={getMetricsCorrelationSpanUrl(
  115. organization,
  116. project?.slug,
  117. row.spansDetails[0]?.spanId,
  118. row.transactionId,
  119. row.transactionSpanId
  120. )}
  121. onClick={() => trackClick('event-id')}
  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. onClick={() => trackClick('transaction')}
  150. >
  151. {row.segmentName}
  152. </Link>
  153. </TextOverflow>
  154. </BodyCell>
  155. );
  156. }
  157. if (key === 'duration') {
  158. // We get duration in miliseconds, but getDuration expects seconds
  159. return (
  160. <BodyCell
  161. rowId={row.transactionId}
  162. onHover={onRowHover}
  163. highlighted={highlighted}
  164. >
  165. {getDuration(row.duration / 1000, 2, true)}
  166. </BodyCell>
  167. );
  168. }
  169. if (key === 'traceId') {
  170. return (
  171. <BodyCell
  172. rowId={row.transactionId}
  173. onHover={onRowHover}
  174. highlighted={highlighted}
  175. >
  176. <Link
  177. to={normalizeUrl(
  178. `/organizations/${organization.slug}/performance/trace/${row.traceId}/`
  179. )}
  180. onClick={() => trackClick('trace-id')}
  181. >
  182. {row.traceId.slice(0, 8)}
  183. </Link>
  184. </BodyCell>
  185. );
  186. }
  187. if (key === 'spansSummary') {
  188. const totalDuration =
  189. row.spansSummary?.reduce(
  190. (acc, spanSummary) => acc + spanSummary.spanDuration,
  191. 0
  192. ) ?? 0;
  193. if (totalDuration === 0) {
  194. return <NoValue>{t('(no value)')}</NoValue>;
  195. }
  196. const preparedSpans = sortAndLimitSpans(row.spansSummary, 5);
  197. return (
  198. <StyledColorBar
  199. colorStops={preparedSpans.map((spanSummary, i) => {
  200. return {
  201. color: CHART_PALETTE[4][i % CHART_PALETTE.length],
  202. percent: (spanSummary.spanDuration / totalDuration) * 100,
  203. renderBarStatus: (barStatus, barKey) => (
  204. <Tooltip
  205. title={
  206. <Fragment>
  207. <div>{spanSummary.spanOp}</div>
  208. <div>
  209. <Duration
  210. seconds={spanSummary.spanDuration / 1000}
  211. fixedDigits={2}
  212. abbreviation
  213. />
  214. </div>
  215. </Fragment>
  216. }
  217. key={barKey}
  218. skipWrapper
  219. >
  220. {barStatus}
  221. </Tooltip>
  222. ),
  223. };
  224. })}
  225. />
  226. );
  227. }
  228. if (key === 'timestamp') {
  229. return (
  230. <BodyCell
  231. rowId={row.transactionId}
  232. onHover={onRowHover}
  233. highlighted={highlighted}
  234. >
  235. <DateTime date={row.timestamp} />
  236. </BodyCell>
  237. );
  238. }
  239. if (key === 'profileId') {
  240. return (
  241. <AlignCenter>
  242. <Tooltip title={t('View Profile')}>
  243. <LinkButton
  244. to={normalizeUrl(
  245. `/organizations/${organization.slug}/profiling/profile/${project?.slug}/${row.profileId}/flamegraph/`
  246. )}
  247. onClick={() => trackClick('profile')}
  248. size="xs"
  249. >
  250. <IconProfiling size="xs" />
  251. </LinkButton>
  252. </Tooltip>
  253. </AlignCenter>
  254. );
  255. }
  256. return (
  257. <BodyCell rowId={row.transactionId} onHover={onRowHover} highlighted={highlighted}>
  258. {row[col.key]}
  259. </BodyCell>
  260. );
  261. }
  262. return (
  263. <Wrapper>
  264. <GridEditable
  265. isLoading={isFetching}
  266. columnOrder={columnOrder}
  267. columnSortBy={[]}
  268. data={rows}
  269. grid={{
  270. renderHeadCell,
  271. renderBodyCell,
  272. }}
  273. emptyMessage={mri ? t('No samples found') : t('Choose a metric to display data.')}
  274. location={location}
  275. />
  276. </Wrapper>
  277. );
  278. }
  279. function BodyCell({children, rowId, highlighted, onHover}: any) {
  280. const handleMouseOver = useCallback(() => {
  281. onHover(rowId);
  282. }, [onHover, rowId]);
  283. const handleMouseOut = useCallback(() => {
  284. onHover(null);
  285. }, [onHover]);
  286. return (
  287. <BodyCellWrapper
  288. onMouseOver={handleMouseOver}
  289. onMouseOut={handleMouseOut}
  290. highlighted={highlighted}
  291. >
  292. {children}
  293. </BodyCellWrapper>
  294. );
  295. }
  296. const Wrapper = styled('div')`
  297. tr:hover {
  298. td {
  299. background: ${p => p.theme.backgroundSecondary};
  300. }
  301. }
  302. `;
  303. const BodyCellWrapper = styled('span')<{highlighted?: boolean}>``;
  304. const AlignCenter = styled('span')`
  305. display: block;
  306. margin: auto;
  307. text-align: center;
  308. width: 100%;
  309. `;
  310. const DurationHeadCell = styled('span')`
  311. display: flex;
  312. gap: ${space(0.25)};
  313. `;
  314. const StyledPlatformIcon = styled(PlatformIcon)`
  315. margin-right: ${space(1)};
  316. height: ${space(3)};
  317. `;
  318. const StyledColorBar = styled(ColorBar)`
  319. margin-bottom: 0px;
  320. `;
  321. const NoValue = styled('span')`
  322. color: ${p => p.theme.gray300};
  323. `;