messageSpanSamplesPanel.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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 {computeAxisMax} from 'sentry/views/insights/common/components/chart';
  26. import DetailPanel from 'sentry/views/insights/common/components/detailPanel';
  27. import {MetricReadout} from 'sentry/views/insights/common/components/metricReadout';
  28. import * as ModuleLayout from 'sentry/views/insights/common/components/moduleLayout';
  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. ...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. <Feature features="performance-sample-panel-search">
  332. <ModuleLayout.Full>
  333. <SearchBar
  334. searchSource={`${ModuleName.QUEUE}-sample-panel`}
  335. query={query.spanSearchQuery}
  336. onSearch={handleSearch}
  337. placeholder={t('Search for span attributes')}
  338. organization={organization}
  339. metricAlert={false}
  340. supportedTags={supportedTags}
  341. dataset={DiscoverDatasets.SPANS_INDEXED}
  342. projectIds={selection.projects}
  343. />
  344. </ModuleLayout.Full>
  345. </Feature>
  346. <ModuleLayout.Full>
  347. <MessageSpanSamplesTable
  348. data={durationSamplesData}
  349. isLoading={isDurationDataFetching || isDurationSamplesDataFetching}
  350. highlightedSpanId={highlightedSpanId}
  351. onSampleMouseOver={sample => setHighlightedSpanId(sample.span_id)}
  352. onSampleMouseOut={() => setHighlightedSpanId(undefined)}
  353. error={durationSamplesDataError}
  354. // Samples endpoint doesn't provide meta data, so we need to provide it here
  355. meta={{
  356. fields: {
  357. [SpanIndexedField.SPAN_DURATION]: 'duration',
  358. [SpanIndexedField.MESSAGING_MESSAGE_BODY_SIZE]: 'size',
  359. [SpanIndexedField.MESSAGING_MESSAGE_RETRY_COUNT]: 'number',
  360. },
  361. units: {
  362. [SpanIndexedField.SPAN_DURATION]: DurationUnit.MILLISECOND,
  363. [SpanIndexedField.MESSAGING_MESSAGE_BODY_SIZE]: SizeUnit.BYTE,
  364. },
  365. }}
  366. type={messageActorType}
  367. />
  368. </ModuleLayout.Full>
  369. <ModuleLayout.Full>
  370. <Button
  371. onClick={() => {
  372. trackAnalytics(
  373. 'performance_views.sample_spans.try_different_samples_clicked',
  374. {organization, source: ModuleName.QUEUE}
  375. );
  376. refetchDurationSpanSamples();
  377. }}
  378. >
  379. {t('Try Different Samples')}
  380. </Button>
  381. </ModuleLayout.Full>
  382. </ModuleLayout.Layout>
  383. </DetailPanel>
  384. </PageAlertProvider>
  385. );
  386. }
  387. function ProducerMetricsRibbon({
  388. metrics,
  389. isLoading,
  390. }: {
  391. isLoading: boolean;
  392. metrics: Partial<SpanMetricsResponse>[];
  393. }) {
  394. const errorRate = 1 - (metrics[0]?.['trace_status_rate(ok)'] ?? 0);
  395. return (
  396. <Fragment>
  397. <MetricReadout
  398. align="left"
  399. title={t('Published')}
  400. value={metrics?.[0]?.['count_op(queue.publish)']}
  401. unit={'count'}
  402. isLoading={isLoading}
  403. />
  404. <MetricReadout
  405. align="left"
  406. title={t('Error Rate')}
  407. value={errorRate}
  408. unit={'percentage'}
  409. isLoading={isLoading}
  410. />
  411. </Fragment>
  412. );
  413. }
  414. function ConsumerMetricsRibbon({
  415. metrics,
  416. isLoading,
  417. }: {
  418. isLoading: boolean;
  419. metrics: Partial<SpanMetricsResponse>[];
  420. }) {
  421. const errorRate = 1 - (metrics[0]?.['trace_status_rate(ok)'] ?? 0);
  422. return (
  423. <Fragment>
  424. <MetricReadout
  425. align="left"
  426. title={t('Processed')}
  427. value={metrics?.[0]?.['count_op(queue.process)']}
  428. unit={'count'}
  429. isLoading={isLoading}
  430. />
  431. <MetricReadout
  432. align="left"
  433. title={t('Error Rate')}
  434. value={errorRate}
  435. unit={'percentage'}
  436. isLoading={isLoading}
  437. />
  438. <MetricReadout
  439. title={t('Avg Time In Queue')}
  440. value={metrics[0]?.['avg(messaging.message.receive.latency)']}
  441. unit={DurationUnit.MILLISECOND}
  442. isLoading={false}
  443. />
  444. <MetricReadout
  445. title={t('Avg Processing Time')}
  446. value={metrics[0]?.['avg_if(span.duration,span.op,queue.process)']}
  447. unit={DurationUnit.MILLISECOND}
  448. isLoading={false}
  449. />
  450. </Fragment>
  451. );
  452. }
  453. const SAMPLE_HOVER_DEBOUNCE = 10;
  454. const TRACE_STATUS_SELECT_OPTIONS = [
  455. {
  456. value: '',
  457. label: t('All'),
  458. },
  459. ...TRACE_STATUS_OPTIONS.map(status => {
  460. return {
  461. value: status,
  462. label: status,
  463. };
  464. }),
  465. ];
  466. const RETRY_COUNT_SELECT_OPTIONS = [
  467. {
  468. value: '',
  469. label: t('Any'),
  470. },
  471. ...RETRY_COUNT_OPTIONS.map(status => {
  472. return {
  473. value: status,
  474. label: status,
  475. };
  476. }),
  477. ];
  478. const SpanSummaryProjectAvatar = styled(ProjectAvatar)`
  479. padding-right: ${space(1)};
  480. `;
  481. const HeaderContainer = styled('div')`
  482. display: grid;
  483. grid-template-rows: auto auto auto;
  484. @media (min-width: ${p => p.theme.breakpoints.small}) {
  485. grid-template-rows: auto;
  486. grid-template-columns: auto 1fr;
  487. }
  488. `;
  489. const TitleContainer = styled('div')`
  490. width: 100%;
  491. overflow: hidden;
  492. `;
  493. const Title = styled('h4')`
  494. overflow: inherit;
  495. text-overflow: ellipsis;
  496. white-space: nowrap;
  497. margin: 0;
  498. `;
  499. const MetricsRibbonContainer = styled('div')`
  500. display: flex;
  501. flex-wrap: wrap;
  502. gap: ${space(4)};
  503. `;
  504. const PanelControls = styled('div')`
  505. display: flex;
  506. gap: ${space(2)};
  507. `;