content.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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 events')}
  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. if (roots === 0 && orphans > 0) {
  240. warning = (
  241. <Alert type="info" showIcon>
  242. <ExternalLink href="https://docs.sentry.io/product/performance/trace-view/#orphan-traces-and-broken-subtraces">
  243. {t(
  244. 'A root transaction is missing. Transactions linked by a dashed line have been orphaned and cannot be directly linked to the root.'
  245. )}
  246. </ExternalLink>
  247. </Alert>
  248. );
  249. } else if (roots === 1 && orphans > 0) {
  250. warning = (
  251. <Alert type="info" showIcon>
  252. <ExternalLink href="https://docs.sentry.io/product/performance/trace-view/#orphan-traces-and-broken-subtraces">
  253. {t(
  254. 'This trace has broken subtraces. Transactions linked by a dashed line have been orphaned and cannot be directly linked to the root.'
  255. )}
  256. </ExternalLink>
  257. </Alert>
  258. );
  259. } else if (roots > 1) {
  260. warning = (
  261. <Alert type="info" showIcon>
  262. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/tracing/trace-view/#multiple-roots">
  263. {t('Multiple root transactions have been found with this trace ID.')}
  264. </ExternalLink>
  265. </Alert>
  266. );
  267. } else if (orphanErrors && orphanErrors.length > 1) {
  268. warning = (
  269. <Alert type="info" showIcon>
  270. {tct(
  271. "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.",
  272. {
  273. tracingLink: (
  274. <ExternalLink href="https://docs.sentry.io/product/performance/getting-started/" />
  275. ),
  276. }
  277. )}
  278. </Alert>
  279. );
  280. }
  281. return warning;
  282. }
  283. renderContent() {
  284. const {
  285. dateSelected,
  286. isLoading,
  287. error,
  288. organization,
  289. location,
  290. traceEventView,
  291. traceSlug,
  292. traces,
  293. meta,
  294. orphanErrors,
  295. } = this.props;
  296. if (!dateSelected) {
  297. return this.renderTraceRequiresDateRangeSelection();
  298. }
  299. if (isLoading) {
  300. return this.renderTraceLoading();
  301. }
  302. const hasData = hasTraceData(traces, orphanErrors);
  303. if (error !== null || !hasData) {
  304. return (
  305. <TraceNotFound
  306. meta={meta}
  307. traceEventView={traceEventView}
  308. traceSlug={traceSlug}
  309. location={location}
  310. organization={organization}
  311. />
  312. );
  313. }
  314. const traceInfo = traces ? getTraceInfo(traces, orphanErrors) : undefined;
  315. return (
  316. <Fragment>
  317. {this.renderTraceWarnings()}
  318. {traceInfo && this.renderTraceHeader(traceInfo)}
  319. {this.renderSearchBar()}
  320. <Margin>
  321. <VisuallyCompleteWithData id="PerformanceDetails-TraceView" hasData={hasData}>
  322. <TraceView
  323. filteredEventIds={this.state.filteredEventIds}
  324. traceInfo={traceInfo}
  325. location={location}
  326. organization={organization}
  327. traceEventView={traceEventView}
  328. traceSlug={traceSlug}
  329. traces={traces || []}
  330. meta={meta}
  331. orphanErrors={orphanErrors || []}
  332. />
  333. </VisuallyCompleteWithData>
  334. </Margin>
  335. </Fragment>
  336. );
  337. }
  338. render() {
  339. const {organization, location, traceEventView, traceSlug} = this.props;
  340. return (
  341. <Fragment>
  342. <Layout.Header>
  343. <Layout.HeaderContent>
  344. <Breadcrumb
  345. organization={organization}
  346. location={location}
  347. traceSlug={traceSlug}
  348. />
  349. <Layout.Title data-test-id="trace-header">
  350. {t('Trace ID: %s', traceSlug)}
  351. </Layout.Title>
  352. </Layout.HeaderContent>
  353. <Layout.HeaderActions>
  354. <ButtonBar gap={1}>
  355. <DiscoverButton
  356. size="sm"
  357. to={traceEventView.getResultsViewUrlTarget(organization.slug)}
  358. onClick={() => {
  359. trackAnalytics('performance_views.trace_view.open_in_discover', {
  360. organization,
  361. });
  362. }}
  363. >
  364. {t('Open in Discover')}
  365. </DiscoverButton>
  366. </ButtonBar>
  367. </Layout.HeaderActions>
  368. </Layout.Header>
  369. <Layout.Body>
  370. <Layout.Main fullWidth>{this.renderContent()}</Layout.Main>
  371. </Layout.Body>
  372. </Fragment>
  373. );
  374. }
  375. }
  376. const Margin = styled('div')`
  377. margin-top: ${space(2)};
  378. `;
  379. export default TraceDetailsContent;