sampleTable.tsx 11 KB

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