memoryChart.tsx 8.5 KB

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