samplePanel.tsx 16 KB

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