vitalCard.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. import {Component} from 'react';
  2. import type {Theme} from '@emotion/react';
  3. import {withTheme} from '@emotion/react';
  4. import styled from '@emotion/styled';
  5. import type {Location} from 'history';
  6. import isEqual from 'lodash/isEqual';
  7. import throttle from 'lodash/throttle';
  8. import {Button} from 'sentry/components/button';
  9. import type {BarChartSeries} from 'sentry/components/charts/barChart';
  10. import {BarChart} from 'sentry/components/charts/barChart';
  11. import BarChartZoom from 'sentry/components/charts/barChartZoom';
  12. import MarkLine from 'sentry/components/charts/components/markLine';
  13. import TransparentLoadingMask from 'sentry/components/charts/transparentLoadingMask';
  14. import Placeholder from 'sentry/components/placeholder';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {Organization} from 'sentry/types/organization';
  18. import {trackAnalytics} from 'sentry/utils/analytics';
  19. import type EventView from 'sentry/utils/discover/eventView';
  20. import {getAggregateAlias} from 'sentry/utils/discover/fields';
  21. import getDuration from 'sentry/utils/duration/getDuration';
  22. import type {WebVital} from 'sentry/utils/fields';
  23. import {formatAbbreviatedNumber} from 'sentry/utils/formatters';
  24. import getDynamicText from 'sentry/utils/getDynamicText';
  25. import {formatFloat} from 'sentry/utils/number/formatFloat';
  26. import type {DataFilter, HistogramData} from 'sentry/utils/performance/histogram/types';
  27. import {
  28. computeBuckets,
  29. formatHistogramData,
  30. } from 'sentry/utils/performance/histogram/utils';
  31. import type {Vital} from 'sentry/utils/performance/vitals/types';
  32. import type {VitalData} from 'sentry/utils/performance/vitals/vitalsCardsDiscoverQuery';
  33. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  34. import {EventsDisplayFilterName} from 'sentry/views/performance/transactionSummary/transactionEvents/utils';
  35. import {VitalBar} from '../../landing/vitalsCards';
  36. import {
  37. VitalState,
  38. vitalStateColors,
  39. webVitalMeh,
  40. webVitalPoor,
  41. } from '../../vitalDetail/utils';
  42. import {NUM_BUCKETS, PERCENTILE} from './constants';
  43. import {Card, CardSectionHeading, CardSummary, Description, StatNumber} from './styles';
  44. import type {Rectangle} from './types';
  45. import {asPixelRect, findNearestBucketIndex, getRefRect, mapPoint} from './utils';
  46. type Props = {
  47. chartData: HistogramData;
  48. colors: [string];
  49. error: boolean;
  50. eventView: EventView;
  51. isLoading: boolean;
  52. location: Location;
  53. organization: Organization;
  54. summaryData: VitalData | null;
  55. theme: Theme;
  56. vital: WebVital;
  57. vitalDetails: Vital;
  58. dataFilter?: DataFilter;
  59. max?: number;
  60. min?: number;
  61. precision?: number;
  62. };
  63. type State = {
  64. /**
  65. * This is a pair of reference points on the graph that we can use to map any
  66. * other points to their pixel coordinates on the graph.
  67. *
  68. * The x values here are the index of the cooresponding bucket and the y value
  69. * are the respective counts.
  70. *
  71. * Invariances:
  72. * - refDataRect.point1.x < refDataRect.point2.x
  73. * - refDataRect.point1.y < refDataRect.point2.y
  74. */
  75. refDataRect: Rectangle | null;
  76. /**
  77. * This is the cooresponding pixel coordinate of the references points from refDataRect.
  78. *
  79. * ECharts' pixel coordinates are relative to the top left whereas the axis coordinates
  80. * used here are relative to the bottom right. Because of this and the invariances imposed
  81. * on refDataRect, these points have the difference invariances.
  82. *
  83. * Invariances:
  84. * - refPixelRect.point1.x < refPixelRect.point2.x
  85. * - refPixelRect.point1.y > refPixelRect.point2.y
  86. */
  87. refPixelRect: Rectangle | null;
  88. };
  89. class VitalCard extends Component<Props, State> {
  90. state: State = {
  91. refDataRect: null,
  92. refPixelRect: null,
  93. };
  94. static getDerivedStateFromProps(nextProps: Readonly<Props>, prevState: State) {
  95. const {isLoading, error, chartData} = nextProps;
  96. if (isLoading || error === null) {
  97. return {...prevState};
  98. }
  99. const refDataRect = getRefRect(chartData);
  100. if (
  101. prevState.refDataRect === null ||
  102. (refDataRect !== null && !isEqual(refDataRect, prevState.refDataRect))
  103. ) {
  104. return {
  105. ...prevState,
  106. refDataRect,
  107. };
  108. }
  109. return {...prevState};
  110. }
  111. trackOpenInDiscoverClicked = () => {
  112. const {organization} = this.props;
  113. const {vitalDetails: vital} = this.props;
  114. trackAnalytics('performance_views.vitals.open_in_discover', {
  115. organization,
  116. vital: vital.slug,
  117. });
  118. };
  119. trackOpenAllEventsClicked = () => {
  120. const {organization} = this.props;
  121. const {vitalDetails: vital} = this.props;
  122. trackAnalytics('performance_views.vitals.open_all_events', {
  123. organization,
  124. vital: vital.slug,
  125. });
  126. };
  127. get summary() {
  128. const {summaryData} = this.props;
  129. return summaryData?.p75 ?? null;
  130. }
  131. get failureRate() {
  132. const {summaryData} = this.props;
  133. const numerator = summaryData?.poor ?? 0;
  134. const denominator = summaryData?.total ?? 0;
  135. return denominator <= 0 ? 0 : numerator / denominator;
  136. }
  137. getFormattedStatNumber() {
  138. const {vitalDetails: vital} = this.props;
  139. const summary = this.summary;
  140. const {type} = vital;
  141. return summary === null
  142. ? '\u2014'
  143. : type === 'duration'
  144. ? getDuration(summary / 1000, 2, true)
  145. : formatFloat(summary, 2);
  146. }
  147. renderSummary() {
  148. const {
  149. vitalDetails: vital,
  150. eventView,
  151. organization,
  152. min,
  153. max,
  154. dataFilter,
  155. } = this.props;
  156. const {slug, name, description} = vital;
  157. const column = `measurements.${slug}`;
  158. const newEventView = eventView
  159. .withColumns([
  160. {kind: 'field', field: 'transaction'},
  161. {
  162. kind: 'function',
  163. function: ['percentile', column, PERCENTILE.toString(), undefined],
  164. },
  165. {kind: 'function', function: ['count', '', '', undefined]},
  166. ])
  167. .withSorts([
  168. {
  169. kind: 'desc',
  170. field: getAggregateAlias(`percentile(${column},${PERCENTILE.toString()})`),
  171. },
  172. ]);
  173. const query = new MutableSearch(newEventView.query ?? '');
  174. query.addFilterValues('has', [column]);
  175. // add in any range constraints if any
  176. if (min !== undefined || max !== undefined) {
  177. if (min !== undefined) {
  178. query.addFilterValues(column, [`>=${min}`]);
  179. }
  180. if (max !== undefined) {
  181. query.addFilterValues(column, [`<=${max}`]);
  182. }
  183. }
  184. newEventView.query = query.formatString();
  185. return (
  186. <CardSummary>
  187. <SummaryHeading>
  188. <CardSectionHeading>{`${name} (${slug.toUpperCase()})`}</CardSectionHeading>
  189. </SummaryHeading>
  190. <StatNumber>
  191. {getDynamicText({
  192. value: this.getFormattedStatNumber(),
  193. fixed: '\u2014',
  194. })}
  195. </StatNumber>
  196. <Description>{description}</Description>
  197. <div>
  198. <Button
  199. size="xs"
  200. to={newEventView
  201. .withColumns([{kind: 'field', field: column}])
  202. .withSorts([{kind: 'desc', field: column}])
  203. .getPerformanceTransactionEventsViewUrlTarget(organization.slug, {
  204. showTransactions:
  205. dataFilter === 'all'
  206. ? EventsDisplayFilterName.P100
  207. : EventsDisplayFilterName.P75,
  208. webVital: column as WebVital,
  209. })}
  210. onClick={this.trackOpenAllEventsClicked}
  211. >
  212. {t('View Sampled Events')}
  213. </Button>
  214. </div>
  215. </CardSummary>
  216. );
  217. }
  218. /**
  219. * This callback happens everytime ECharts renders. This is NOT when ECharts
  220. * finishes rendering, so it can be called quite frequently. The calculations
  221. * here can get expensive if done frequently, furthermore, this can trigger a
  222. * state change leading to a re-render. So slow down the updates here as they
  223. * do not need to be updated every single time.
  224. */
  225. handleRendered = throttle(
  226. (_, chartRef) => {
  227. const {chartData} = this.props;
  228. const {refDataRect} = this.state;
  229. if (refDataRect === null || chartData.length < 1) {
  230. return;
  231. }
  232. const refPixelRect =
  233. refDataRect === null ? null : asPixelRect(chartRef, refDataRect!);
  234. if (refPixelRect !== null && !isEqual(refPixelRect, this.state.refPixelRect)) {
  235. this.setState({refPixelRect});
  236. }
  237. },
  238. 200,
  239. {leading: true}
  240. );
  241. handleDataZoomCancelled = () => {};
  242. renderHistogram() {
  243. const {
  244. theme,
  245. location,
  246. isLoading,
  247. chartData,
  248. summaryData,
  249. error,
  250. colors,
  251. vital,
  252. vitalDetails,
  253. precision = 0,
  254. } = this.props;
  255. const {slug} = vitalDetails;
  256. const series = this.getSeries();
  257. const xAxis = {
  258. type: 'category' as const,
  259. truncate: true,
  260. axisTick: {
  261. alignWithLabel: true,
  262. },
  263. };
  264. const values = series.data.map(point => point.value);
  265. const max = values.length ? Math.max(...values) : undefined;
  266. const yAxis = {
  267. type: 'value' as const,
  268. max,
  269. axisLabel: {
  270. color: theme.chartLabel,
  271. formatter: (value: string | number) => formatAbbreviatedNumber(value),
  272. },
  273. };
  274. const allSeries = [series];
  275. if (!isLoading && !error) {
  276. const baselineSeries = this.getBaselineSeries();
  277. if (baselineSeries !== null) {
  278. allSeries.push(baselineSeries);
  279. }
  280. }
  281. const vitalData =
  282. !isLoading && !error && summaryData !== null ? {[vital]: summaryData} : {};
  283. return (
  284. <BarChartZoom
  285. minZoomWidth={10 ** -precision * NUM_BUCKETS}
  286. location={location}
  287. paramStart={`${slug}Start`}
  288. paramEnd={`${slug}End`}
  289. xAxisIndex={[0]}
  290. buckets={computeBuckets(chartData)}
  291. onDataZoomCancelled={this.handleDataZoomCancelled}
  292. >
  293. {zoomRenderProps => (
  294. <Container>
  295. <TransparentLoadingMask visible={isLoading} />
  296. <PercentContainer>
  297. <VitalBar
  298. isLoading={isLoading}
  299. data={vitalData}
  300. vital={vital}
  301. showBar={false}
  302. showStates={false}
  303. showVitalPercentNames={false}
  304. showVitalThresholds={false}
  305. showDurationDetail={false}
  306. />
  307. </PercentContainer>
  308. {getDynamicText({
  309. value: (
  310. <BarChart
  311. series={allSeries}
  312. xAxis={xAxis}
  313. yAxis={yAxis}
  314. colors={colors}
  315. onRendered={this.handleRendered}
  316. grid={{
  317. left: space(3),
  318. right: space(3),
  319. top: space(3),
  320. bottom: space(1.5),
  321. }}
  322. stacked
  323. {...zoomRenderProps}
  324. />
  325. ),
  326. fixed: <Placeholder testId="skeleton-ui" height="200px" />,
  327. })}
  328. </Container>
  329. )}
  330. </BarChartZoom>
  331. );
  332. }
  333. bucketWidth() {
  334. const {chartData} = this.props;
  335. // We can assume that all buckets are of equal width, use the first two
  336. // buckets to get the width. The value of each histogram function indicates
  337. // the beginning of the bucket.
  338. return chartData.length >= 2 ? chartData[1].bin - chartData[0].bin : 0;
  339. }
  340. getSeries() {
  341. const {theme, chartData, precision, vitalDetails, vital} = this.props;
  342. const additionalFieldsFn = bucket => {
  343. return {
  344. itemStyle: {color: theme[this.getVitalsColor(vital, bucket)]},
  345. };
  346. };
  347. const data = formatHistogramData(chartData, {
  348. precision: precision === 0 ? undefined : precision,
  349. type: vitalDetails.type,
  350. additionalFieldsFn,
  351. });
  352. return {
  353. seriesName: t('Count'),
  354. data,
  355. };
  356. }
  357. getVitalsColor(vital: WebVital, value: number) {
  358. const poorThreshold = webVitalPoor[vital];
  359. const mehThreshold = webVitalMeh[vital];
  360. if (value >= poorThreshold) {
  361. return vitalStateColors[VitalState.POOR];
  362. }
  363. if (value >= mehThreshold) {
  364. return vitalStateColors[VitalState.MEH];
  365. }
  366. return vitalStateColors[VitalState.GOOD];
  367. }
  368. getBaselineSeries(): BarChartSeries | null {
  369. const {theme, chartData} = this.props;
  370. const summary = this.summary;
  371. if (summary === null || this.state.refPixelRect === null) {
  372. return null;
  373. }
  374. const summaryBucket = findNearestBucketIndex(chartData, summary);
  375. if (summaryBucket === null || summaryBucket === -1) {
  376. return null;
  377. }
  378. const thresholdPixelBottom = mapPoint(
  379. {
  380. // subtract 0.5 from the x here to ensure that the threshold lies between buckets
  381. x: summaryBucket - 0.5,
  382. y: 0,
  383. },
  384. this.state.refDataRect!,
  385. this.state.refPixelRect!
  386. );
  387. if (thresholdPixelBottom === null) {
  388. return null;
  389. }
  390. const thresholdPixelTop = mapPoint(
  391. {
  392. // subtract 0.5 from the x here to ensure that the threshold lies between buckets
  393. x: summaryBucket - 0.5,
  394. y: Math.max(...chartData.map(data => data.count)) || 1,
  395. },
  396. this.state.refDataRect!,
  397. this.state.refPixelRect!
  398. );
  399. if (thresholdPixelTop === null) {
  400. return null;
  401. }
  402. const markLine = MarkLine({
  403. animationDuration: 200,
  404. data: [[thresholdPixelBottom, thresholdPixelTop] as any],
  405. label: {
  406. show: false,
  407. },
  408. lineStyle: {
  409. color: theme.textColor,
  410. type: 'solid',
  411. },
  412. tooltip: {
  413. formatter: () => {
  414. return [
  415. '<div class="tooltip-series tooltip-series-solo">',
  416. '<span class="tooltip-label">',
  417. `<strong>${t('p75')}</strong>`,
  418. '</span>',
  419. '</div>',
  420. '<div class="tooltip-arrow"></div>',
  421. ].join('');
  422. },
  423. },
  424. });
  425. return {
  426. seriesName: t('p75'),
  427. data: [],
  428. markLine,
  429. };
  430. }
  431. render() {
  432. return (
  433. <Card>
  434. {this.renderSummary()}
  435. {this.renderHistogram()}
  436. </Card>
  437. );
  438. }
  439. }
  440. const SummaryHeading = styled('div')`
  441. display: flex;
  442. justify-content: space-between;
  443. `;
  444. const Container = styled('div')`
  445. position: relative;
  446. `;
  447. const PercentContainer = styled('div')`
  448. position: absolute;
  449. top: ${space(2)};
  450. right: ${space(3)};
  451. z-index: 2;
  452. `;
  453. export default withTheme(VitalCard);