content.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374
  1. import {Component, createRef, Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {Alert} from 'sentry/components/alert';
  5. import GuideAnchor from 'sentry/components/assistant/guideAnchor';
  6. import ButtonBar from 'sentry/components/buttonBar';
  7. import DiscoverButton from 'sentry/components/discoverButton';
  8. import * as Layout from 'sentry/components/layouts/thirds';
  9. import ExternalLink from 'sentry/components/links/externalLink';
  10. import LoadingError from 'sentry/components/loadingError';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import TimeSince from 'sentry/components/timeSince';
  13. import {t, tct, tn} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import {Organization} from 'sentry/types';
  16. import {defined} from 'sentry/utils';
  17. import {trackAnalytics} from 'sentry/utils/analytics';
  18. import EventView from 'sentry/utils/discover/eventView';
  19. import {QueryError} from 'sentry/utils/discover/genericDiscoverQuery';
  20. import {getDuration} from 'sentry/utils/formatters';
  21. import {createFuzzySearch, Fuse} from 'sentry/utils/fuzzySearch';
  22. import getDynamicText from 'sentry/utils/getDynamicText';
  23. import {TraceFullDetailed, TraceMeta} from 'sentry/utils/performance/quickTrace/types';
  24. import {filterTrace, reduceTrace} from 'sentry/utils/performance/quickTrace/utils';
  25. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  26. import Breadcrumb from 'sentry/views/performance/breadcrumb';
  27. import {MetaData} from 'sentry/views/performance/transactionDetails/styles';
  28. import {TraceDetailHeader, TraceSearchBar, TraceSearchContainer} from './styles';
  29. import TraceNotFound from './traceNotFound';
  30. import TraceView from './traceView';
  31. import {TraceInfo} from './types';
  32. import {getTraceInfo, isRootTransaction} from './utils';
  33. type IndexedFusedTransaction = {
  34. indexed: string[];
  35. transaction: TraceFullDetailed;
  36. };
  37. type Props = Pick<RouteComponentProps<{traceSlug: string}, {}>, 'params' | 'location'> & {
  38. dateSelected: boolean;
  39. error: QueryError | null;
  40. isLoading: boolean;
  41. meta: TraceMeta | null;
  42. organization: Organization;
  43. traceEventView: EventView;
  44. traceSlug: string;
  45. traces: TraceFullDetailed[] | null;
  46. };
  47. type State = {
  48. filteredTransactionIds: Set<string> | undefined;
  49. searchQuery: string | undefined;
  50. };
  51. class TraceDetailsContent extends Component<Props, State> {
  52. state: State = {
  53. searchQuery: undefined,
  54. filteredTransactionIds: undefined,
  55. };
  56. componentDidMount() {
  57. this.initFuse();
  58. }
  59. componentDidUpdate(prevProps: Props) {
  60. if (this.props.traces !== prevProps.traces) {
  61. this.initFuse();
  62. }
  63. }
  64. fuse: Fuse<IndexedFusedTransaction> | null = null;
  65. traceViewRef = createRef<HTMLDivElement>();
  66. virtualScrollbarContainerRef = createRef<HTMLDivElement>();
  67. async initFuse() {
  68. if (defined(this.props.traces) && this.props.traces.length > 0) {
  69. const transformed: IndexedFusedTransaction[] = this.props.traces.flatMap(trace =>
  70. reduceTrace<IndexedFusedTransaction[]>(
  71. trace,
  72. (acc, transaction) => {
  73. const indexed: string[] = [
  74. transaction['transaction.op'],
  75. transaction.transaction,
  76. transaction.project_slug,
  77. ];
  78. acc.push({
  79. transaction,
  80. indexed,
  81. });
  82. return acc;
  83. },
  84. []
  85. )
  86. );
  87. this.fuse = await createFuzzySearch(transformed, {
  88. keys: ['indexed'],
  89. includeMatches: true,
  90. threshold: 0.6,
  91. location: 0,
  92. distance: 100,
  93. maxPatternLength: 32,
  94. });
  95. }
  96. }
  97. renderTraceLoading() {
  98. return <LoadingIndicator />;
  99. }
  100. renderTraceRequiresDateRangeSelection() {
  101. return <LoadingError message={t('Trace view requires a date range selection.')} />;
  102. }
  103. handleTransactionFilter = (searchQuery: string) => {
  104. this.setState({searchQuery: searchQuery || undefined}, this.filterTransactions);
  105. };
  106. filterTransactions = () => {
  107. const {traces} = this.props;
  108. const {filteredTransactionIds, searchQuery} = this.state;
  109. if (!searchQuery || traces === null || traces.length <= 0 || !defined(this.fuse)) {
  110. if (filteredTransactionIds !== undefined) {
  111. this.setState({
  112. filteredTransactionIds: undefined,
  113. });
  114. }
  115. return;
  116. }
  117. const fuseMatches = this.fuse
  118. .search<IndexedFusedTransaction>(searchQuery)
  119. /**
  120. * Sometimes, there can be matches that don't include any
  121. * indices. These matches are often noise, so exclude them.
  122. */
  123. .filter(({matches}) => matches?.length)
  124. .map(({item}) => item.transaction.event_id);
  125. /**
  126. * Fuzzy search on ids result in seemingly random results. So switch to
  127. * doing substring matches on ids to provide more meaningful results.
  128. */
  129. const idMatches = traces
  130. .flatMap(trace =>
  131. filterTrace(
  132. trace,
  133. ({event_id, span_id}) =>
  134. event_id.includes(searchQuery) || span_id.includes(searchQuery)
  135. )
  136. )
  137. .map(transaction => transaction.event_id);
  138. this.setState({
  139. filteredTransactionIds: new Set([...fuseMatches, ...idMatches]),
  140. });
  141. };
  142. renderSearchBar() {
  143. return (
  144. <TraceSearchContainer>
  145. <TraceSearchBar
  146. defaultQuery=""
  147. query={this.state.searchQuery || ''}
  148. placeholder={t('Search for transactions')}
  149. onSearch={this.handleTransactionFilter}
  150. />
  151. </TraceSearchContainer>
  152. );
  153. }
  154. renderTraceHeader(traceInfo: TraceInfo) {
  155. const {meta} = this.props;
  156. const errors = meta?.errors ?? traceInfo.errors.size;
  157. const performanceIssues =
  158. meta?.performance_issues ?? traceInfo.performanceIssues.size;
  159. return (
  160. <TraceDetailHeader>
  161. <GuideAnchor target="trace_view_guide_breakdown">
  162. <MetaData
  163. headingText={t('Event Breakdown')}
  164. tooltipText={t(
  165. 'The number of transactions and issues there are in this trace.'
  166. )}
  167. bodyText={tct('[transactions] | [errors]', {
  168. transactions: tn(
  169. '%s Transaction',
  170. '%s Transactions',
  171. meta?.transactions ?? traceInfo.transactions.size
  172. ),
  173. errors: tn('%s Issue', '%s Issues', errors + performanceIssues),
  174. })}
  175. subtext={tn(
  176. 'Across %s project',
  177. 'Across %s projects',
  178. meta?.projects ?? traceInfo.projects.size
  179. )}
  180. />
  181. </GuideAnchor>
  182. <MetaData
  183. headingText={t('Total Duration')}
  184. tooltipText={t('The time elapsed between the start and end of this trace.')}
  185. bodyText={getDuration(
  186. traceInfo.endTimestamp - traceInfo.startTimestamp,
  187. 2,
  188. true
  189. )}
  190. subtext={getDynamicText({
  191. value: <TimeSince date={(traceInfo.endTimestamp || 0) * 1000} />,
  192. fixed: '5 days ago',
  193. })}
  194. />
  195. </TraceDetailHeader>
  196. );
  197. }
  198. renderTraceWarnings() {
  199. const {traces} = this.props;
  200. const {roots, orphans} = (traces ?? []).reduce(
  201. (counts, trace) => {
  202. if (isRootTransaction(trace)) {
  203. counts.roots++;
  204. } else {
  205. counts.orphans++;
  206. }
  207. return counts;
  208. },
  209. {roots: 0, orphans: 0}
  210. );
  211. let warning: React.ReactNode = null;
  212. if (roots === 0 && orphans > 0) {
  213. warning = (
  214. <Alert type="info" showIcon>
  215. <ExternalLink href="https://docs.sentry.io/product/performance/trace-view/#orphan-traces-and-broken-subtraces">
  216. {t(
  217. 'A root transaction is missing. Transactions linked by a dashed line have been orphaned and cannot be directly linked to the root.'
  218. )}
  219. </ExternalLink>
  220. </Alert>
  221. );
  222. } else if (roots === 1 && orphans > 0) {
  223. warning = (
  224. <Alert type="info" showIcon>
  225. <ExternalLink href="https://docs.sentry.io/product/performance/trace-view/#orphan-traces-and-broken-subtraces">
  226. {t(
  227. 'This trace has broken subtraces. Transactions linked by a dashed line have been orphaned and cannot be directly linked to the root.'
  228. )}
  229. </ExternalLink>
  230. </Alert>
  231. );
  232. } else if (roots > 1) {
  233. warning = (
  234. <Alert type="info" showIcon>
  235. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/tracing/trace-view/#multiple-roots">
  236. {t('Multiple root transactions have been found with this trace ID.')}
  237. </ExternalLink>
  238. </Alert>
  239. );
  240. }
  241. return warning;
  242. }
  243. renderContent() {
  244. const {
  245. dateSelected,
  246. isLoading,
  247. error,
  248. organization,
  249. location,
  250. traceEventView,
  251. traceSlug,
  252. traces,
  253. meta,
  254. } = this.props;
  255. if (!dateSelected) {
  256. return this.renderTraceRequiresDateRangeSelection();
  257. }
  258. if (isLoading) {
  259. return this.renderTraceLoading();
  260. }
  261. if (error !== null || traces === null || traces.length <= 0) {
  262. return (
  263. <TraceNotFound
  264. meta={meta}
  265. traceEventView={traceEventView}
  266. traceSlug={traceSlug}
  267. location={location}
  268. organization={organization}
  269. />
  270. );
  271. }
  272. const traceInfo = getTraceInfo(traces);
  273. return (
  274. <Fragment>
  275. {this.renderTraceWarnings()}
  276. {this.renderTraceHeader(traceInfo)}
  277. {this.renderSearchBar()}
  278. <Margin>
  279. <VisuallyCompleteWithData
  280. id="PerformanceDetails-TraceView"
  281. hasData={!!traces.length}
  282. >
  283. <TraceView
  284. filteredTransactionIds={this.state.filteredTransactionIds}
  285. traceInfo={traceInfo}
  286. location={location}
  287. organization={organization}
  288. traceEventView={traceEventView}
  289. traceSlug={traceSlug}
  290. traces={traces}
  291. meta={meta}
  292. />
  293. </VisuallyCompleteWithData>
  294. </Margin>
  295. </Fragment>
  296. );
  297. }
  298. render() {
  299. const {organization, location, traceEventView, traceSlug} = this.props;
  300. return (
  301. <Fragment>
  302. <Layout.Header>
  303. <Layout.HeaderContent>
  304. <Breadcrumb
  305. organization={organization}
  306. location={location}
  307. traceSlug={traceSlug}
  308. />
  309. <Layout.Title data-test-id="trace-header">
  310. {t('Trace ID: %s', traceSlug)}
  311. </Layout.Title>
  312. </Layout.HeaderContent>
  313. <Layout.HeaderActions>
  314. <ButtonBar gap={1}>
  315. <DiscoverButton
  316. size="sm"
  317. to={traceEventView.getResultsViewUrlTarget(organization.slug)}
  318. onClick={() => {
  319. trackAnalytics('performance_views.trace_view.open_in_discover', {
  320. organization,
  321. });
  322. }}
  323. >
  324. {t('Open in Discover')}
  325. </DiscoverButton>
  326. </ButtonBar>
  327. </Layout.HeaderActions>
  328. </Layout.Header>
  329. <Layout.Body>
  330. <Layout.Main fullWidth>{this.renderContent()}</Layout.Main>
  331. </Layout.Body>
  332. </Fragment>
  333. );
  334. }
  335. }
  336. const Margin = styled('div')`
  337. margin-top: ${space(2)};
  338. `;
  339. export default TraceDetailsContent;