memoryChart.tsx 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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 FluidHeight from 'sentry/views/replays/detail/layout/fluidHeight';
  19. import type {MemorySpan} from 'sentry/views/replays/types';
  20. interface Props {
  21. memorySpans: undefined | MemorySpan[];
  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 * 1000, 'MMM D, YYYY hh:mm:ss A z', {local: false});
  31. function MemoryChart({
  32. forwardedRef,
  33. memorySpans,
  34. startTimestampMs = 0,
  35. setCurrentTime,
  36. setCurrentHoverTime,
  37. }: MemoryChartProps) {
  38. const theme = useTheme();
  39. if (!memorySpans) {
  40. return (
  41. <MemoryChartWrapper>
  42. <Placeholder height="100%" />
  43. </MemoryChartWrapper>
  44. );
  45. }
  46. if (memorySpans.length <= 0) {
  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 * 1000)
  92. .toDate()
  93. .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] * 1000 - startTimestampMs);
  135. }
  136. },
  137. onMouseOut: () => {
  138. setCurrentHoverTime(undefined);
  139. },
  140. onClick: ({data}) => {
  141. if (data.value) {
  142. setCurrentTime(data.value * 1000 - startTimestampMs);
  143. }
  144. },
  145. };
  146. const series: Series[] = [
  147. {
  148. seriesName: t('Used Heap Memory'),
  149. data: memorySpans.map(span => ({
  150. value: span.data.memory.usedJSHeapSize,
  151. name: span.endTimestamp,
  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: memorySpans.map(span => ({
  162. value: span.data.memory.totalJSHeapSize - span.data.memory.usedJSHeapSize,
  163. name: span.endTimestamp,
  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. margin-bottom: ${space(3)};
  215. border-radius: ${space(0.5)};
  216. border: 1px solid ${p => p.theme.border};
  217. `;
  218. const MemoizedMemoryChart = memo(
  219. forwardRef<ReactEchartsRef, Props>((props, ref) => (
  220. <MemoryChart forwardedRef={ref} {...props} />
  221. ))
  222. );
  223. interface MemoryChartContainerProps extends Props {
  224. currentHoverTime: number | undefined;
  225. currentTime: number;
  226. }
  227. /**
  228. * This container is used to update echarts outside of React. `currentTime` is
  229. * the current time of the player -- if replay is currently playing, this will be
  230. * updated quite frequently causing the chart to constantly re-render. The
  231. * re-renders will conflict with mouse interactions (e.g. hovers and
  232. * 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. currentTime,
  240. currentHoverTime,
  241. startTimestampMs = 0,
  242. ...props
  243. }: MemoryChartContainerProps) {
  244. const chart = useRef<ReactEchartsRef>(null);
  245. const theme = useTheme();
  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 ref={chart} startTimestampMs={startTimestampMs} {...props} />
  292. );
  293. }
  294. export default MemoryChartContainer;