messageSpanSamplesPanel.tsx 17 KB

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