breakdownBar.tsx 10 KB

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