memoryChart.tsx 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. import {forwardRef, memo, useEffect, useRef} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import moment from 'moment';
  5. import {AreaChart, AreaChartProps} from 'sentry/components/charts/areaChart';
  6. import Grid from 'sentry/components/charts/components/grid';
  7. import {ChartTooltip} from 'sentry/components/charts/components/tooltip';
  8. import XAxis from 'sentry/components/charts/components/xAxis';
  9. import YAxis from 'sentry/components/charts/components/yAxis';
  10. import EmptyMessage from 'sentry/components/emptyMessage';
  11. import Placeholder from 'sentry/components/placeholder';
  12. import {showPlayerTime} from 'sentry/components/replays/utils';
  13. import {t} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import {ReactEchartsRef, Series} from 'sentry/types/echarts';
  16. import {formatBytesBase2} from 'sentry/utils';
  17. import {getFormattedDate} from 'sentry/utils/dates';
  18. import type {MemoryFrame} from 'sentry/utils/replays/types';
  19. import FluidHeight from 'sentry/views/replays/detail/layout/fluidHeight';
  20. interface Props {
  21. memoryFrames: undefined | MemoryFrame[];
  22. setCurrentHoverTime: (time: undefined | number) => void;
  23. setCurrentTime: (time: number) => void;
  24. startTimestampMs: undefined | number;
  25. }
  26. interface MemoryChartProps extends Props {
  27. forwardedRef: React.Ref<ReactEchartsRef>;
  28. }
  29. const formatTimestamp = timestamp =>
  30. getFormattedDate(timestamp, 'MMM D, YYYY hh:mm:ss A z', {local: false});
  31. function MemoryChart({
  32. forwardedRef,
  33. memoryFrames,
  34. startTimestampMs = 0,
  35. setCurrentTime,
  36. setCurrentHoverTime,
  37. }: MemoryChartProps) {
  38. const theme = useTheme();
  39. if (!memoryFrames) {
  40. return (
  41. <MemoryChartWrapper>
  42. <Placeholder height="100%" />
  43. </MemoryChartWrapper>
  44. );
  45. }
  46. if (!memoryFrames.length) {
  47. return (
  48. <EmptyMessage
  49. title={t('No memory metrics found')}
  50. description={t(
  51. 'Memory metrics are only captured within Chromium based browser sessions.'
  52. )}
  53. />
  54. );
  55. }
  56. const chartOptions: Omit<AreaChartProps, 'series'> = {
  57. grid: Grid({
  58. // makes space for the title
  59. top: '40px',
  60. left: space(1),
  61. right: space(1),
  62. }),
  63. tooltip: ChartTooltip({
  64. appendToBody: true,
  65. trigger: 'axis',
  66. renderMode: 'html',
  67. chartId: 'replay-memory-chart',
  68. formatter: values => {
  69. const seriesTooltips = values.map(
  70. value => `
  71. <div>
  72. <span className="tooltip-label">${value.marker}<strong>${
  73. value.seriesName
  74. }</strong></span>
  75. ${formatBytesBase2(value.data[1])}
  76. </div>
  77. `
  78. );
  79. // showPlayerTime expects a timestamp so we take the captured time in seconds and convert it to a UTC timestamp
  80. const template = [
  81. '<div class="tooltip-series">',
  82. ...seriesTooltips,
  83. '</div>',
  84. `<div class="tooltip-footer" style="display: inline-block; width: max-content;">${t(
  85. 'Span Time'
  86. )}:
  87. ${formatTimestamp(values[0].axisValue)}
  88. </div>`,
  89. `<div class="tooltip-footer" style="border: none;">${'Relative Time'}:
  90. ${showPlayerTime(
  91. moment(values[0].axisValue).toDate().toUTCString(),
  92. startTimestampMs
  93. )}
  94. </div>`,
  95. '<div class="tooltip-arrow"></div>',
  96. ].join('');
  97. return template;
  98. },
  99. }),
  100. xAxis: XAxis({
  101. type: 'time',
  102. axisLabel: {
  103. formatter: formatTimestamp,
  104. },
  105. theme,
  106. }),
  107. yAxis: YAxis({
  108. type: 'value',
  109. name: t('Heap Size'),
  110. theme,
  111. nameTextStyle: {
  112. padding: 8,
  113. fontSize: theme.fontSizeLarge,
  114. fontWeight: 600,
  115. lineHeight: 1.2,
  116. color: theme.gray300,
  117. },
  118. // input is in bytes, minInterval is a megabyte
  119. minInterval: 1024 * 1024,
  120. // maxInterval is a terabyte
  121. maxInterval: Math.pow(1024, 4),
  122. // format the axis labels to be whole number values
  123. axisLabel: {
  124. formatter: value => formatBytesBase2(value, 0),
  125. },
  126. }),
  127. // XXX: For area charts, mouse events *only* occurs when interacting with
  128. // the "line" of the area chart. Mouse events do not fire when interacting
  129. // with the "area" under the line.
  130. onMouseOver: ({data}) => {
  131. if (data[0]) {
  132. setCurrentHoverTime(data[0] - startTimestampMs);
  133. }
  134. },
  135. onMouseOut: () => {
  136. setCurrentHoverTime(undefined);
  137. },
  138. onClick: ({data}) => {
  139. if (data.value) {
  140. setCurrentTime(data.value - startTimestampMs);
  141. }
  142. },
  143. };
  144. const series: Series[] = [
  145. {
  146. seriesName: t('Used Heap Memory'),
  147. data: memoryFrames.map(frame => ({
  148. value: frame.data.memory.usedJSHeapSize,
  149. name: frame.endTimestampMs,
  150. })),
  151. stack: 'heap-memory',
  152. lineStyle: {
  153. opacity: 0.75,
  154. width: 1,
  155. },
  156. },
  157. {
  158. seriesName: t('Free Heap Memory'),
  159. data: memoryFrames.map(frame => ({
  160. value: frame.data.memory.totalJSHeapSize - frame.data.memory.usedJSHeapSize,
  161. name: frame.endTimestampMs,
  162. })),
  163. stack: 'heap-memory',
  164. lineStyle: {
  165. opacity: 0.75,
  166. width: 1,
  167. },
  168. },
  169. // Inserting this here so we can update in Container
  170. {
  171. id: 'currentTime',
  172. seriesName: t('Current player time'),
  173. data: [],
  174. markLine: {
  175. symbol: ['', ''],
  176. data: [],
  177. label: {
  178. show: false,
  179. },
  180. lineStyle: {
  181. type: 'solid' as const,
  182. color: theme.purple300,
  183. width: 2,
  184. },
  185. },
  186. },
  187. {
  188. id: 'hoverTime',
  189. seriesName: t('Hover player time'),
  190. data: [],
  191. markLine: {
  192. symbol: ['', ''],
  193. data: [],
  194. label: {
  195. show: false,
  196. },
  197. lineStyle: {
  198. type: 'solid' as const,
  199. color: theme.purple200,
  200. width: 2,
  201. },
  202. },
  203. },
  204. ];
  205. return (
  206. <MemoryChartWrapper id="replay-memory-chart">
  207. <AreaChart forwardedRef={forwardedRef} series={series} {...chartOptions} />
  208. </MemoryChartWrapper>
  209. );
  210. }
  211. const MemoryChartWrapper = styled(FluidHeight)`
  212. border-radius: ${space(0.5)};
  213. border: 1px solid ${p => p.theme.border};
  214. `;
  215. const MemoizedMemoryChart = memo(
  216. forwardRef<ReactEchartsRef, Props>((props, ref) => (
  217. <MemoryChart forwardedRef={ref} {...props} />
  218. ))
  219. );
  220. interface MemoryChartContainerProps extends Props {
  221. currentHoverTime: number | undefined;
  222. currentTime: number;
  223. }
  224. /**
  225. * This container is used to update echarts outside of React. `currentTime` is
  226. * the current time of the player -- if replay is currently playing, this will
  227. * be updated quite frequently causing the chart to constantly re-render. The
  228. * re-renders will conflict with mouse interactions (e.g. hovers and tooltips).
  229. *
  230. * We need `MemoryChart` (which wraps an `<AreaChart>`) to re-render as
  231. * infrequently as possible, so we use React.memo and only pass in props that
  232. * are not frequently updated.
  233. */
  234. function MemoryChartContainer({
  235. currentTime,
  236. currentHoverTime,
  237. startTimestampMs = 0,
  238. ...props
  239. }: MemoryChartContainerProps) {
  240. const chart = useRef<ReactEchartsRef>(null);
  241. const theme = useTheme();
  242. useEffect(() => {
  243. if (!chart.current) {
  244. return;
  245. }
  246. const echarts = chart.current.getEchartsInstance();
  247. echarts.setOption({
  248. series: [
  249. {
  250. id: 'currentTime',
  251. markLine: {
  252. data: [
  253. {
  254. xAxis: currentTime + startTimestampMs,
  255. },
  256. ],
  257. },
  258. },
  259. ],
  260. });
  261. }, [currentTime, startTimestampMs, theme]);
  262. useEffect(() => {
  263. if (!chart.current) {
  264. return;
  265. }
  266. const echarts = chart.current.getEchartsInstance();
  267. echarts.setOption({
  268. series: [
  269. {
  270. id: 'hoverTime',
  271. markLine: {
  272. data: [
  273. ...(currentHoverTime
  274. ? [
  275. {
  276. xAxis: currentHoverTime + startTimestampMs,
  277. },
  278. ]
  279. : []),
  280. ],
  281. },
  282. },
  283. ],
  284. });
  285. }, [currentHoverTime, startTimestampMs, theme]);
  286. return (
  287. <MemoizedMemoryChart ref={chart} startTimestampMs={startTimestampMs} {...props} />
  288. );
  289. }
  290. export default MemoryChartContainer;