messageSpanSamplesPanel.tsx 18 KB

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