messageSpanSamplesPanel.tsx 17 KB

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