content.tsx 13 KB

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