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 trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  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. return (
  157. <TraceDetailHeader>
  158. <GuideAnchor target="trace_view_guide_breakdown">
  159. <MetaData
  160. headingText={t('Event Breakdown')}
  161. tooltipText={t(
  162. 'The number of transactions and errors there are in this trace.'
  163. )}
  164. bodyText={tct('[transactions] | [errors]', {
  165. transactions: tn(
  166. '%s Transaction',
  167. '%s Transactions',
  168. meta?.transactions ?? traceInfo.transactions.size
  169. ),
  170. errors: tn('%s Error', '%s Errors', meta?.errors ?? traceInfo.errors.size),
  171. })}
  172. subtext={tn(
  173. 'Across %s project',
  174. 'Across %s projects',
  175. meta?.projects ?? traceInfo.projects.size
  176. )}
  177. />
  178. </GuideAnchor>
  179. <MetaData
  180. headingText={t('Total Duration')}
  181. tooltipText={t('The time elapsed between the start and end of this trace.')}
  182. bodyText={getDuration(
  183. traceInfo.endTimestamp - traceInfo.startTimestamp,
  184. 2,
  185. true
  186. )}
  187. subtext={getDynamicText({
  188. value: <TimeSince date={(traceInfo.endTimestamp || 0) * 1000} />,
  189. fixed: '5 days ago',
  190. })}
  191. />
  192. </TraceDetailHeader>
  193. );
  194. }
  195. renderTraceWarnings() {
  196. const {traces} = this.props;
  197. const {roots, orphans} = (traces ?? []).reduce(
  198. (counts, trace) => {
  199. if (isRootTransaction(trace)) {
  200. counts.roots++;
  201. } else {
  202. counts.orphans++;
  203. }
  204. return counts;
  205. },
  206. {roots: 0, orphans: 0}
  207. );
  208. let warning: React.ReactNode = null;
  209. if (roots === 0 && orphans > 0) {
  210. warning = (
  211. <Alert type="info" showIcon>
  212. <ExternalLink href="https://docs.sentry.io/product/performance/trace-view/#orphan-traces-and-broken-subtraces">
  213. {t(
  214. 'A root transaction is missing. Transactions linked by a dashed line have been orphaned and cannot be directly linked to the root.'
  215. )}
  216. </ExternalLink>
  217. </Alert>
  218. );
  219. } else if (roots === 1 && orphans > 0) {
  220. warning = (
  221. <Alert type="info" showIcon>
  222. <ExternalLink href="https://docs.sentry.io/product/performance/trace-view/#orphan-traces-and-broken-subtraces">
  223. {t(
  224. 'This trace has broken subtraces. Transactions linked by a dashed line have been orphaned and cannot be directly linked to the root.'
  225. )}
  226. </ExternalLink>
  227. </Alert>
  228. );
  229. } else if (roots > 1) {
  230. warning = (
  231. <Alert type="info" showIcon>
  232. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/tracing/trace-view/#multiple-roots">
  233. {t('Multiple root transactions have been found with this trace ID.')}
  234. </ExternalLink>
  235. </Alert>
  236. );
  237. }
  238. return warning;
  239. }
  240. renderContent() {
  241. const {
  242. dateSelected,
  243. isLoading,
  244. error,
  245. organization,
  246. location,
  247. traceEventView,
  248. traceSlug,
  249. traces,
  250. meta,
  251. } = this.props;
  252. if (!dateSelected) {
  253. return this.renderTraceRequiresDateRangeSelection();
  254. }
  255. if (isLoading) {
  256. return this.renderTraceLoading();
  257. }
  258. if (error !== null || traces === null || traces.length <= 0) {
  259. return (
  260. <TraceNotFound
  261. meta={meta}
  262. traceEventView={traceEventView}
  263. traceSlug={traceSlug}
  264. location={location}
  265. organization={organization}
  266. />
  267. );
  268. }
  269. const traceInfo = getTraceInfo(traces);
  270. return (
  271. <Fragment>
  272. {this.renderTraceWarnings()}
  273. {this.renderTraceHeader(traceInfo)}
  274. {this.renderSearchBar()}
  275. <Margin>
  276. <VisuallyCompleteWithData
  277. id="PerformanceDetails-TraceView"
  278. hasData={!!traces.length}
  279. >
  280. <TraceView
  281. filteredTransactionIds={this.state.filteredTransactionIds}
  282. traceInfo={traceInfo}
  283. location={location}
  284. organization={organization}
  285. traceEventView={traceEventView}
  286. traceSlug={traceSlug}
  287. traces={traces}
  288. meta={meta}
  289. />
  290. </VisuallyCompleteWithData>
  291. </Margin>
  292. </Fragment>
  293. );
  294. }
  295. render() {
  296. const {organization, location, traceEventView, traceSlug} = this.props;
  297. return (
  298. <Fragment>
  299. <Layout.Header>
  300. <Layout.HeaderContent>
  301. <Breadcrumb
  302. organization={organization}
  303. location={location}
  304. traceSlug={traceSlug}
  305. />
  306. <Layout.Title data-test-id="trace-header">
  307. {t('Trace ID: %s', traceSlug)}
  308. </Layout.Title>
  309. </Layout.HeaderContent>
  310. <Layout.HeaderActions>
  311. <ButtonBar gap={1}>
  312. <DiscoverButton
  313. size="sm"
  314. to={traceEventView.getResultsViewUrlTarget(organization.slug)}
  315. onClick={() => {
  316. trackAdvancedAnalyticsEvent(
  317. 'performance_views.trace_view.open_in_discover',
  318. {
  319. organization,
  320. }
  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;