httpSamplesPanel.tsx 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import {Button} from 'sentry/components/button';
  4. import {CompactSelect} from 'sentry/components/compactSelect';
  5. import {DrawerHeader} from 'sentry/components/globalDrawer/components';
  6. import {SpanSearchQueryBuilder} from 'sentry/components/performance/spanSearchQueryBuilder';
  7. import {SegmentedControl} from 'sentry/components/segmentedControl';
  8. import {t} from 'sentry/locale';
  9. import {space} from 'sentry/styles/space';
  10. import {trackAnalytics} from 'sentry/utils/analytics';
  11. import {DurationUnit, RateUnit} from 'sentry/utils/discover/fields';
  12. import {PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  13. import {decodeList, decodeScalar} from 'sentry/utils/queryString';
  14. import {
  15. EMPTY_OPTION_VALUE,
  16. escapeFilterValue,
  17. MutableSearch,
  18. } from 'sentry/utils/tokenizeSearch';
  19. import useLocationQuery from 'sentry/utils/url/useLocationQuery';
  20. import {useLocation} from 'sentry/utils/useLocation';
  21. import {useNavigate} from 'sentry/utils/useNavigate';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import usePageFilters from 'sentry/utils/usePageFilters';
  24. import useProjects from 'sentry/utils/useProjects';
  25. import {computeAxisMax} from 'sentry/views/insights/common/components/chart';
  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 {getTimeSpentExplanation} from 'sentry/views/insights/common/components/tableCells/timeSpentCell';
  30. import {
  31. useSpanMetrics,
  32. useSpansIndexed,
  33. } from 'sentry/views/insights/common/queries/useDiscover';
  34. import {useSpanMetricsSeries} from 'sentry/views/insights/common/queries/useDiscoverSeries';
  35. import {useSpanMetricsTopNSeries} from 'sentry/views/insights/common/queries/useSpanMetricsTopNSeries';
  36. import {AverageValueMarkLine} from 'sentry/views/insights/common/utils/averageValueMarkLine';
  37. import {findSampleFromDataPoint} from 'sentry/views/insights/common/utils/findDataPoint';
  38. import {
  39. DataTitles,
  40. getThroughputTitle,
  41. } from 'sentry/views/insights/common/views/spans/types';
  42. import {useSampleScatterPlotSeries} from 'sentry/views/insights/common/views/spanSummaryPage/sampleList/durationChart/useSampleScatterPlotSeries';
  43. import {DurationChartWithSamples} from 'sentry/views/insights/http/components/charts/durationChartWithSamples';
  44. import {ResponseCodeCountChart} from 'sentry/views/insights/http/components/charts/responseCodeCountChart';
  45. import {SpanSamplesTable} from 'sentry/views/insights/http/components/tables/spanSamplesTable';
  46. import {HTTP_RESPONSE_STATUS_CODES} from 'sentry/views/insights/http/data/definitions';
  47. import {useSpanSamples} from 'sentry/views/insights/http/queries/useSpanSamples';
  48. import {Referrer} from 'sentry/views/insights/http/referrers';
  49. import {BASE_FILTERS} from 'sentry/views/insights/http/settings';
  50. import decodePanel from 'sentry/views/insights/http/utils/queryParameterDecoders/panel';
  51. import decodeResponseCodeClass from 'sentry/views/insights/http/utils/queryParameterDecoders/responseCodeClass';
  52. import {useDebouncedState} from 'sentry/views/insights/http/utils/useDebouncedState';
  53. import {
  54. ModuleName,
  55. SpanFunction,
  56. SpanIndexedField,
  57. SpanMetricsField,
  58. type SpanMetricsQueryFilters,
  59. } from 'sentry/views/insights/types';
  60. import {TraceViewSources} from 'sentry/views/performance/newTraceDetails/traceHeader/breadcrumbs';
  61. import {SampleDrawerBody} from '../../common/components/sampleDrawerBody';
  62. import {SampleDrawerHeaderTransaction} from '../../common/components/sampleDrawerHeaderTransaction';
  63. export function HTTPSamplesPanel() {
  64. const navigate = useNavigate();
  65. const location = useLocation();
  66. const query = useLocationQuery({
  67. fields: {
  68. project: decodeScalar,
  69. domain: decodeScalar,
  70. transaction: decodeScalar,
  71. transactionMethod: decodeScalar,
  72. panel: decodePanel,
  73. responseCodeClass: decodeResponseCodeClass,
  74. spanSearchQuery: decodeScalar,
  75. [SpanMetricsField.USER_GEO_SUBREGION]: decodeList,
  76. },
  77. });
  78. const organization = useOrganization();
  79. const {projects} = useProjects();
  80. const {selection} = usePageFilters();
  81. const project = projects.find(p => query.project === p.id);
  82. const [highlightedSpanId, setHighlightedSpanId] = useDebouncedState<string | undefined>(
  83. undefined,
  84. [],
  85. SAMPLE_HOVER_DEBOUNCE
  86. );
  87. // `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
  88. const detailKey = query.transaction
  89. ? [query.domain, query.transactionMethod, query.transaction].filter(Boolean).join(':')
  90. : undefined;
  91. const handlePanelChange = (newPanelName: any) => {
  92. trackAnalytics('performance_views.sample_spans.filter_updated', {
  93. filter: 'panel',
  94. new_state: newPanelName,
  95. organization,
  96. source: ModuleName.HTTP,
  97. });
  98. navigate({
  99. pathname: location.pathname,
  100. query: {
  101. ...location.query,
  102. panel: newPanelName,
  103. },
  104. });
  105. };
  106. const handleResponseCodeClassChange = (newResponseCodeClass: any) => {
  107. trackAnalytics('performance_views.sample_spans.filter_updated', {
  108. filter: 'status_code',
  109. new_state: newResponseCodeClass.value,
  110. organization,
  111. source: ModuleName.HTTP,
  112. });
  113. navigate({
  114. pathname: location.pathname,
  115. query: {
  116. ...location.query,
  117. responseCodeClass: newResponseCodeClass.value,
  118. },
  119. });
  120. };
  121. const isPanelOpen = Boolean(detailKey);
  122. const ADDITONAL_FILTERS = {
  123. 'span.domain':
  124. query.domain === '' ? EMPTY_OPTION_VALUE : escapeFilterValue(query.domain),
  125. transaction: query.transaction,
  126. ...(query[SpanMetricsField.USER_GEO_SUBREGION].length > 0
  127. ? {
  128. [SpanMetricsField.USER_GEO_SUBREGION]: `[${query[SpanMetricsField.USER_GEO_SUBREGION].join(',')}]`,
  129. }
  130. : {}),
  131. };
  132. // The ribbon is above the data selectors, and not affected by them. So, it has its own filters.
  133. const ribbonFilters: SpanMetricsQueryFilters = {
  134. ...BASE_FILTERS,
  135. ...ADDITONAL_FILTERS,
  136. ...new MutableSearch(query.spanSearchQuery).filters,
  137. };
  138. // These filters are for the charts and samples tables
  139. const filters: SpanMetricsQueryFilters = {
  140. ...BASE_FILTERS,
  141. ...ADDITONAL_FILTERS,
  142. ...new MutableSearch(query.spanSearchQuery).filters,
  143. };
  144. const responseCodeInRange = query.responseCodeClass
  145. ? Object.keys(HTTP_RESPONSE_STATUS_CODES).filter(code =>
  146. code.startsWith(query.responseCodeClass)
  147. )
  148. : [];
  149. if (responseCodeInRange.length > 0) {
  150. // TODO: Allow automatic array parameter concatenation
  151. filters['span.status_code'] = `[${responseCodeInRange.join(',')}]`;
  152. }
  153. const search = MutableSearch.fromQueryObject(filters);
  154. const {
  155. data: domainTransactionMetrics,
  156. isFetching: areDomainTransactionMetricsFetching,
  157. } = useSpanMetrics(
  158. {
  159. search: MutableSearch.fromQueryObject(ribbonFilters),
  160. fields: [
  161. `${SpanFunction.SPM}()`,
  162. `avg(${SpanMetricsField.SPAN_SELF_TIME})`,
  163. `sum(${SpanMetricsField.SPAN_SELF_TIME})`,
  164. 'http_response_rate(3)',
  165. 'http_response_rate(4)',
  166. 'http_response_rate(5)',
  167. `${SpanFunction.TIME_SPENT_PERCENTAGE}()`,
  168. ],
  169. enabled: isPanelOpen,
  170. },
  171. Referrer.SAMPLES_PANEL_METRICS_RIBBON
  172. );
  173. const {
  174. isFetching: isDurationDataFetching,
  175. data: durationData,
  176. error: durationError,
  177. } = useSpanMetricsSeries(
  178. {
  179. search,
  180. yAxis: [`avg(span.self_time)`],
  181. enabled: isPanelOpen && query.panel === 'duration',
  182. },
  183. Referrer.SAMPLES_PANEL_DURATION_CHART
  184. );
  185. const {
  186. isFetching: isResponseCodeDataLoading,
  187. data: responseCodeData,
  188. error: responseCodeError,
  189. } = useSpanMetricsTopNSeries({
  190. search,
  191. fields: ['span.status_code', 'count()'],
  192. yAxis: ['count()'],
  193. topEvents: 5,
  194. sorts: [
  195. {
  196. kind: 'desc',
  197. field: 'count()',
  198. },
  199. ],
  200. enabled: isPanelOpen && query.panel === 'status',
  201. referrer: Referrer.SAMPLES_PANEL_RESPONSE_CODE_CHART,
  202. });
  203. const durationAxisMax = computeAxisMax([durationData?.[`avg(span.self_time)`]]);
  204. const {
  205. data: durationSamplesData,
  206. isFetching: isDurationSamplesDataFetching,
  207. error: durationSamplesDataError,
  208. refetch: refetchDurationSpanSamples,
  209. } = useSpanSamples({
  210. search,
  211. fields: [
  212. SpanIndexedField.TRACE,
  213. SpanIndexedField.TRANSACTION_ID,
  214. SpanIndexedField.SPAN_DESCRIPTION,
  215. SpanIndexedField.RESPONSE_CODE,
  216. ],
  217. min: 0,
  218. max: durationAxisMax,
  219. enabled: isPanelOpen && query.panel === 'duration' && durationAxisMax > 0,
  220. referrer: Referrer.SAMPLES_PANEL_DURATION_SAMPLES,
  221. });
  222. const {
  223. data: responseCodeSamplesData,
  224. isFetching: isResponseCodeSamplesDataFetching,
  225. error: responseCodeSamplesDataError,
  226. refetch: refetchResponseCodeSpanSamples,
  227. } = useSpansIndexed(
  228. {
  229. search,
  230. fields: [
  231. SpanIndexedField.PROJECT,
  232. SpanIndexedField.TRACE,
  233. SpanIndexedField.TRANSACTION_ID,
  234. SpanIndexedField.ID,
  235. SpanIndexedField.TIMESTAMP,
  236. SpanIndexedField.SPAN_DESCRIPTION,
  237. SpanIndexedField.RESPONSE_CODE,
  238. ],
  239. sorts: [SPAN_SAMPLES_SORT],
  240. limit: SPAN_SAMPLE_LIMIT,
  241. enabled: isPanelOpen && query.panel === 'status',
  242. },
  243. Referrer.SAMPLES_PANEL_RESPONSE_CODE_SAMPLES
  244. );
  245. const sampledSpanDataSeries = useSampleScatterPlotSeries(
  246. durationSamplesData,
  247. domainTransactionMetrics?.[0]?.['avg(span.self_time)'],
  248. highlightedSpanId
  249. );
  250. const handleSearch = (newSpanSearchQuery: string) => {
  251. navigate({
  252. pathname: location.pathname,
  253. query: {
  254. ...location.query,
  255. spanSearchQuery: newSpanSearchQuery,
  256. },
  257. });
  258. if (query.panel === 'duration') {
  259. refetchDurationSpanSamples();
  260. } else {
  261. refetchResponseCodeSpanSamples();
  262. }
  263. };
  264. return (
  265. <PageAlertProvider>
  266. <DrawerHeader>
  267. <SampleDrawerHeaderTransaction
  268. project={project}
  269. transaction={query.transaction}
  270. transactionMethod={query.transactionMethod}
  271. />
  272. </DrawerHeader>
  273. <SampleDrawerBody>
  274. <ModuleLayout.Layout>
  275. <ModuleLayout.Full>
  276. <ReadoutRibbon>
  277. <MetricReadout
  278. title={getThroughputTitle('http')}
  279. value={domainTransactionMetrics?.[0]?.[`${SpanFunction.SPM}()`]}
  280. unit={RateUnit.PER_MINUTE}
  281. isLoading={areDomainTransactionMetricsFetching}
  282. />
  283. <MetricReadout
  284. title={DataTitles.avg}
  285. value={
  286. domainTransactionMetrics?.[0]?.[
  287. `avg(${SpanMetricsField.SPAN_SELF_TIME})`
  288. ]
  289. }
  290. unit={DurationUnit.MILLISECOND}
  291. isLoading={areDomainTransactionMetricsFetching}
  292. />
  293. <MetricReadout
  294. title={t('3XXs')}
  295. value={domainTransactionMetrics?.[0]?.[`http_response_rate(3)`]}
  296. unit="percentage"
  297. isLoading={areDomainTransactionMetricsFetching}
  298. />
  299. <MetricReadout
  300. title={t('4XXs')}
  301. value={domainTransactionMetrics?.[0]?.[`http_response_rate(4)`]}
  302. unit="percentage"
  303. isLoading={areDomainTransactionMetricsFetching}
  304. />
  305. <MetricReadout
  306. title={t('5XXs')}
  307. value={domainTransactionMetrics?.[0]?.[`http_response_rate(5)`]}
  308. unit="percentage"
  309. isLoading={areDomainTransactionMetricsFetching}
  310. />
  311. <MetricReadout
  312. title={DataTitles.timeSpent}
  313. value={domainTransactionMetrics?.[0]?.['sum(span.self_time)']}
  314. unit={DurationUnit.MILLISECOND}
  315. tooltip={getTimeSpentExplanation(
  316. domainTransactionMetrics?.[0]?.['time_spent_percentage()']!,
  317. 'http.client'
  318. )}
  319. isLoading={areDomainTransactionMetricsFetching}
  320. />
  321. </ReadoutRibbon>
  322. </ModuleLayout.Full>
  323. <ModuleLayout.Full>
  324. <PanelControls>
  325. <SegmentedControl
  326. value={query.panel}
  327. onChange={handlePanelChange}
  328. aria-label={t('Choose breakdown type')}
  329. >
  330. <SegmentedControl.Item key="duration">
  331. {t('By Duration')}
  332. </SegmentedControl.Item>
  333. <SegmentedControl.Item key="status">
  334. {t('By Response Code')}
  335. </SegmentedControl.Item>
  336. </SegmentedControl>
  337. <CompactSelect
  338. value={query.responseCodeClass}
  339. options={HTTP_RESPONSE_CODE_CLASS_OPTIONS}
  340. onChange={handleResponseCodeClassChange}
  341. triggerProps={{
  342. prefix: t('Response Code'),
  343. }}
  344. />
  345. </PanelControls>
  346. </ModuleLayout.Full>
  347. {query.panel === 'duration' && (
  348. <Fragment>
  349. <ModuleLayout.Full>
  350. <DurationChartWithSamples
  351. series={[
  352. {
  353. ...durationData[`avg(span.self_time)`],
  354. markLine: AverageValueMarkLine(),
  355. },
  356. ]}
  357. scatterPlot={sampledSpanDataSeries}
  358. onHighlight={highlights => {
  359. const firstHighlight = highlights[0];
  360. if (!firstHighlight) {
  361. setHighlightedSpanId(undefined);
  362. return;
  363. }
  364. const sample = findSampleFromDataPoint<
  365. (typeof durationSamplesData)[0]
  366. >(
  367. firstHighlight.dataPoint,
  368. durationSamplesData,
  369. SpanIndexedField.SPAN_SELF_TIME
  370. );
  371. setHighlightedSpanId(sample?.span_id);
  372. }}
  373. isLoading={isDurationDataFetching}
  374. error={durationError}
  375. />
  376. </ModuleLayout.Full>
  377. </Fragment>
  378. )}
  379. {query.panel === 'status' && (
  380. <Fragment>
  381. <ModuleLayout.Full>
  382. <ResponseCodeCountChart
  383. series={Object.values(responseCodeData).filter(Boolean)}
  384. isLoading={isResponseCodeDataLoading}
  385. error={responseCodeError}
  386. />
  387. </ModuleLayout.Full>
  388. </Fragment>
  389. )}
  390. <ModuleLayout.Full>
  391. <SpanSearchQueryBuilder
  392. projects={selection.projects}
  393. initialQuery={query.spanSearchQuery}
  394. onSearch={handleSearch}
  395. placeholder={t('Search for span attributes')}
  396. searchSource={`${ModuleName.HTTP}-sample-panel`}
  397. />
  398. </ModuleLayout.Full>
  399. {query.panel === 'duration' && (
  400. <Fragment>
  401. <ModuleLayout.Full>
  402. <SpanSamplesTable
  403. data={durationSamplesData}
  404. isLoading={isDurationDataFetching || isDurationSamplesDataFetching}
  405. highlightedSpanId={highlightedSpanId}
  406. onSampleMouseOver={sample => setHighlightedSpanId(sample.span_id)}
  407. onSampleMouseOut={() => setHighlightedSpanId(undefined)}
  408. error={durationSamplesDataError}
  409. // TODO: The samples endpoint doesn't provide its own meta, so we need to create it manually
  410. meta={{
  411. fields: {
  412. 'span.response_code': 'number',
  413. },
  414. units: {},
  415. }}
  416. referrer={TraceViewSources.REQUESTS_MODULE}
  417. />
  418. </ModuleLayout.Full>
  419. <ModuleLayout.Full>
  420. <Button
  421. onClick={() => {
  422. trackAnalytics(
  423. 'performance_views.sample_spans.try_different_samples_clicked',
  424. {organization, source: ModuleName.HTTP}
  425. );
  426. refetchDurationSpanSamples();
  427. }}
  428. >
  429. {t('Try Different Samples')}
  430. </Button>
  431. </ModuleLayout.Full>
  432. </Fragment>
  433. )}
  434. {query.panel === 'status' && (
  435. <Fragment>
  436. <ModuleLayout.Full>
  437. <SpanSamplesTable
  438. data={responseCodeSamplesData ?? []}
  439. isLoading={isResponseCodeSamplesDataFetching}
  440. error={responseCodeSamplesDataError}
  441. // TODO: The samples endpoint doesn't provide its own meta, so we need to create it manually
  442. meta={{
  443. fields: {
  444. 'span.response_code': 'number',
  445. },
  446. units: {},
  447. }}
  448. />
  449. </ModuleLayout.Full>
  450. <ModuleLayout.Full>
  451. <Button
  452. onClick={() => {
  453. trackAnalytics(
  454. 'performance_views.sample_spans.try_different_samples_clicked',
  455. {organization, source: ModuleName.HTTP}
  456. );
  457. refetchResponseCodeSpanSamples();
  458. }}
  459. >
  460. {t('Try Different Samples')}
  461. </Button>
  462. </ModuleLayout.Full>
  463. </Fragment>
  464. )}
  465. </ModuleLayout.Layout>
  466. </SampleDrawerBody>
  467. </PageAlertProvider>
  468. );
  469. }
  470. const SAMPLE_HOVER_DEBOUNCE = 10;
  471. const SPAN_SAMPLE_LIMIT = 10;
  472. // This is functionally a random sort, which is what we want
  473. const SPAN_SAMPLES_SORT = {
  474. field: 'span_id',
  475. kind: 'desc' as const,
  476. };
  477. const HTTP_RESPONSE_CODE_CLASS_OPTIONS = [
  478. {
  479. value: '',
  480. label: t('All'),
  481. },
  482. {
  483. value: '2',
  484. label: t('2XXs'),
  485. },
  486. {
  487. value: '3',
  488. label: t('3XXs'),
  489. },
  490. {
  491. value: '4',
  492. label: t('4XXs'),
  493. },
  494. {
  495. value: '5',
  496. label: t('5XXs'),
  497. },
  498. ];
  499. const PanelControls = styled('div')`
  500. display: flex;
  501. justify-content: space-between;
  502. gap: ${space(2)};
  503. `;