messageSpanSamplesPanel.tsx 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548
  1. import {Fragment, useCallback} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as qs from 'query-string';
  4. import Feature from 'sentry/components/acl/feature';
  5. import ProjectAvatar from 'sentry/components/avatar/projectAvatar';
  6. import {Button} from 'sentry/components/button';
  7. import {CompactSelect, type SelectOption} from 'sentry/components/compactSelect';
  8. import SearchBar from 'sentry/components/events/searchBar';
  9. import Link from 'sentry/components/links/link';
  10. import {t} from 'sentry/locale';
  11. import {space} from 'sentry/styles/space';
  12. import {trackAnalytics} from 'sentry/utils/analytics';
  13. import {DurationUnit, SizeUnit} from 'sentry/utils/discover/fields';
  14. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  15. import {PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  16. import {decodeScalar} from 'sentry/utils/queryString';
  17. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  18. import useLocationQuery from 'sentry/utils/url/useLocationQuery';
  19. import {useLocation} from 'sentry/utils/useLocation';
  20. import useOrganization from 'sentry/utils/useOrganization';
  21. import usePageFilters from 'sentry/utils/usePageFilters';
  22. import useProjects from 'sentry/utils/useProjects';
  23. import useRouter from 'sentry/utils/useRouter';
  24. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  25. import {AverageValueMarkLine} from 'sentry/views/performance/charts/averageValueMarkLine';
  26. import {DurationChart} from 'sentry/views/performance/http/charts/durationChart';
  27. import {useSpanSamples} from 'sentry/views/performance/http/data/useSpanSamples';
  28. import {useDebouncedState} from 'sentry/views/performance/http/useDebouncedState';
  29. import {MetricReadout} from 'sentry/views/performance/metricReadout';
  30. import * as ModuleLayout from 'sentry/views/performance/moduleLayout';
  31. import {MessageSpanSamplesTable} from 'sentry/views/performance/queues/destinationSummary/messageSpanSamplesTable';
  32. import {useQueuesMetricsQuery} from 'sentry/views/performance/queues/queries/useQueuesMetricsQuery';
  33. import decodeRetryCount from 'sentry/views/performance/queues/queryParameterDecoders/retryCount';
  34. import decodeTraceStatus from 'sentry/views/performance/queues/queryParameterDecoders/traceStatus';
  35. import {Referrer} from 'sentry/views/performance/queues/referrers';
  36. import {
  37. CONSUMER_QUERY_FILTER,
  38. MessageActorType,
  39. PRODUCER_QUERY_FILTER,
  40. RETRY_COUNT_OPTIONS,
  41. TRACE_STATUS_OPTIONS,
  42. } from 'sentry/views/performance/queues/settings';
  43. import {useSpanFieldSupportedTags} from 'sentry/views/performance/utils/useSpanFieldSupportedTags';
  44. import {Subtitle} from 'sentry/views/profiling/landing/styles';
  45. import {computeAxisMax} from 'sentry/views/starfish/components/chart';
  46. import DetailPanel from 'sentry/views/starfish/components/detailPanel';
  47. import {useSpanMetricsSeries} from 'sentry/views/starfish/queries/useDiscoverSeries';
  48. import {
  49. ModuleName,
  50. SpanIndexedField,
  51. type SpanMetricsResponse,
  52. } from 'sentry/views/starfish/types';
  53. import {useSampleScatterPlotSeries} from 'sentry/views/starfish/views/spanSummaryPage/sampleList/durationChart/useSampleScatterPlotSeries';
  54. export function MessageSpanSamplesPanel() {
  55. const router = useRouter();
  56. const location = useLocation();
  57. const query = useLocationQuery({
  58. fields: {
  59. project: decodeScalar,
  60. destination: decodeScalar,
  61. transaction: decodeScalar,
  62. retryCount: decodeRetryCount,
  63. traceStatus: decodeTraceStatus,
  64. spanSearchQuery: decodeScalar,
  65. 'span.op': decodeScalar,
  66. },
  67. });
  68. const {projects} = useProjects();
  69. const {selection} = usePageFilters();
  70. const supportedTags = useSpanFieldSupportedTags();
  71. const project = projects.find(p => query.project === p.id);
  72. const organization = useOrganization();
  73. const [highlightedSpanId, setHighlightedSpanId] = useDebouncedState<string | undefined>(
  74. undefined,
  75. [],
  76. SAMPLE_HOVER_DEBOUNCE
  77. );
  78. // `detailKey` controls whether the panel is open. If all required properties are available, concat them to make a key, otherwise set to `undefined` and hide the panel
  79. const detailKey = query.transaction
  80. ? [query.destination, query.transaction].filter(Boolean).join(':')
  81. : undefined;
  82. const handleTraceStatusChange = (newTraceStatus: SelectOption<string>) => {
  83. trackAnalytics('performance_views.sample_spans.filter_updated', {
  84. filter: 'trace_status',
  85. new_state: newTraceStatus.value,
  86. organization,
  87. source: ModuleName.QUEUE,
  88. });
  89. router.replace({
  90. pathname: location.pathname,
  91. query: {
  92. ...location.query,
  93. traceStatus: newTraceStatus.value,
  94. },
  95. });
  96. };
  97. const handleRetryCountChange = (newRetryCount: SelectOption<string>) => {
  98. trackAnalytics('performance_views.sample_spans.filter_updated', {
  99. filter: 'retry_count',
  100. new_state: newRetryCount.value,
  101. organization,
  102. source: ModuleName.QUEUE,
  103. });
  104. router.replace({
  105. pathname: location.pathname,
  106. query: {
  107. ...location.query,
  108. retryCount: newRetryCount.value,
  109. },
  110. });
  111. };
  112. const isPanelOpen = Boolean(detailKey);
  113. const messageActorType =
  114. query['span.op'] === 'queue.publish'
  115. ? MessageActorType.PRODUCER
  116. : MessageActorType.CONSUMER;
  117. const queryFilter =
  118. messageActorType === MessageActorType.PRODUCER
  119. ? PRODUCER_QUERY_FILTER
  120. : CONSUMER_QUERY_FILTER;
  121. const timeseriesFilters = new MutableSearch(queryFilter);
  122. timeseriesFilters.addFilterValue('transaction', query.transaction);
  123. timeseriesFilters.addFilterValue('messaging.destination.name', query.destination);
  124. const sampleFilters = new MutableSearch(queryFilter);
  125. sampleFilters.addFilterValue('transaction', query.transaction);
  126. sampleFilters.addFilterValue('messaging.destination.name', query.destination);
  127. // filter by key-value filters specified in the search bar query
  128. sampleFilters.addStringMultiFilter(query.spanSearchQuery);
  129. if (query.traceStatus.length > 0) {
  130. sampleFilters.addFilterValue('trace.status', query.traceStatus);
  131. }
  132. // Note: only consumer panels should allow filtering by retry count
  133. if (messageActorType === MessageActorType.CONSUMER) {
  134. if (query.retryCount === '0') {
  135. sampleFilters.addFilterValue('measurements.messaging.message.retry.count', '0');
  136. } else if (query.retryCount === '1-3') {
  137. sampleFilters.addFilterValues('measurements.messaging.message.retry.count', [
  138. '>=1',
  139. '<=3',
  140. ]);
  141. } else if (query.retryCount === '4+') {
  142. sampleFilters.addFilterValue('measurements.messaging.message.retry.count', '>=4');
  143. }
  144. }
  145. const {data: transactionMetrics, isFetching: aretransactionMetricsFetching} =
  146. useQueuesMetricsQuery({
  147. destination: query.destination,
  148. transaction: query.transaction,
  149. enabled: isPanelOpen,
  150. referrer: Referrer.QUEUES_SAMPLES_PANEL,
  151. });
  152. const avg = transactionMetrics?.[0]?.['avg(span.duration)'];
  153. const {
  154. isFetching: isDurationDataFetching,
  155. data: durationData,
  156. error: durationError,
  157. } = useSpanMetricsSeries(
  158. {
  159. search: timeseriesFilters,
  160. yAxis: [`avg(span.duration)`],
  161. enabled: isPanelOpen,
  162. },
  163. 'api.performance.queues.avg-duration-chart'
  164. );
  165. const durationAxisMax = computeAxisMax([durationData?.[`avg(span.duration)`]]);
  166. const {
  167. data: durationSamplesData,
  168. isFetching: isDurationSamplesDataFetching,
  169. error: durationSamplesDataError,
  170. refetch: refetchDurationSpanSamples,
  171. } = useSpanSamples({
  172. search: sampleFilters,
  173. min: 0,
  174. max: durationAxisMax,
  175. enabled: isPanelOpen && durationAxisMax > 0,
  176. fields: [
  177. SpanIndexedField.TRACE,
  178. SpanIndexedField.TRANSACTION_ID,
  179. SpanIndexedField.SPAN_DESCRIPTION,
  180. SpanIndexedField.MESSAGING_MESSAGE_BODY_SIZE,
  181. SpanIndexedField.MESSAGING_MESSAGE_RECEIVE_LATENCY,
  182. SpanIndexedField.MESSAGING_MESSAGE_RETRY_COUNT,
  183. SpanIndexedField.MESSAGING_MESSAGE_ID,
  184. SpanIndexedField.TRACE_STATUS,
  185. SpanIndexedField.SPAN_DURATION,
  186. ],
  187. });
  188. const sampledSpanDataSeries = useSampleScatterPlotSeries(
  189. durationSamplesData,
  190. transactionMetrics?.[0]?.['avg(span.duration)'],
  191. highlightedSpanId,
  192. 'span.duration'
  193. );
  194. const findSampleFromDataPoint = (dataPoint: {name: string | number; value: number}) => {
  195. return durationSamplesData.find(
  196. s => s.timestamp === dataPoint.name && s['span.duration'] === dataPoint.value
  197. );
  198. };
  199. const handleSearch = (newSpanSearchQuery: string) => {
  200. router.replace({
  201. pathname: location.pathname,
  202. query: {
  203. ...query,
  204. spanSearchQuery: newSpanSearchQuery,
  205. },
  206. });
  207. };
  208. const handleClose = () => {
  209. router.replace({
  210. pathname: router.location.pathname,
  211. query: {
  212. ...router.location.query,
  213. transaction: undefined,
  214. transactionMethod: undefined,
  215. },
  216. });
  217. };
  218. const handleOpen = useCallback(() => {
  219. if (query.transaction) {
  220. trackAnalytics('performance_views.sample_spans.opened', {
  221. organization,
  222. source: ModuleName.QUEUE,
  223. });
  224. }
  225. }, [organization, query.transaction]);
  226. return (
  227. <PageAlertProvider>
  228. <DetailPanel detailKey={detailKey} onClose={handleClose} onOpen={handleOpen}>
  229. <ModuleLayout.Layout>
  230. <ModuleLayout.Full>
  231. <HeaderContainer>
  232. {project ? (
  233. <SpanSummaryProjectAvatar
  234. project={project}
  235. direction="left"
  236. size={40}
  237. hasTooltip
  238. tooltip={project.slug}
  239. />
  240. ) : (
  241. <div />
  242. )}
  243. <TitleContainer>
  244. <Subtitle>
  245. {messageActorType === MessageActorType.PRODUCER
  246. ? t('Producer')
  247. : t('Consumer')}
  248. </Subtitle>
  249. <Title>
  250. <Link
  251. to={normalizeUrl(
  252. `/organizations/${organization.slug}/performance/summary?${qs.stringify(
  253. {
  254. project: query.project,
  255. transaction: query.transaction,
  256. }
  257. )}`
  258. )}
  259. >
  260. {query.transaction}
  261. </Link>
  262. </Title>
  263. </TitleContainer>
  264. </HeaderContainer>
  265. </ModuleLayout.Full>
  266. <ModuleLayout.Full>
  267. <MetricsRibbonContainer>
  268. {messageActorType === MessageActorType.PRODUCER ? (
  269. <ProducerMetricsRibbon
  270. metrics={transactionMetrics}
  271. isLoading={aretransactionMetricsFetching}
  272. />
  273. ) : (
  274. <ConsumerMetricsRibbon
  275. metrics={transactionMetrics}
  276. isLoading={aretransactionMetricsFetching}
  277. />
  278. )}
  279. </MetricsRibbonContainer>
  280. </ModuleLayout.Full>
  281. <ModuleLayout.Full>
  282. <PanelControls>
  283. <CompactSelect
  284. searchable
  285. value={query.traceStatus}
  286. options={TRACE_STATUS_SELECT_OPTIONS}
  287. onChange={handleTraceStatusChange}
  288. triggerProps={{
  289. prefix: t('Status'),
  290. }}
  291. />
  292. {messageActorType === MessageActorType.CONSUMER && (
  293. <CompactSelect
  294. value={query.retryCount}
  295. options={RETRY_COUNT_SELECT_OPTIONS}
  296. onChange={handleRetryCountChange}
  297. triggerProps={{
  298. prefix: t('Retries'),
  299. }}
  300. />
  301. )}
  302. </PanelControls>
  303. </ModuleLayout.Full>
  304. <ModuleLayout.Full>
  305. <DurationChart
  306. series={[
  307. {
  308. ...durationData[`avg(span.duration)`],
  309. markLine: AverageValueMarkLine({value: avg}),
  310. },
  311. ]}
  312. scatterPlot={sampledSpanDataSeries}
  313. onHighlight={highlights => {
  314. const firstHighlight = highlights[0];
  315. if (!firstHighlight) {
  316. setHighlightedSpanId(undefined);
  317. return;
  318. }
  319. const sample = findSampleFromDataPoint(firstHighlight.dataPoint);
  320. setHighlightedSpanId(sample?.span_id);
  321. }}
  322. isLoading={isDurationDataFetching}
  323. error={durationError}
  324. />
  325. </ModuleLayout.Full>
  326. <Feature features="performance-sample-panel-search">
  327. <ModuleLayout.Full>
  328. <SearchBar
  329. searchSource={`${ModuleName.QUEUE}-sample-panel`}
  330. query={query.spanSearchQuery}
  331. onSearch={handleSearch}
  332. placeholder={t('Search for span attributes')}
  333. organization={organization}
  334. metricAlert={false}
  335. supportedTags={supportedTags}
  336. dataset={DiscoverDatasets.SPANS_INDEXED}
  337. projectIds={selection.projects}
  338. />
  339. </ModuleLayout.Full>
  340. </Feature>
  341. <ModuleLayout.Full>
  342. <MessageSpanSamplesTable
  343. data={durationSamplesData}
  344. isLoading={isDurationDataFetching || isDurationSamplesDataFetching}
  345. highlightedSpanId={highlightedSpanId}
  346. onSampleMouseOver={sample => setHighlightedSpanId(sample.span_id)}
  347. onSampleMouseOut={() => setHighlightedSpanId(undefined)}
  348. error={durationSamplesDataError}
  349. // Samples endpoint doesn't provide meta data, so we need to provide it here
  350. meta={{
  351. fields: {
  352. [SpanIndexedField.SPAN_DURATION]: 'duration',
  353. [SpanIndexedField.MESSAGING_MESSAGE_BODY_SIZE]: 'size',
  354. [SpanIndexedField.MESSAGING_MESSAGE_RETRY_COUNT]: 'number',
  355. },
  356. units: {
  357. [SpanIndexedField.SPAN_DURATION]: DurationUnit.MILLISECOND,
  358. [SpanIndexedField.MESSAGING_MESSAGE_BODY_SIZE]: SizeUnit.BYTE,
  359. },
  360. }}
  361. type={messageActorType}
  362. />
  363. </ModuleLayout.Full>
  364. <ModuleLayout.Full>
  365. <Button
  366. onClick={() => {
  367. trackAnalytics(
  368. 'performance_views.sample_spans.try_different_samples_clicked',
  369. {organization, source: ModuleName.QUEUE}
  370. );
  371. refetchDurationSpanSamples();
  372. }}
  373. >
  374. {t('Try Different Samples')}
  375. </Button>
  376. </ModuleLayout.Full>
  377. </ModuleLayout.Layout>
  378. </DetailPanel>
  379. </PageAlertProvider>
  380. );
  381. }
  382. function ProducerMetricsRibbon({
  383. metrics,
  384. isLoading,
  385. }: {
  386. isLoading: boolean;
  387. metrics: Partial<SpanMetricsResponse>[];
  388. }) {
  389. const errorRate = 1 - (metrics[0]?.['trace_status_rate(ok)'] ?? 0);
  390. return (
  391. <Fragment>
  392. <MetricReadout
  393. align="left"
  394. title={t('Published')}
  395. value={metrics?.[0]?.['count_op(queue.publish)']}
  396. unit={'count'}
  397. isLoading={isLoading}
  398. />
  399. <MetricReadout
  400. align="left"
  401. title={t('Error Rate')}
  402. value={errorRate}
  403. unit={'percentage'}
  404. isLoading={isLoading}
  405. />
  406. </Fragment>
  407. );
  408. }
  409. function ConsumerMetricsRibbon({
  410. metrics,
  411. isLoading,
  412. }: {
  413. isLoading: boolean;
  414. metrics: Partial<SpanMetricsResponse>[];
  415. }) {
  416. const errorRate = 1 - (metrics[0]?.['trace_status_rate(ok)'] ?? 0);
  417. return (
  418. <Fragment>
  419. <MetricReadout
  420. align="left"
  421. title={t('Processed')}
  422. value={metrics?.[0]?.['count_op(queue.process)']}
  423. unit={'count'}
  424. isLoading={isLoading}
  425. />
  426. <MetricReadout
  427. align="left"
  428. title={t('Error Rate')}
  429. value={errorRate}
  430. unit={'percentage'}
  431. isLoading={isLoading}
  432. />
  433. <MetricReadout
  434. title={t('Avg Time In Queue')}
  435. value={metrics[0]?.['avg(messaging.message.receive.latency)']}
  436. unit={DurationUnit.MILLISECOND}
  437. isLoading={false}
  438. />
  439. <MetricReadout
  440. title={t('Avg Processing Time')}
  441. value={metrics[0]?.['avg_if(span.duration,span.op,queue.process)']}
  442. unit={DurationUnit.MILLISECOND}
  443. isLoading={false}
  444. />
  445. </Fragment>
  446. );
  447. }
  448. const SAMPLE_HOVER_DEBOUNCE = 10;
  449. const TRACE_STATUS_SELECT_OPTIONS = [
  450. {
  451. value: '',
  452. label: t('All'),
  453. },
  454. ...TRACE_STATUS_OPTIONS.map(status => {
  455. return {
  456. value: status,
  457. label: status,
  458. };
  459. }),
  460. ];
  461. const RETRY_COUNT_SELECT_OPTIONS = [
  462. {
  463. value: '',
  464. label: t('Any'),
  465. },
  466. ...RETRY_COUNT_OPTIONS.map(status => {
  467. return {
  468. value: status,
  469. label: status,
  470. };
  471. }),
  472. ];
  473. const SpanSummaryProjectAvatar = styled(ProjectAvatar)`
  474. padding-right: ${space(1)};
  475. `;
  476. const HeaderContainer = styled('div')`
  477. display: grid;
  478. grid-template-rows: auto auto auto;
  479. @media (min-width: ${p => p.theme.breakpoints.small}) {
  480. grid-template-rows: auto;
  481. grid-template-columns: auto 1fr auto;
  482. }
  483. `;
  484. const TitleContainer = styled('div')`
  485. width: 100%;
  486. position: relative;
  487. height: 40px;
  488. `;
  489. const Title = styled('h4')`
  490. position: absolute;
  491. bottom: 0;
  492. margin-bottom: 0;
  493. `;
  494. const MetricsRibbonContainer = styled('div')`
  495. display: flex;
  496. flex-wrap: wrap;
  497. gap: ${space(4)};
  498. `;
  499. const PanelControls = styled('div')`
  500. display: flex;
  501. gap: ${space(2)};
  502. `;