messageSpanSamplesPanel.tsx 17 KB

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