content.tsx 11 KB

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