httpSamplesPanel.tsx 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. import {Fragment, useCallback} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as qs from 'query-string';
  4. import ProjectAvatar from 'sentry/components/avatar/projectAvatar';
  5. import {Button} from 'sentry/components/button';
  6. import {CompactSelect} from 'sentry/components/compactSelect';
  7. import Link from 'sentry/components/links/link';
  8. import {SegmentedControl} from 'sentry/components/segmentedControl';
  9. import {t} from 'sentry/locale';
  10. import {space} from 'sentry/styles/space';
  11. import {trackAnalytics} from 'sentry/utils/analytics';
  12. import {DurationUnit, RateUnit} from 'sentry/utils/discover/fields';
  13. import {PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  14. import {decodeScalar} from 'sentry/utils/queryString';
  15. import {
  16. EMPTY_OPTION_VALUE,
  17. escapeFilterValue,
  18. MutableSearch,
  19. } from 'sentry/utils/tokenizeSearch';
  20. import useLocationQuery from 'sentry/utils/url/useLocationQuery';
  21. import {useLocation} from 'sentry/utils/useLocation';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import useProjects from 'sentry/utils/useProjects';
  24. import useRouter from 'sentry/utils/useRouter';
  25. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  26. import {AverageValueMarkLine} from 'sentry/views/performance/charts/averageValueMarkLine';
  27. import {DurationChart} from 'sentry/views/performance/http/charts/durationChart';
  28. import {ResponseCodeCountChart} from 'sentry/views/performance/http/charts/responseCodeCountChart';
  29. import {HTTP_RESPONSE_STATUS_CODES} from 'sentry/views/performance/http/data/definitions';
  30. import {useSpanSamples} from 'sentry/views/performance/http/data/useSpanSamples';
  31. import decodePanel from 'sentry/views/performance/http/queryParameterDecoders/panel';
  32. import decodeResponseCodeClass from 'sentry/views/performance/http/queryParameterDecoders/responseCodeClass';
  33. import {Referrer} from 'sentry/views/performance/http/referrers';
  34. import {BASE_FILTERS} from 'sentry/views/performance/http/settings';
  35. import {SpanSamplesTable} from 'sentry/views/performance/http/tables/spanSamplesTable';
  36. import {useDebouncedState} from 'sentry/views/performance/http/useDebouncedState';
  37. import {MetricReadout} from 'sentry/views/performance/metricReadout';
  38. import * as ModuleLayout from 'sentry/views/performance/moduleLayout';
  39. import {computeAxisMax} from 'sentry/views/starfish/components/chart';
  40. import DetailPanel from 'sentry/views/starfish/components/detailPanel';
  41. import {getTimeSpentExplanation} from 'sentry/views/starfish/components/tableCells/timeSpentCell';
  42. import {useSpanMetrics} from 'sentry/views/starfish/queries/useDiscover';
  43. import {useSpanMetricsSeries} from 'sentry/views/starfish/queries/useDiscoverSeries';
  44. import {useIndexedSpans} from 'sentry/views/starfish/queries/useIndexedSpans';
  45. import {useSpanMetricsTopNSeries} from 'sentry/views/starfish/queries/useSpanMetricsTopNSeries';
  46. import {
  47. ModuleName,
  48. SpanFunction,
  49. SpanIndexedField,
  50. SpanMetricsField,
  51. type SpanMetricsQueryFilters,
  52. } from 'sentry/views/starfish/types';
  53. import {findSampleFromDataPoint} from 'sentry/views/starfish/utils/chart/findDataPoint';
  54. import {DataTitles, getThroughputTitle} from 'sentry/views/starfish/views/spans/types';
  55. import {useSampleScatterPlotSeries} from 'sentry/views/starfish/views/spanSummaryPage/sampleList/durationChart/useSampleScatterPlotSeries';
  56. export function HTTPSamplesPanel() {
  57. const router = useRouter();
  58. const location = useLocation();
  59. const query = useLocationQuery({
  60. fields: {
  61. project: decodeScalar,
  62. domain: decodeScalar,
  63. transaction: decodeScalar,
  64. transactionMethod: decodeScalar,
  65. panel: decodePanel,
  66. responseCodeClass: decodeResponseCodeClass,
  67. },
  68. });
  69. const organization = useOrganization();
  70. const {projects} = useProjects();
  71. const project = projects.find(p => query.project === p.id);
  72. const [highlightedSpanId, setHighlightedSpanId] = useDebouncedState<string | undefined>(
  73. undefined,
  74. [],
  75. SAMPLE_HOVER_DEBOUNCE
  76. );
  77. // `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
  78. const detailKey = query.transaction
  79. ? [query.domain, query.transactionMethod, query.transaction].filter(Boolean).join(':')
  80. : undefined;
  81. const handlePanelChange = newPanelName => {
  82. trackAnalytics('performance_views.sample_spans.filter_updated', {
  83. filter: 'panel',
  84. new_state: newPanelName,
  85. organization,
  86. source: ModuleName.HTTP,
  87. });
  88. router.replace({
  89. pathname: location.pathname,
  90. query: {
  91. ...location.query,
  92. panel: newPanelName,
  93. },
  94. });
  95. };
  96. const handleResponseCodeClassChange = newResponseCodeClass => {
  97. trackAnalytics('performance_views.sample_spans.filter_updated', {
  98. filter: 'status_code',
  99. new_state: newResponseCodeClass.value,
  100. organization,
  101. source: ModuleName.HTTP,
  102. });
  103. router.replace({
  104. pathname: location.pathname,
  105. query: {
  106. ...location.query,
  107. responseCodeClass: newResponseCodeClass.value,
  108. },
  109. });
  110. };
  111. const isPanelOpen = Boolean(detailKey);
  112. // The ribbon is above the data selectors, and not affected by them. So, it has its own filters.
  113. const ribbonFilters: SpanMetricsQueryFilters = {
  114. ...BASE_FILTERS,
  115. 'span.domain':
  116. query.domain === '' ? EMPTY_OPTION_VALUE : escapeFilterValue(query.domain),
  117. transaction: query.transaction,
  118. };
  119. // These filters are for the charts and samples tables
  120. const filters: SpanMetricsQueryFilters = {
  121. ...BASE_FILTERS,
  122. 'span.domain':
  123. query.domain === '' ? EMPTY_OPTION_VALUE : escapeFilterValue(query.domain),
  124. transaction: query.transaction,
  125. };
  126. const responseCodeInRange = query.responseCodeClass
  127. ? Object.keys(HTTP_RESPONSE_STATUS_CODES).filter(code =>
  128. code.startsWith(query.responseCodeClass)
  129. )
  130. : [];
  131. if (responseCodeInRange.length > 0) {
  132. // TODO: Allow automatic array parameter concatenation
  133. filters['span.status_code'] = `[${responseCodeInRange.join(',')}]`;
  134. }
  135. const search = MutableSearch.fromQueryObject(filters);
  136. const {
  137. data: domainTransactionMetrics,
  138. isFetching: areDomainTransactionMetricsFetching,
  139. } = useSpanMetrics(
  140. {
  141. search: MutableSearch.fromQueryObject(ribbonFilters),
  142. fields: [
  143. `${SpanFunction.SPM}()`,
  144. `avg(${SpanMetricsField.SPAN_SELF_TIME})`,
  145. `sum(${SpanMetricsField.SPAN_SELF_TIME})`,
  146. 'http_response_rate(3)',
  147. 'http_response_rate(4)',
  148. 'http_response_rate(5)',
  149. `${SpanFunction.TIME_SPENT_PERCENTAGE}()`,
  150. ],
  151. enabled: isPanelOpen,
  152. },
  153. Referrer.SAMPLES_PANEL_METRICS_RIBBON
  154. );
  155. const {
  156. isFetching: isDurationDataFetching,
  157. data: durationData,
  158. error: durationError,
  159. } = useSpanMetricsSeries(
  160. {
  161. search,
  162. yAxis: [`avg(span.self_time)`],
  163. enabled: isPanelOpen && query.panel === 'duration',
  164. },
  165. Referrer.SAMPLES_PANEL_DURATION_CHART
  166. );
  167. const {
  168. isFetching: isResponseCodeDataLoading,
  169. data: responseCodeData,
  170. error: responseCodeError,
  171. } = useSpanMetricsTopNSeries({
  172. search,
  173. fields: ['span.status_code', 'count()'],
  174. yAxis: ['count()'],
  175. topEvents: 5,
  176. enabled: isPanelOpen && query.panel === 'status',
  177. referrer: Referrer.SAMPLES_PANEL_RESPONSE_CODE_CHART,
  178. });
  179. // NOTE: Due to some data confusion, the `domain` column in the spans table can either be `null` or `""`. Searches like `"!has:span.domain"` are turned into the ClickHouse clause `isNull(domain)`, and do not match the empty string. We need a query that matches empty strings _and_ null_ which is `(!has:domain OR domain:[""])`. This hack can be removed in August 2024, once https://github.com/getsentry/snuba/pull/5780 has been deployed for 90 days and all `""` domains have fallen out of the data retention window. Also, `null` domains will become more rare as people upgrade the JS SDK to versions that populate the `server.address` span attribute
  180. const sampleSpansSearch = MutableSearch.fromQueryObject({
  181. ...filters,
  182. 'span.domain': undefined,
  183. });
  184. if (query.domain === '') {
  185. sampleSpansSearch.addOp('(');
  186. sampleSpansSearch.addFilterValue('!has', 'span.domain');
  187. sampleSpansSearch.addOp('OR');
  188. // HACK: Use `addOp` to add the condition `'span.domain:[""]'` and avoid escaping the double quotes. Ideally there'd be a way to specify this explicitly, but this whole thing is a hack anyway. Once a plain `!has:span.domain` condition works, this is not necessary
  189. sampleSpansSearch.addOp('span.domain:[""]');
  190. sampleSpansSearch.addOp(')');
  191. } else {
  192. sampleSpansSearch.addFilterValue('span.domain', query.domain);
  193. }
  194. const durationAxisMax = computeAxisMax([durationData?.[`avg(span.self_time)`]]);
  195. const {
  196. data: durationSamplesData,
  197. isFetching: isDurationSamplesDataFetching,
  198. error: durationSamplesDataError,
  199. refetch: refetchDurationSpanSamples,
  200. } = useSpanSamples({
  201. search: sampleSpansSearch,
  202. fields: [
  203. SpanIndexedField.TRACE,
  204. SpanIndexedField.TRANSACTION_ID,
  205. SpanIndexedField.SPAN_DESCRIPTION,
  206. SpanIndexedField.RESPONSE_CODE,
  207. ],
  208. min: 0,
  209. max: durationAxisMax,
  210. enabled: isPanelOpen && query.panel === 'duration' && durationAxisMax > 0,
  211. referrer: Referrer.SAMPLES_PANEL_DURATION_SAMPLES,
  212. });
  213. const {
  214. data: responseCodeSamplesData,
  215. isFetching: isResponseCodeSamplesDataFetching,
  216. error: responseCodeSamplesDataError,
  217. refetch: refetchResponseCodeSpanSamples,
  218. } = useIndexedSpans({
  219. search: sampleSpansSearch,
  220. fields: [
  221. SpanIndexedField.PROJECT,
  222. SpanIndexedField.TRACE,
  223. SpanIndexedField.TRANSACTION_ID,
  224. SpanIndexedField.ID,
  225. SpanIndexedField.TIMESTAMP,
  226. SpanIndexedField.SPAN_DESCRIPTION,
  227. SpanIndexedField.RESPONSE_CODE,
  228. ],
  229. sorts: [SPAN_SAMPLES_SORT],
  230. limit: SPAN_SAMPLE_LIMIT,
  231. enabled: isPanelOpen && query.panel === 'status',
  232. referrer: Referrer.SAMPLES_PANEL_RESPONSE_CODE_SAMPLES,
  233. });
  234. const sampledSpanDataSeries = useSampleScatterPlotSeries(
  235. durationSamplesData,
  236. domainTransactionMetrics?.[0]?.['avg(span.self_time)'],
  237. highlightedSpanId
  238. );
  239. const handleClose = () => {
  240. router.replace({
  241. pathname: router.location.pathname,
  242. query: {
  243. ...router.location.query,
  244. transaction: undefined,
  245. transactionMethod: undefined,
  246. },
  247. });
  248. };
  249. const handleOpen = useCallback(() => {
  250. if (query.transaction) {
  251. trackAnalytics('performance_views.sample_spans.opened', {
  252. organization,
  253. source: ModuleName.HTTP,
  254. });
  255. }
  256. }, [organization, query.transaction]);
  257. return (
  258. <PageAlertProvider>
  259. <DetailPanel detailKey={detailKey} onClose={handleClose} onOpen={handleOpen}>
  260. <ModuleLayout.Layout>
  261. <ModuleLayout.Full>
  262. <HeaderContainer>
  263. {project && (
  264. <SpanSummaryProjectAvatar
  265. project={project}
  266. direction="left"
  267. size={40}
  268. hasTooltip
  269. tooltip={project.slug}
  270. />
  271. )}
  272. <TitleContainer>
  273. <Title>
  274. <Link
  275. to={normalizeUrl(
  276. `/organizations/${organization.slug}/performance/summary?${qs.stringify(
  277. {
  278. project: query.project,
  279. transaction: query.transaction,
  280. }
  281. )}`
  282. )}
  283. >
  284. {query.transaction &&
  285. query.transactionMethod &&
  286. !query.transaction.startsWith(query.transactionMethod)
  287. ? `${query.transactionMethod} ${query.transaction}`
  288. : query.transaction}
  289. </Link>
  290. </Title>
  291. </TitleContainer>
  292. </HeaderContainer>
  293. </ModuleLayout.Full>
  294. <ModuleLayout.Full>
  295. <MetricsRibbon>
  296. <MetricReadout
  297. align="left"
  298. title={getThroughputTitle('http')}
  299. value={domainTransactionMetrics?.[0]?.[`${SpanFunction.SPM}()`]}
  300. unit={RateUnit.PER_MINUTE}
  301. isLoading={areDomainTransactionMetricsFetching}
  302. />
  303. <MetricReadout
  304. align="left"
  305. title={DataTitles.avg}
  306. value={
  307. domainTransactionMetrics?.[0]?.[
  308. `avg(${SpanMetricsField.SPAN_SELF_TIME})`
  309. ]
  310. }
  311. unit={DurationUnit.MILLISECOND}
  312. isLoading={areDomainTransactionMetricsFetching}
  313. />
  314. <MetricReadout
  315. align="left"
  316. title={t('3XXs')}
  317. value={domainTransactionMetrics?.[0]?.[`http_response_rate(3)`]}
  318. unit="percentage"
  319. isLoading={areDomainTransactionMetricsFetching}
  320. />
  321. <MetricReadout
  322. align="left"
  323. title={t('4XXs')}
  324. value={domainTransactionMetrics?.[0]?.[`http_response_rate(4)`]}
  325. unit="percentage"
  326. isLoading={areDomainTransactionMetricsFetching}
  327. />
  328. <MetricReadout
  329. align="left"
  330. title={t('5XXs')}
  331. value={domainTransactionMetrics?.[0]?.[`http_response_rate(5)`]}
  332. unit="percentage"
  333. isLoading={areDomainTransactionMetricsFetching}
  334. />
  335. <MetricReadout
  336. align="left"
  337. title={DataTitles.timeSpent}
  338. value={domainTransactionMetrics?.[0]?.['sum(span.self_time)']}
  339. unit={DurationUnit.MILLISECOND}
  340. tooltip={getTimeSpentExplanation(
  341. domainTransactionMetrics?.[0]?.['time_spent_percentage()'],
  342. 'http.client'
  343. )}
  344. isLoading={areDomainTransactionMetricsFetching}
  345. />
  346. </MetricsRibbon>
  347. </ModuleLayout.Full>
  348. <ModuleLayout.Full>
  349. <PanelControls>
  350. <SegmentedControl
  351. value={query.panel}
  352. onChange={handlePanelChange}
  353. aria-label={t('Choose breakdown type')}
  354. >
  355. <SegmentedControl.Item key="duration">
  356. {t('By Duration')}
  357. </SegmentedControl.Item>
  358. <SegmentedControl.Item key="status">
  359. {t('By Response Code')}
  360. </SegmentedControl.Item>
  361. </SegmentedControl>
  362. <CompactSelect
  363. value={query.responseCodeClass}
  364. options={HTTP_RESPONSE_CODE_CLASS_OPTIONS}
  365. onChange={handleResponseCodeClassChange}
  366. triggerProps={{
  367. prefix: t('Response Code'),
  368. }}
  369. />
  370. </PanelControls>
  371. </ModuleLayout.Full>
  372. {query.panel === 'duration' && (
  373. <Fragment>
  374. <ModuleLayout.Full>
  375. <DurationChart
  376. series={[
  377. {
  378. ...durationData[`avg(span.self_time)`],
  379. markLine: AverageValueMarkLine(),
  380. },
  381. ]}
  382. scatterPlot={sampledSpanDataSeries}
  383. onHighlight={highlights => {
  384. const firstHighlight = highlights[0];
  385. if (!firstHighlight) {
  386. setHighlightedSpanId(undefined);
  387. return;
  388. }
  389. const sample = findSampleFromDataPoint<
  390. (typeof durationSamplesData)[0]
  391. >(
  392. firstHighlight.dataPoint,
  393. durationSamplesData,
  394. SpanIndexedField.SPAN_SELF_TIME
  395. );
  396. setHighlightedSpanId(sample?.span_id);
  397. }}
  398. isLoading={isDurationDataFetching}
  399. error={durationError}
  400. />
  401. </ModuleLayout.Full>
  402. <ModuleLayout.Full>
  403. <SpanSamplesTable
  404. data={durationSamplesData}
  405. isLoading={isDurationDataFetching || isDurationSamplesDataFetching}
  406. highlightedSpanId={highlightedSpanId}
  407. onSampleMouseOver={sample => setHighlightedSpanId(sample.span_id)}
  408. onSampleMouseOut={() => setHighlightedSpanId(undefined)}
  409. error={durationSamplesDataError}
  410. // TODO: The samples endpoint doesn't provide its own meta, so we need to create it manually
  411. meta={{
  412. fields: {
  413. 'span.response_code': 'number',
  414. },
  415. units: {},
  416. }}
  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. <ResponseCodeCountChart
  438. series={Object.values(responseCodeData).filter(Boolean)}
  439. isLoading={isResponseCodeDataLoading}
  440. error={responseCodeError}
  441. />
  442. </ModuleLayout.Full>
  443. <ModuleLayout.Full>
  444. <SpanSamplesTable
  445. data={responseCodeSamplesData ?? []}
  446. isLoading={isResponseCodeSamplesDataFetching}
  447. error={responseCodeSamplesDataError}
  448. // TODO: The samples endpoint doesn't provide its own meta, so we need to create it manually
  449. meta={{
  450. fields: {
  451. 'span.response_code': 'number',
  452. },
  453. units: {},
  454. }}
  455. />
  456. </ModuleLayout.Full>
  457. <ModuleLayout.Full>
  458. <Button
  459. onClick={() => {
  460. trackAnalytics(
  461. 'performance_views.sample_spans.try_different_samples_clicked',
  462. {organization, source: ModuleName.HTTP}
  463. );
  464. refetchResponseCodeSpanSamples();
  465. }}
  466. >
  467. {t('Try Different Samples')}
  468. </Button>
  469. </ModuleLayout.Full>
  470. </Fragment>
  471. )}
  472. </ModuleLayout.Layout>
  473. </DetailPanel>
  474. </PageAlertProvider>
  475. );
  476. }
  477. const SAMPLE_HOVER_DEBOUNCE = 10;
  478. const SPAN_SAMPLE_LIMIT = 10;
  479. // This is functionally a random sort, which is what we want
  480. const SPAN_SAMPLES_SORT = {
  481. field: 'span_id',
  482. kind: 'desc' as const,
  483. };
  484. const SpanSummaryProjectAvatar = styled(ProjectAvatar)`
  485. padding-right: ${space(1)};
  486. `;
  487. const HTTP_RESPONSE_CODE_CLASS_OPTIONS = [
  488. {
  489. value: '',
  490. label: t('All'),
  491. },
  492. {
  493. value: '2',
  494. label: t('2XXs'),
  495. },
  496. {
  497. value: '3',
  498. label: t('3XXs'),
  499. },
  500. {
  501. value: '4',
  502. label: t('4XXs'),
  503. },
  504. {
  505. value: '5',
  506. label: t('5XXs'),
  507. },
  508. ];
  509. const HeaderContainer = styled('div')`
  510. display: grid;
  511. grid-template-rows: auto auto auto;
  512. @media (min-width: ${p => p.theme.breakpoints.small}) {
  513. grid-template-rows: auto;
  514. grid-template-columns: auto 1fr auto;
  515. }
  516. `;
  517. const TitleContainer = styled('div')`
  518. width: 100%;
  519. position: relative;
  520. height: 40px;
  521. `;
  522. const Title = styled('h4')`
  523. position: absolute;
  524. bottom: 0;
  525. margin-bottom: 0;
  526. `;
  527. const MetricsRibbon = styled('div')`
  528. display: flex;
  529. flex-wrap: wrap;
  530. gap: ${space(4)};
  531. `;
  532. const PanelControls = styled('div')`
  533. display: flex;
  534. justify-content: space-between;
  535. gap: ${space(2)};
  536. `;