content.tsx 13 KB

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