messageSpanSamplesPanel.tsx 17 KB

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