content.tsx 13 KB

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