sampleTable.tsx 11 KB

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