samplePanel.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. import {Fragment, useCallback} from 'react';
  2. import styled from '@emotion/styled';
  3. import keyBy from 'lodash/keyBy';
  4. import * as qs from 'query-string';
  5. import Feature from 'sentry/components/acl/feature';
  6. import ProjectAvatar from 'sentry/components/avatar/projectAvatar';
  7. import {Button} from 'sentry/components/button';
  8. import {CompactSelect} from 'sentry/components/compactSelect';
  9. import SearchBar from 'sentry/components/events/searchBar';
  10. import Link from 'sentry/components/links/link';
  11. import {t} from 'sentry/locale';
  12. import {space} from 'sentry/styles/space';
  13. import {trackAnalytics} from 'sentry/utils/analytics';
  14. import {DurationUnit, RateUnit, SizeUnit} from 'sentry/utils/discover/fields';
  15. import {DiscoverDatasets} from 'sentry/utils/discover/types';
  16. import {PageAlertProvider} from 'sentry/utils/performance/contexts/pageAlert';
  17. import {decodeScalar} from 'sentry/utils/queryString';
  18. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  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 {normalizeUrl} from 'sentry/utils/withDomainRequired';
  26. import {CacheHitMissChart} from 'sentry/views/performance/cache/charts/hitMissChart';
  27. import {Referrer} from 'sentry/views/performance/cache/referrers';
  28. import {TransactionDurationChart} from 'sentry/views/performance/cache/samplePanel/charts/transactionDurationChart';
  29. import {BASE_FILTERS} from 'sentry/views/performance/cache/settings';
  30. import {SpanSamplesTable} from 'sentry/views/performance/cache/tables/spanSamplesTable';
  31. import {useDebouncedState} from 'sentry/views/performance/http/useDebouncedState';
  32. import {MetricReadout} from 'sentry/views/performance/metricReadout';
  33. import * as ModuleLayout from 'sentry/views/performance/moduleLayout';
  34. import {useSpanFieldSupportedTags} from 'sentry/views/performance/utils/useSpanFieldSupportedTags';
  35. import DetailPanel from 'sentry/views/starfish/components/detailPanel';
  36. import {getTimeSpentExplanation} from 'sentry/views/starfish/components/tableCells/timeSpentCell';
  37. import {
  38. useMetrics,
  39. useSpanMetrics,
  40. useSpansIndexed,
  41. } from 'sentry/views/starfish/queries/useDiscover';
  42. import {useSpanMetricsSeries} from 'sentry/views/starfish/queries/useDiscoverSeries';
  43. import {useTransactions} from 'sentry/views/starfish/queries/useTransactions';
  44. import {
  45. MetricsFields,
  46. type MetricsQueryFilters,
  47. ModuleName,
  48. SpanFunction,
  49. SpanIndexedField,
  50. type SpanIndexedQueryFilters,
  51. type SpanIndexedResponse,
  52. SpanMetricsField,
  53. type SpanMetricsQueryFilters,
  54. } from 'sentry/views/starfish/types';
  55. import {findSampleFromDataPoint} from 'sentry/views/starfish/utils/chart/findDataPoint';
  56. import {DataTitles, getThroughputTitle} from 'sentry/views/starfish/views/spans/types';
  57. // This is similar to http sample table, its difficult to use the generic span samples sidebar as we require a bunch of custom things.
  58. export function CacheSamplePanel() {
  59. const router = useRouter();
  60. const location = useLocation();
  61. const organization = useOrganization();
  62. const {selection} = usePageFilters();
  63. const supportedTags = useSpanFieldSupportedTags();
  64. const query = useLocationQuery({
  65. fields: {
  66. project: decodeScalar,
  67. transaction: decodeScalar,
  68. statusClass: decodeScalar,
  69. spanSearchQuery: decodeScalar,
  70. },
  71. });
  72. const [highlightedSpanId, setHighlightedSpanId] = useDebouncedState<string | undefined>(
  73. undefined,
  74. [],
  75. 10
  76. );
  77. const handleStatusClassChange = newStatusClass => {
  78. trackAnalytics('performance_views.sample_spans.filter_updated', {
  79. filter: 'status',
  80. new_state: newStatusClass.value,
  81. organization,
  82. source: ModuleName.CACHE,
  83. });
  84. router.replace({
  85. pathname: location.pathname,
  86. query: {
  87. ...location.query,
  88. statusClass: newStatusClass.value,
  89. },
  90. });
  91. };
  92. // `detailKey` controls whether the panel is open. If all required properties are ailable, concat them to make a key, otherwise set to `undefined` and hide the panel
  93. const detailKey = query.transaction
  94. ? [query.transaction].filter(Boolean).join(':')
  95. : undefined;
  96. const isPanelOpen = Boolean(detailKey);
  97. const filters: SpanMetricsQueryFilters = {
  98. ...BASE_FILTERS,
  99. transaction: query.transaction,
  100. 'project.id': query.project,
  101. };
  102. const {data: cacheHitRateData, isLoading: isCacheHitRateLoading} = useSpanMetricsSeries(
  103. {
  104. search: MutableSearch.fromQueryObject(filters satisfies SpanMetricsQueryFilters),
  105. yAxis: [`${SpanFunction.CACHE_MISS_RATE}()`],
  106. },
  107. Referrer.SAMPLES_CACHE_HIT_MISS_CHART
  108. );
  109. const {data: cacheTransactionMetrics, isFetching: areCacheTransactionMetricsFetching} =
  110. useSpanMetrics(
  111. {
  112. search: MutableSearch.fromQueryObject(filters),
  113. fields: [
  114. `${SpanFunction.SPM}()`,
  115. `${SpanFunction.CACHE_MISS_RATE}()`,
  116. `${SpanFunction.TIME_SPENT_PERCENTAGE}()`,
  117. `sum(${SpanMetricsField.SPAN_SELF_TIME})`,
  118. `avg(${SpanMetricsField.CACHE_ITEM_SIZE})`,
  119. ],
  120. enabled: isPanelOpen,
  121. },
  122. Referrer.SAMPLES_CACHE_METRICS_RIBBON
  123. );
  124. const {data: transactionDurationData, isLoading: isTransactionDurationLoading} =
  125. useMetrics(
  126. {
  127. search: MutableSearch.fromQueryObject({
  128. transaction: query.transaction,
  129. } satisfies MetricsQueryFilters),
  130. fields: [`avg(${MetricsFields.TRANSACTION_DURATION})`],
  131. enabled: isPanelOpen && Boolean(query.transaction),
  132. },
  133. Referrer.SAMPLES_CACHE_TRANSACTION_DURATION
  134. );
  135. const sampleFilters: SpanIndexedQueryFilters = {
  136. ...BASE_FILTERS,
  137. transaction: query.transaction,
  138. project_id: query.project,
  139. };
  140. const useIndexedCacheSpans = (
  141. isCacheHit: SpanIndexedResponse['cache.hit'],
  142. limit: number
  143. ) =>
  144. useSpansIndexed(
  145. {
  146. search: MutableSearch.fromQueryObject({
  147. ...sampleFilters,
  148. ...new MutableSearch(query.spanSearchQuery).filters,
  149. 'cache.hit': isCacheHit,
  150. }),
  151. fields: [
  152. SpanIndexedField.PROJECT,
  153. SpanIndexedField.TRACE,
  154. SpanIndexedField.TRANSACTION_ID,
  155. SpanIndexedField.ID,
  156. SpanIndexedField.TIMESTAMP,
  157. SpanIndexedField.SPAN_DESCRIPTION,
  158. SpanIndexedField.CACHE_HIT,
  159. SpanIndexedField.SPAN_OP,
  160. SpanIndexedField.CACHE_ITEM_SIZE,
  161. ],
  162. sorts: [SPAN_SAMPLES_SORT],
  163. limit,
  164. enabled: isPanelOpen,
  165. },
  166. Referrer.SAMPLES_CACHE_SPAN_SAMPLES
  167. );
  168. // display half hits and half misses by default
  169. let cacheHitSamplesLimit = SPAN_SAMPLE_LIMIT / 2;
  170. let cacheMissSamplesLimit = SPAN_SAMPLE_LIMIT / 2;
  171. if (query.statusClass === 'hit') {
  172. cacheHitSamplesLimit = SPAN_SAMPLE_LIMIT;
  173. cacheMissSamplesLimit = -1;
  174. } else if (query.statusClass === 'miss') {
  175. cacheHitSamplesLimit = -1;
  176. cacheMissSamplesLimit = SPAN_SAMPLE_LIMIT;
  177. }
  178. const {
  179. data: cacheHitSamples,
  180. isFetching: isCacheHitsFetching,
  181. refetch: refetchCacheHits,
  182. } = useIndexedCacheSpans('true', cacheHitSamplesLimit);
  183. const {
  184. data: cacheMissSamples,
  185. isFetching: isCacheMissesFetching,
  186. refetch: refetchCacheMisses,
  187. } = useIndexedCacheSpans('false', cacheMissSamplesLimit);
  188. const cacheSamples = [...(cacheHitSamples || []), ...(cacheMissSamples || [])];
  189. const {
  190. data: transactionData,
  191. error: transactionError,
  192. isFetching: isFetchingTransactions,
  193. } = useTransactions(
  194. cacheSamples?.map(span => span['transaction.id']) || [],
  195. Referrer.SAMPLES_CACHE_SPAN_SAMPLES
  196. );
  197. const transactionDurationsMap = keyBy(transactionData, 'id');
  198. const spansWithDuration =
  199. cacheSamples?.map(span => ({
  200. ...span,
  201. 'transaction.duration':
  202. transactionDurationsMap[span['transaction.id']]?.['transaction.duration'],
  203. })) || [];
  204. const {projects} = useProjects();
  205. const project = projects.find(p => query.project === p.id);
  206. const handleSearch = (newSpanSearchQuery: string) => {
  207. router.replace({
  208. pathname: location.pathname,
  209. query: {
  210. ...query,
  211. spanSearchQuery: newSpanSearchQuery,
  212. },
  213. });
  214. };
  215. const handleClose = () => {
  216. router.replace({
  217. pathname: router.location.pathname,
  218. query: {
  219. ...router.location.query,
  220. transaction: undefined,
  221. transactionMethod: undefined,
  222. },
  223. });
  224. };
  225. const handleOpen = useCallback(() => {
  226. if (query.transaction) {
  227. trackAnalytics('performance_views.sample_spans.opened', {
  228. organization,
  229. source: ModuleName.CACHE,
  230. });
  231. }
  232. }, [organization, query.transaction]);
  233. const handleRefetch = () => {
  234. refetchCacheHits();
  235. refetchCacheMisses();
  236. };
  237. return (
  238. <PageAlertProvider>
  239. <DetailPanel detailKey={detailKey} onClose={handleClose} onOpen={handleOpen}>
  240. <ModuleLayout.Layout>
  241. <ModuleLayout.Full>
  242. <HeaderContainer>
  243. {project && (
  244. <SpanSummaryProjectAvatar
  245. project={project}
  246. direction="left"
  247. size={40}
  248. hasTooltip
  249. tooltip={project.slug}
  250. />
  251. )}
  252. <TitleContainer>
  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. <MetricsRibbon>
  272. <MetricReadout
  273. align="left"
  274. title={DataTitles[`avg(${SpanMetricsField.CACHE_ITEM_SIZE})`]}
  275. value={
  276. cacheTransactionMetrics?.[0]?.[
  277. `avg(${SpanMetricsField.CACHE_ITEM_SIZE})`
  278. ]
  279. }
  280. unit={SizeUnit.BYTE}
  281. isLoading={areCacheTransactionMetricsFetching}
  282. />
  283. <MetricReadout
  284. align="left"
  285. title={getThroughputTitle('cache')}
  286. value={cacheTransactionMetrics?.[0]?.[`${SpanFunction.SPM}()`]}
  287. unit={RateUnit.PER_MINUTE}
  288. isLoading={areCacheTransactionMetricsFetching}
  289. />
  290. <MetricReadout
  291. align="left"
  292. title={DataTitles[`avg(${MetricsFields.TRANSACTION_DURATION})`]}
  293. value={
  294. transactionDurationData?.[0]?.[
  295. `avg(${MetricsFields.TRANSACTION_DURATION})`
  296. ]
  297. }
  298. unit={DurationUnit.MILLISECOND}
  299. isLoading={isTransactionDurationLoading}
  300. />
  301. <MetricReadout
  302. align="left"
  303. title={DataTitles[`${SpanFunction.CACHE_MISS_RATE}()`]}
  304. value={
  305. cacheTransactionMetrics?.[0]?.[`${SpanFunction.CACHE_MISS_RATE}()`]
  306. }
  307. unit="percentage"
  308. isLoading={areCacheTransactionMetricsFetching}
  309. />
  310. <MetricReadout
  311. align="left"
  312. title={DataTitles.timeSpent}
  313. value={cacheTransactionMetrics?.[0]?.['sum(span.self_time)']}
  314. unit={DurationUnit.MILLISECOND}
  315. tooltip={getTimeSpentExplanation(
  316. cacheTransactionMetrics?.[0]?.['time_spent_percentage()']
  317. )}
  318. isLoading={areCacheTransactionMetricsFetching}
  319. />
  320. </MetricsRibbon>
  321. </ModuleLayout.Full>
  322. <ModuleLayout.Full>
  323. <CompactSelect
  324. value={query.statusClass}
  325. options={CACHE_STATUS_OPTIONS}
  326. onChange={handleStatusClassChange}
  327. triggerProps={{
  328. prefix: t('Status'),
  329. }}
  330. />
  331. </ModuleLayout.Full>
  332. <ModuleLayout.Half>
  333. <CacheHitMissChart
  334. isLoading={isCacheHitRateLoading}
  335. series={cacheHitRateData[`cache_miss_rate()`]}
  336. />
  337. </ModuleLayout.Half>
  338. <ModuleLayout.Half>
  339. <TransactionDurationChart
  340. samples={spansWithDuration}
  341. averageTransactionDuration={
  342. transactionDurationData?.[0]?.[
  343. `avg(${MetricsFields.TRANSACTION_DURATION})`
  344. ]
  345. }
  346. highlightedSpanId={highlightedSpanId}
  347. onHighlight={highlights => {
  348. const firstHighlight = highlights[0];
  349. if (!firstHighlight) {
  350. setHighlightedSpanId(undefined);
  351. return;
  352. }
  353. const sample = findSampleFromDataPoint<(typeof spansWithDuration)[0]>(
  354. firstHighlight.dataPoint,
  355. spansWithDuration,
  356. 'transaction.duration'
  357. );
  358. setHighlightedSpanId(sample?.span_id);
  359. }}
  360. />
  361. </ModuleLayout.Half>
  362. <Feature features="performance-sample-panel-search">
  363. <ModuleLayout.Full>
  364. <SearchBar
  365. searchSource={`${ModuleName.CACHE}-sample-panel`}
  366. query={query.spanSearchQuery}
  367. onSearch={handleSearch}
  368. placeholder={t('Search for span attributes')}
  369. organization={organization}
  370. metricAlert={false}
  371. supportedTags={supportedTags}
  372. dataset={DiscoverDatasets.SPANS_INDEXED}
  373. projectIds={selection.projects}
  374. />
  375. </ModuleLayout.Full>
  376. </Feature>
  377. <Fragment>
  378. <ModuleLayout.Full>
  379. <SpanSamplesTable
  380. data={spansWithDuration ?? []}
  381. meta={{
  382. fields: {
  383. 'transaction.duration': 'duration',
  384. [SpanIndexedField.CACHE_ITEM_SIZE]: 'size',
  385. },
  386. units: {[SpanIndexedField.CACHE_ITEM_SIZE]: 'byte'},
  387. }}
  388. isLoading={
  389. isCacheHitsFetching || isCacheMissesFetching || isFetchingTransactions
  390. }
  391. highlightedSpanId={highlightedSpanId}
  392. onSampleMouseOver={sample => setHighlightedSpanId(sample.span_id)}
  393. onSampleMouseOut={() => setHighlightedSpanId(undefined)}
  394. error={transactionError}
  395. />
  396. </ModuleLayout.Full>
  397. </Fragment>
  398. <Fragment>
  399. <ModuleLayout.Full>
  400. <Button
  401. onClick={() => {
  402. trackAnalytics(
  403. 'performance_views.sample_spans.try_different_samples_clicked',
  404. {organization, source: ModuleName.CACHE}
  405. );
  406. handleRefetch();
  407. }}
  408. >
  409. {t('Try Different Samples')}
  410. </Button>
  411. </ModuleLayout.Full>
  412. </Fragment>
  413. </ModuleLayout.Layout>
  414. </DetailPanel>
  415. </PageAlertProvider>
  416. );
  417. }
  418. const SPAN_SAMPLE_LIMIT = 10;
  419. const SPAN_SAMPLES_SORT = {
  420. field: 'span_id',
  421. kind: 'desc' as const,
  422. };
  423. const CACHE_STATUS_OPTIONS = [
  424. {
  425. value: '',
  426. label: t('All'),
  427. },
  428. {
  429. value: 'hit',
  430. label: t('Hit'),
  431. },
  432. {
  433. value: 'miss',
  434. label: t('Miss'),
  435. },
  436. ];
  437. const SpanSummaryProjectAvatar = styled(ProjectAvatar)`
  438. padding-right: ${space(1)};
  439. `;
  440. const HeaderContainer = styled('div')`
  441. display: grid;
  442. grid-template-rows: auto auto auto;
  443. @media (min-width: ${p => p.theme.breakpoints.small}) {
  444. grid-template-rows: auto;
  445. grid-template-columns: auto 1fr auto;
  446. }
  447. `;
  448. const TitleContainer = styled('div')`
  449. width: 100%;
  450. position: relative;
  451. height: 40px;
  452. `;
  453. const Title = styled('h4')`
  454. position: absolute;
  455. bottom: 0;
  456. margin-bottom: 0;
  457. `;
  458. const MetricsRibbon = styled('div')`
  459. display: flex;
  460. flex-wrap: wrap;
  461. gap: ${space(4)};
  462. `;