spanSummaryTable.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import {Fragment, useCallback, useMemo} from 'react';
  2. import styled from '@emotion/styled';
  3. import type {Location} from 'history';
  4. import SearchBar from 'sentry/components/events/searchBar';
  5. import type {GridColumnHeader} from 'sentry/components/gridEditable';
  6. import GridEditable, {COL_WIDTH_UNDEFINED} from 'sentry/components/gridEditable';
  7. import Pagination, {type CursorHandler} from 'sentry/components/pagination';
  8. import {SpanSearchQueryBuilder} from 'sentry/components/performance/spanSearchQueryBuilder';
  9. import {ROW_HEIGHT, ROW_PADDING} from 'sentry/components/performance/waterfall/constants';
  10. import PerformanceDuration from 'sentry/components/performanceDuration';
  11. import {Tooltip} from 'sentry/components/tooltip';
  12. import {t} from 'sentry/locale';
  13. import {space} from 'sentry/styles/space';
  14. import type {Organization} from 'sentry/types/organization';
  15. import type {Project} from 'sentry/types/project';
  16. import {defined} from 'sentry/utils';
  17. import {browserHistory} from 'sentry/utils/browserHistory';
  18. import EventView, {type MetaType} from 'sentry/utils/discover/eventView';
  19. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  20. import type {ColumnType} from 'sentry/utils/discover/fields';
  21. import {
  22. type DiscoverQueryProps,
  23. useGenericDiscoverQuery,
  24. } from 'sentry/utils/discover/genericDiscoverQuery';
  25. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  26. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  27. import {decodeScalar} from 'sentry/utils/queryString';
  28. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  29. import {useLocation} from 'sentry/utils/useLocation';
  30. import {useNavigate} from 'sentry/utils/useNavigate';
  31. import useOrganization from 'sentry/utils/useOrganization';
  32. import {useParams} from 'sentry/utils/useParams';
  33. import {renderHeadCell} from 'sentry/views/insights/common/components/tableCells/renderHeadCell';
  34. import {SpanIdCell} from 'sentry/views/insights/common/components/tableCells/spanIdCell';
  35. import {useSpansIndexed} from 'sentry/views/insights/common/queries/useDiscover';
  36. import {QueryParameterNames} from 'sentry/views/insights/common/views/queryParameters';
  37. import {
  38. ModuleName,
  39. SpanIndexedField,
  40. type SpanIndexedResponse,
  41. type SpanMetricsQueryFilters,
  42. } from 'sentry/views/insights/types';
  43. import {TraceViewSources} from 'sentry/views/performance/newTraceDetails/traceMetadataHeader';
  44. import {SpanDurationBar} from 'sentry/views/performance/transactionSummary/transactionSpans/spanDetails/spanDetailsTable';
  45. import {SpanSummaryReferrer} from 'sentry/views/performance/transactionSummary/transactionSpans/spanSummary/referrers';
  46. import {useSpanSummarySort} from 'sentry/views/performance/transactionSummary/transactionSpans/spanSummary/useSpanSummarySort';
  47. import {useSpanFieldSupportedTags} from 'sentry/views/performance/utils/useSpanFieldSupportedTags';
  48. import Tab from '../../tabs';
  49. type DataRowKeys =
  50. | SpanIndexedField.ID
  51. | SpanIndexedField.TIMESTAMP
  52. | SpanIndexedField.SPAN_DURATION
  53. | SpanIndexedField.TRANSACTION_ID
  54. | SpanIndexedField.TRACE
  55. | SpanIndexedField.PROJECT;
  56. type ColumnKeys =
  57. | SpanIndexedField.ID
  58. | SpanIndexedField.TIMESTAMP
  59. | SpanIndexedField.SPAN_DURATION;
  60. type DataRow = Pick<SpanIndexedResponse, DataRowKeys> & {'transaction.duration': number};
  61. type Column = GridColumnHeader<ColumnKeys>;
  62. const COLUMN_ORDER: Column[] = [
  63. {
  64. key: SpanIndexedField.ID,
  65. name: t('Span ID'),
  66. width: COL_WIDTH_UNDEFINED,
  67. },
  68. {
  69. key: SpanIndexedField.TIMESTAMP,
  70. name: t('Timestamp'),
  71. width: COL_WIDTH_UNDEFINED,
  72. },
  73. {
  74. key: SpanIndexedField.SPAN_DURATION,
  75. name: t('Span Duration'),
  76. width: COL_WIDTH_UNDEFINED,
  77. },
  78. ];
  79. const COLUMN_TYPE: Omit<
  80. Record<ColumnKeys, ColumnType>,
  81. 'spans' | 'transactionDuration'
  82. > = {
  83. span_id: 'string',
  84. timestamp: 'date',
  85. 'span.duration': 'duration',
  86. };
  87. const LIMIT = 8;
  88. type Props = {
  89. project: Project | undefined;
  90. };
  91. export default function SpanSummaryTable(props: Props) {
  92. const {project} = props;
  93. const organization = useOrganization();
  94. const supportedTags = useSpanFieldSupportedTags();
  95. const {spanSlug} = useParams();
  96. const navigate = useNavigate();
  97. const [spanOp, groupId] = spanSlug.split(':');
  98. const location = useLocation();
  99. const {transaction} = location.query;
  100. const spansCursor = decodeScalar(location.query?.[QueryParameterNames.SPANS_CURSOR]);
  101. const spansQuery = decodeScalar(location.query.spansQuery, '');
  102. const filters: SpanMetricsQueryFilters = {
  103. 'span.group': groupId,
  104. 'span.op': spanOp,
  105. transaction: transaction as string,
  106. };
  107. const sort = useSpanSummarySort();
  108. const spanSearchString = new MutableSearch(spansQuery).formatString();
  109. const search = MutableSearch.fromQueryObject(filters);
  110. search.addStringMultiFilter(spanSearchString);
  111. const {
  112. data: rowData,
  113. pageLinks,
  114. isPending: isRowDataLoading,
  115. } = useSpansIndexed(
  116. {
  117. fields: [
  118. SpanIndexedField.ID,
  119. SpanIndexedField.TRANSACTION_ID,
  120. SpanIndexedField.TIMESTAMP,
  121. SpanIndexedField.SPAN_DURATION,
  122. SpanIndexedField.TRACE,
  123. SpanIndexedField.PROJECT,
  124. ],
  125. search,
  126. limit: LIMIT,
  127. sorts: [sort],
  128. cursor: spansCursor,
  129. },
  130. SpanSummaryReferrer.SPAN_SUMMARY_TABLE
  131. );
  132. const transactionIds = rowData?.map(row => row[SpanIndexedField.TRANSACTION_ID]);
  133. const eventView = EventView.fromNewQueryWithLocation(
  134. {
  135. name: 'Transaction Durations',
  136. query: MutableSearch.fromQueryObject({
  137. project: project?.slug,
  138. id: `[${transactionIds?.join() ?? ''}]`,
  139. }).formatString(),
  140. fields: ['id', 'transaction.duration'],
  141. version: 2,
  142. },
  143. location
  144. );
  145. const {
  146. isPending: isTxnDurationDataLoading,
  147. data: txnDurationData,
  148. isError: isTxnDurationError,
  149. } = useGenericDiscoverQuery<
  150. {
  151. data: any[];
  152. meta: MetaType;
  153. },
  154. DiscoverQueryProps
  155. >({
  156. route: 'events',
  157. eventView,
  158. location,
  159. orgSlug: organization.slug,
  160. getRequestPayload: () => ({
  161. ...eventView.getEventsAPIPayload(location),
  162. interval: eventView.interval,
  163. }),
  164. limit: LIMIT,
  165. options: {
  166. refetchOnWindowFocus: false,
  167. enabled: Boolean(rowData && rowData.length > 0),
  168. },
  169. referrer: SpanSummaryReferrer.SPAN_SUMMARY_TABLE,
  170. });
  171. // Restructure the transaction durations into a map for faster lookup
  172. const transactionDurationMap = {};
  173. txnDurationData?.data.forEach(datum => {
  174. transactionDurationMap[datum.id] = datum['transaction.duration'];
  175. });
  176. const mergedData: DataRow[] =
  177. rowData?.map((row: Pick<SpanIndexedResponse, DataRowKeys>) => {
  178. const transactionId = row[SpanIndexedField.TRANSACTION_ID];
  179. const newRow = {
  180. ...row,
  181. 'transaction.duration': transactionDurationMap[transactionId],
  182. };
  183. return newRow;
  184. }) ?? [];
  185. const handleCursor: CursorHandler = (cursor, pathname, query) => {
  186. browserHistory.push({
  187. pathname,
  188. query: {...query, [QueryParameterNames.SPANS_CURSOR]: cursor},
  189. });
  190. };
  191. const handleSearch = useCallback(
  192. (searchString: string) => {
  193. navigate({
  194. ...location,
  195. query: {
  196. ...location.query,
  197. spansQuery: new MutableSearch(searchString).formatString(),
  198. },
  199. });
  200. },
  201. [location, navigate]
  202. );
  203. const projectIds = useMemo(() => eventView.project.slice(), [eventView]);
  204. return (
  205. <Fragment>
  206. <StyledSearchBarWrapper>
  207. {organization.features.includes('search-query-builder-performance') ? (
  208. <SpanSearchQueryBuilder
  209. projects={projectIds}
  210. initialQuery={spansQuery}
  211. onSearch={handleSearch}
  212. searchSource="transaction_span_summary"
  213. />
  214. ) : (
  215. <SearchBar
  216. organization={organization}
  217. projectIds={eventView.project}
  218. query={spansQuery}
  219. fields={eventView.fields}
  220. placeholder={t('Search for span attributes')}
  221. supportedTags={supportedTags}
  222. dataset={DiscoverDatasets.SPANS_INDEXED}
  223. onSearch={handleSearch}
  224. />
  225. )}
  226. </StyledSearchBarWrapper>
  227. <VisuallyCompleteWithData
  228. id="SpanDetails-SpanDetailsTable"
  229. hasData={!!mergedData?.length}
  230. isLoading={isRowDataLoading}
  231. >
  232. <GridEditable
  233. isLoading={isRowDataLoading}
  234. data={mergedData}
  235. columnOrder={COLUMN_ORDER}
  236. columnSortBy={[
  237. {
  238. key: sort.field,
  239. order: sort.kind,
  240. },
  241. ]}
  242. grid={{
  243. renderHeadCell: column =>
  244. renderHeadCell({
  245. column,
  246. location,
  247. sort,
  248. }),
  249. renderBodyCell: renderBodyCell(
  250. location,
  251. organization,
  252. spanOp,
  253. isTxnDurationDataLoading || isTxnDurationError
  254. ),
  255. }}
  256. />
  257. </VisuallyCompleteWithData>
  258. <Pagination pageLinks={pageLinks} onCursor={handleCursor} />
  259. </Fragment>
  260. );
  261. }
  262. function renderBodyCell(
  263. location: Location,
  264. organization: Organization,
  265. spanOp: string = '',
  266. isTxnDurationDataLoading: boolean
  267. ) {
  268. return function (column: Column, dataRow: DataRow): React.ReactNode {
  269. const {timestamp, span_id, trace, project} = dataRow;
  270. const spanDuration = dataRow[SpanIndexedField.SPAN_DURATION];
  271. const transactionId = dataRow[SpanIndexedField.TRANSACTION_ID];
  272. const transactionDuration = dataRow['transaction.duration'];
  273. if (column.key === SpanIndexedField.SPAN_DURATION) {
  274. if (isTxnDurationDataLoading) {
  275. return <EmptySpanDurationBar />;
  276. }
  277. if (!transactionDuration) {
  278. return (
  279. <EmptySpanDurationBar>
  280. <Tooltip
  281. title={t('Transaction duration unknown')}
  282. containerDisplayMode="block"
  283. >
  284. <PerformanceDuration abbreviation milliseconds={spanDuration} />
  285. </Tooltip>
  286. </EmptySpanDurationBar>
  287. );
  288. }
  289. return (
  290. <SpanDurationBar
  291. spanOp={spanOp}
  292. spanDuration={spanDuration}
  293. transactionDuration={transactionDuration}
  294. />
  295. );
  296. }
  297. if (column.key === SpanIndexedField.ID) {
  298. if (!defined(span_id)) {
  299. return null;
  300. }
  301. return (
  302. <SpanIdCell
  303. moduleName={ModuleName.OTHER}
  304. projectSlug={project}
  305. spanId={span_id}
  306. timestamp={timestamp}
  307. traceId={trace}
  308. transactionId={transactionId}
  309. location={{
  310. ...location,
  311. query: {
  312. ...location.query,
  313. tab: Tab.SPANS,
  314. spanSlug: `${spanOp}:${transactionId}`,
  315. },
  316. }}
  317. source={TraceViewSources.PERFORMANCE_TRANSACTION_SUMMARY}
  318. />
  319. );
  320. }
  321. const fieldRenderer = getFieldRenderer(column.key, COLUMN_TYPE);
  322. const rendered = fieldRenderer(dataRow, {location, organization});
  323. return rendered;
  324. };
  325. }
  326. const EmptySpanDurationBar = styled('div')`
  327. height: ${ROW_HEIGHT - 2 * ROW_PADDING}px;
  328. width: 100%;
  329. position: relative;
  330. display: flex;
  331. align-items: center;
  332. top: ${space(0.5)};
  333. background-color: ${p => p.theme.gray100};
  334. padding-left: ${space(1)};
  335. color: ${p => p.theme.gray300};
  336. font-size: ${p => p.theme.fontSizeExtraSmall};
  337. font-variant-numeric: tabular-nums;
  338. line-height: 1;
  339. `;
  340. const StyledSearchBarWrapper = styled('div')`
  341. margin-bottom: ${space(2)};
  342. `;