memoryChart.tsx 8.9 KB

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