memoryChart.tsx 8.8 KB

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