breakdownBar.tsx 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  1. import {Fragment, useState} from 'react';
  2. import {Link} from 'react-router';
  3. import isPropValid from '@emotion/is-prop-valid';
  4. import {useTheme} from '@emotion/react';
  5. import styled from '@emotion/styled';
  6. import {motion} from 'framer-motion';
  7. import * as qs from 'query-string';
  8. import Truncate from 'sentry/components/truncate';
  9. import {t} from 'sentry/locale';
  10. import {space} from 'sentry/styles/space';
  11. import {percent} from 'sentry/utils';
  12. import {getUtcDateString} from 'sentry/utils/dates';
  13. import {useQuery} from 'sentry/utils/queryClient';
  14. import usePageFilters from 'sentry/utils/usePageFilters';
  15. import {
  16. getOtherDomainsActionsAndOpTimeseries,
  17. getTopDomainsActionsAndOp,
  18. getTopDomainsActionsAndOpTimeseries,
  19. totalCumulativeTime,
  20. } from 'sentry/views/starfish/views/webServiceView/queries';
  21. import {WebServiceBreakdownChart} from 'sentry/views/starfish/views/webServiceView/webServiceBreakdownChart';
  22. const HOST = 'http://localhost:8080';
  23. type ModuleSegment = {
  24. action: string;
  25. domain: string;
  26. module: string;
  27. num_spans: number;
  28. span_operation: string;
  29. sum: number;
  30. };
  31. type Props = {
  32. title: string;
  33. transaction?: string;
  34. };
  35. export function getSegmentLabel(span_operation, action, domain) {
  36. if (span_operation === 'http.client') {
  37. return t('%s requests to %s', action, domain);
  38. }
  39. if (span_operation === 'db') {
  40. return t('%s queries on %s', action, domain);
  41. }
  42. return span_operation || domain || undefined;
  43. }
  44. function getNumSpansLabel(segment) {
  45. if (segment.span_operation === 'other' && segment.num_spans === 0) {
  46. return t('Other');
  47. }
  48. if (segment.num_spans && segment.module && segment.module !== 'none') {
  49. return t('%s %s spans', segment.num_spans, segment.module);
  50. }
  51. return t('%s spans', segment.num_spans);
  52. }
  53. function getGroupingLabel(segment) {
  54. if (segment.module === 'http') {
  55. return t('Action: %s, Host: %s', segment.action, segment.domain);
  56. }
  57. if (segment.module === 'db') {
  58. return t('Action: %s, Table: %s', segment.action, segment.domain);
  59. }
  60. if (segment.module !== 'other') {
  61. return t('Operation: %s', segment.span_operation);
  62. }
  63. return '';
  64. }
  65. function FacetBreakdownBar({transaction: maybeTransaction}: Props) {
  66. const theme = useTheme();
  67. const {selection} = usePageFilters();
  68. const [hoveredValue, setHoveredValue] = useState<ModuleSegment | null>(null);
  69. const transaction = maybeTransaction ?? '';
  70. const {data: segments} = useQuery({
  71. queryKey: ['webServiceSpanGrouping', transaction],
  72. queryFn: () =>
  73. fetch(`${HOST}/?query=${getTopDomainsActionsAndOp({transaction})}`).then(res =>
  74. res.json()
  75. ),
  76. retry: false,
  77. initialData: [],
  78. });
  79. const {data: cumulativeTime} = useQuery({
  80. queryKey: ['totalCumulativeTime', transaction],
  81. queryFn: () =>
  82. fetch(`${HOST}/?query=${totalCumulativeTime({transaction})}`).then(res =>
  83. res.json()
  84. ),
  85. retry: false,
  86. initialData: [],
  87. });
  88. const totalValues = cumulativeTime.reduce((acc, segment) => acc + segment.sum, 0);
  89. const totalSegments = segments.reduce((acc, segment) => acc + segment.sum, 0);
  90. const otherValue = totalValues - totalSegments;
  91. const otherSegment = {
  92. span_operation: 'other',
  93. sum: otherValue,
  94. action: '',
  95. domain: '',
  96. num_spans: 0,
  97. module: 'other',
  98. } as ModuleSegment;
  99. let topConditions =
  100. segments.length > 0
  101. ? ` (span_operation = '${segments[0].span_operation}' ${
  102. segments[0].action ? `AND action = '${segments[0].action}'` : ''
  103. } ${segments[0].domain ? `AND domain = '${segments[0].domain}'` : ''})`
  104. : '';
  105. for (let index = 1; index < segments.length; index++) {
  106. const element = segments[index];
  107. topConditions = topConditions.concat(
  108. ' OR ',
  109. `(span_operation = '${element.span_operation}' ${
  110. element.action ? `AND action = '${element.action}'` : ''
  111. } ${element.domain ? `AND domain = '${element.domain}'` : ''})`
  112. );
  113. }
  114. const {isLoading: isTopDataLoading, data: topData} = useQuery({
  115. queryKey: ['topSpanGroupTimeseries', transaction, topConditions],
  116. queryFn: () =>
  117. fetch(
  118. `${HOST}/?query=${getTopDomainsActionsAndOpTimeseries({
  119. transaction,
  120. topConditions,
  121. })}`
  122. ).then(res => res.json()),
  123. retry: false,
  124. initialData: [],
  125. });
  126. const {isLoading: isOtherDataLoading, data: otherData} = useQuery({
  127. queryKey: ['otherSpanGroupTimeseries', transaction, topConditions],
  128. queryFn: () =>
  129. fetch(
  130. `${HOST}/?query=${getOtherDomainsActionsAndOpTimeseries({
  131. transaction,
  132. topConditions,
  133. })}`
  134. ).then(res => res.json()),
  135. retry: false,
  136. initialData: [],
  137. });
  138. const legendColors = theme.charts.getColorPalette(5);
  139. function renderLegend() {
  140. return (
  141. <LegendAnimateContainer expanded animate={{height: '100%', opacity: 1}}>
  142. <LegendContainer>
  143. {[...segments, otherSegment].map((segment, index) => {
  144. const pctLabel = Math.floor(percent(segment.sum, totalValues));
  145. const unfocus = !!hoveredValue && hoveredValue !== segment;
  146. const focus = hoveredValue === segment;
  147. const label = getSegmentLabel(
  148. segment.span_operation,
  149. segment.action,
  150. segment.domain
  151. );
  152. const numSpansLabel = getNumSpansLabel(segment);
  153. const groupingLabel = getGroupingLabel(segment);
  154. const {start, end, utc, period} = selection.datetime;
  155. const spansLinkQueryParams =
  156. start && end
  157. ? {start: getUtcDateString(start), end: getUtcDateString(end), utc}
  158. : {statsPeriod: period};
  159. ['span_operation', 'action', 'domain'].forEach(key => {
  160. if (segment[key] !== undefined && segment[key] !== null) {
  161. spansLinkQueryParams[key] = segment[key];
  162. }
  163. });
  164. const spansLink =
  165. segment.module === 'other'
  166. ? `/starfish/spans/`
  167. : `/starfish/spans/?${qs.stringify(spansLinkQueryParams)}`;
  168. return (
  169. <li key={`segment-${label}-${index}`}>
  170. <Link to={spansLink}>
  171. <div
  172. onMouseOver={() => setHoveredValue(segment)}
  173. onMouseLeave={() => setHoveredValue(null)}
  174. onClick={() => {}}
  175. >
  176. <LegendRow>
  177. <LegendDot color={legendColors[index]} focus={focus} />
  178. <LegendText unfocus={unfocus}>
  179. {numSpansLabel ?? (
  180. <NotApplicableLabel>{t('n/a')}</NotApplicableLabel>
  181. )}
  182. </LegendText>
  183. <LegendPercent unfocus={unfocus}>{`${pctLabel}%`}</LegendPercent>
  184. </LegendRow>
  185. <SpanGroupingText color={legendColors[index]} unfocus={unfocus}>
  186. <SpanGroupLabelTruncate value={groupingLabel} maxLength={40} />
  187. </SpanGroupingText>
  188. </div>
  189. </Link>
  190. </li>
  191. );
  192. })}
  193. </LegendContainer>
  194. </LegendAnimateContainer>
  195. );
  196. }
  197. const cumulativeSummary = <TagSummary>{renderLegend()}</TagSummary>;
  198. return (
  199. <Fragment>
  200. <WebServiceBreakdownChart
  201. segments={segments}
  202. isTopDataLoading={isTopDataLoading}
  203. topData={topData}
  204. isOtherDataLoading={isOtherDataLoading}
  205. otherData={otherData}
  206. cumulativeSummary={cumulativeSummary}
  207. />
  208. </Fragment>
  209. );
  210. }
  211. export default FacetBreakdownBar;
  212. const TagSummary = styled('div')`
  213. margin-bottom: ${space(2)};
  214. `;
  215. const LegendAnimateContainer = styled(motion.div, {
  216. shouldForwardProp: prop =>
  217. prop === 'animate' || (prop !== 'expanded' && isPropValid(prop)),
  218. })<{expanded: boolean}>`
  219. height: 0;
  220. opacity: 0;
  221. ${p => (!p.expanded ? 'overflow: hidden;' : '')}
  222. `;
  223. const LegendContainer = styled('ol')`
  224. list-style: none;
  225. padding: 0;
  226. margin: ${space(1)} 0;
  227. `;
  228. const LegendRow = styled('div')`
  229. display: flex;
  230. align-items: center;
  231. cursor: pointer;
  232. `;
  233. const SpanGroupingText = styled('div')<{
  234. color: string;
  235. unfocus: boolean;
  236. }>`
  237. display: flex;
  238. align-items: center;
  239. cursor: pointer;
  240. padding: 0 0 ${space(1)} 0;
  241. color: ${p => p.color};
  242. opacity: ${p => (p.unfocus ? '0.6' : '1')};
  243. `;
  244. const LegendDot = styled('span')<{color: string; focus: boolean}>`
  245. padding: 0;
  246. position: relative;
  247. width: 11px;
  248. height: 11px;
  249. text-indent: -9999em;
  250. display: inline-block;
  251. border-radius: 50%;
  252. flex-shrink: 0;
  253. background-color: ${p => p.color};
  254. &:after {
  255. content: '';
  256. border-radius: 50%;
  257. position: absolute;
  258. top: 0;
  259. left: 0;
  260. width: 100%;
  261. height: 100%;
  262. outline: ${p => p.theme.gray100} ${space(0.5)} solid;
  263. opacity: ${p => (p.focus ? '1' : '0')};
  264. transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  265. }
  266. `;
  267. const LegendText = styled('span')<{unfocus: boolean}>`
  268. margin-left: ${space(1)};
  269. overflow: hidden;
  270. white-space: nowrap;
  271. text-overflow: ellipsis;
  272. transition: color 0.3s;
  273. color: ${p => (p.unfocus ? p.theme.gray300 : p.theme.gray400)};
  274. `;
  275. const LegendPercent = styled('span')<{unfocus: boolean}>`
  276. margin-left: ${space(1)};
  277. color: ${p => (p.unfocus ? p.theme.gray300 : p.theme.gray400)};
  278. text-align: right;
  279. flex-grow: 1;
  280. `;
  281. const NotApplicableLabel = styled('span')`
  282. color: ${p => p.theme.gray300};
  283. `;
  284. export const SpanGroupLabelTruncate = styled(Truncate)`
  285. white-space: nowrap;
  286. `;