sampleTable.tsx 11 KB

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