opsBreakdown.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399
  1. import {Component} from 'react';
  2. import styled from '@emotion/styled';
  3. import isFinite from 'lodash/isFinite';
  4. import {SectionHeading} from 'sentry/components/charts/styles';
  5. import {ActiveOperationFilter} from 'sentry/components/events/interfaces/spans/filter';
  6. import {
  7. RawSpanType,
  8. SpanEntry,
  9. TraceContextType,
  10. } from 'sentry/components/events/interfaces/spans/types';
  11. import {getSpanOperation} from 'sentry/components/events/interfaces/spans/utils';
  12. import {pickBarColor} from 'sentry/components/performance/waterfall/utils';
  13. import QuestionTooltip from 'sentry/components/questionTooltip';
  14. import {t} from 'sentry/locale';
  15. import space from 'sentry/styles/space';
  16. import {EntryType, Event, EventTransaction} from 'sentry/types/event';
  17. type StartTimestamp = number;
  18. type EndTimestamp = number;
  19. type Duration = number;
  20. type TimeWindowSpan = [StartTimestamp, EndTimestamp];
  21. const OtherOperation = Symbol('Other');
  22. type OperationName = string | typeof OtherOperation;
  23. // mapping an operation name to a disjoint set of time intervals (start/end timestamp).
  24. // this is an intermediary data structure to help calculate the coverage of an operation name
  25. // with respect to the root transaction span's operation lifetime
  26. type OperationNameIntervals = Record<OperationName, Array<TimeWindowSpan>>;
  27. type OperationNameCoverage = Record<OperationName, Duration>;
  28. type OpStats = {
  29. name: OperationName;
  30. percentage: number;
  31. totalInterval: number;
  32. };
  33. const TOP_N_SPANS = 4;
  34. type OpBreakdownType = OpStats[];
  35. type DefaultProps = {
  36. hideHeader: boolean;
  37. topN: number;
  38. };
  39. type Props = DefaultProps & {
  40. event: Event;
  41. operationNameFilters: ActiveOperationFilter;
  42. };
  43. class OpsBreakdown extends Component<Props> {
  44. static defaultProps: DefaultProps = {
  45. topN: TOP_N_SPANS,
  46. hideHeader: false,
  47. };
  48. getTransactionEvent(): EventTransaction | undefined {
  49. const {event} = this.props;
  50. if (event.type === 'transaction') {
  51. return event as EventTransaction;
  52. }
  53. return undefined;
  54. }
  55. generateStats(): OpBreakdownType {
  56. const {topN, operationNameFilters} = this.props;
  57. const event = this.getTransactionEvent();
  58. if (!event) {
  59. return [];
  60. }
  61. const traceContext: TraceContextType | undefined = event?.contexts?.trace;
  62. if (!traceContext) {
  63. return [];
  64. }
  65. const spanEntry = event.entries.find((entry: SpanEntry | any): entry is SpanEntry => {
  66. return entry.type === EntryType.SPANS;
  67. });
  68. let spans: RawSpanType[] = spanEntry?.data ?? [];
  69. const rootSpan = {
  70. op: traceContext.op,
  71. timestamp: event.endTimestamp,
  72. start_timestamp: event.startTimestamp,
  73. trace_id: traceContext.trace_id || '',
  74. span_id: traceContext.span_id || '',
  75. data: {},
  76. };
  77. spans =
  78. spans.length > 0
  79. ? spans
  80. : // if there are no descendent spans, then use the transaction root span
  81. [rootSpan];
  82. // Filter spans by operation name
  83. if (operationNameFilters.type === 'active_filter') {
  84. spans = [...spans, rootSpan];
  85. spans = spans.filter(span => {
  86. const operationName = getSpanOperation(span);
  87. const shouldFilterOut =
  88. typeof operationName === 'string' &&
  89. !operationNameFilters.operationNames.has(operationName);
  90. return !shouldFilterOut;
  91. });
  92. }
  93. const operationNameIntervals = spans.reduce(
  94. (intervals: Partial<OperationNameIntervals>, span: RawSpanType) => {
  95. let startTimestamp = span.start_timestamp;
  96. let endTimestamp = span.timestamp;
  97. if (endTimestamp < startTimestamp) {
  98. // reverse timestamps
  99. startTimestamp = span.timestamp;
  100. endTimestamp = span.start_timestamp;
  101. }
  102. // invariant: startTimestamp <= endTimestamp
  103. let operationName = span.op;
  104. if (typeof operationName !== 'string') {
  105. // a span with no operation name is considered an 'unknown' op
  106. operationName = 'unknown';
  107. }
  108. const cover: TimeWindowSpan = [startTimestamp, endTimestamp];
  109. const operationNameInterval = intervals[operationName];
  110. if (!Array.isArray(operationNameInterval)) {
  111. intervals[operationName] = [cover];
  112. return intervals;
  113. }
  114. operationNameInterval.push(cover);
  115. intervals[operationName] = mergeInterval(operationNameInterval);
  116. return intervals;
  117. },
  118. {}
  119. ) as OperationNameIntervals;
  120. const operationNameCoverage = Object.entries(operationNameIntervals).reduce(
  121. (
  122. acc: Partial<OperationNameCoverage>,
  123. [operationName, intervals]: [OperationName, TimeWindowSpan[]]
  124. ) => {
  125. const duration = intervals.reduce((sum: number, [start, end]) => {
  126. return sum + Math.abs(end - start);
  127. }, 0);
  128. acc[operationName] = duration;
  129. return acc;
  130. },
  131. {}
  132. ) as OperationNameCoverage;
  133. const sortedOpsBreakdown = Object.entries(operationNameCoverage).sort(
  134. (first: [OperationName, Duration], second: [OperationName, Duration]) => {
  135. const firstDuration = first[1];
  136. const secondDuration = second[1];
  137. if (firstDuration === secondDuration) {
  138. return 0;
  139. }
  140. if (firstDuration < secondDuration) {
  141. // sort second before first
  142. return 1;
  143. }
  144. // otherwise, sort first before second
  145. return -1;
  146. }
  147. );
  148. const breakdown = sortedOpsBreakdown
  149. .slice(0, topN)
  150. .map(([operationName, duration]: [OperationName, Duration]): OpStats => {
  151. return {
  152. name: operationName,
  153. // percentage to be recalculated after the ops breakdown group is decided
  154. percentage: 0,
  155. totalInterval: duration,
  156. };
  157. });
  158. const other = sortedOpsBreakdown.slice(topN).reduce(
  159. (accOther: OpStats, [_operationName, duration]: [OperationName, Duration]) => {
  160. accOther.totalInterval += duration;
  161. return accOther;
  162. },
  163. {
  164. name: OtherOperation,
  165. // percentage to be recalculated after the ops breakdown group is decided
  166. percentage: 0,
  167. totalInterval: 0,
  168. }
  169. );
  170. if (other.totalInterval > 0) {
  171. breakdown.push(other);
  172. }
  173. // calculate breakdown total duration
  174. const total = breakdown.reduce((sum: number, operationNameGroup) => {
  175. return sum + operationNameGroup.totalInterval;
  176. }, 0);
  177. // recalculate percentage values
  178. breakdown.forEach(operationNameGroup => {
  179. operationNameGroup.percentage = operationNameGroup.totalInterval / total;
  180. });
  181. return breakdown;
  182. }
  183. render() {
  184. const {hideHeader} = this.props;
  185. const event = this.getTransactionEvent();
  186. if (!event) {
  187. return null;
  188. }
  189. const breakdown = this.generateStats();
  190. const contents = breakdown.map(currOp => {
  191. const {name, percentage, totalInterval} = currOp;
  192. const isOther = name === OtherOperation;
  193. const operationName = typeof name === 'string' ? name : t('Other');
  194. const durLabel = Math.round(totalInterval * 1000 * 100) / 100;
  195. const pctLabel = isFinite(percentage) ? Math.round(percentage * 100) : '∞';
  196. const opsColor: string = pickBarColor(operationName);
  197. return (
  198. <OpsLine key={operationName}>
  199. <OpsNameContainer>
  200. <OpsDot style={{backgroundColor: isOther ? 'transparent' : opsColor}} />
  201. <OpsName>{operationName}</OpsName>
  202. </OpsNameContainer>
  203. <OpsContent>
  204. <Dur>{durLabel}ms</Dur>
  205. <Pct>{pctLabel}%</Pct>
  206. </OpsContent>
  207. </OpsLine>
  208. );
  209. });
  210. if (!hideHeader) {
  211. return (
  212. <StyledBreakdown>
  213. <SectionHeading>
  214. {t('Operation Breakdown')}
  215. <QuestionTooltip
  216. position="top"
  217. size="sm"
  218. containerDisplayMode="block"
  219. title={t(
  220. 'Span durations are summed over the course of an entire transaction. Any overlapping spans are only counted once. Percentages are calculated by dividing the summed span durations by the total of all span durations.'
  221. )}
  222. />
  223. </SectionHeading>
  224. {contents}
  225. </StyledBreakdown>
  226. );
  227. }
  228. return <StyledBreakdownNoHeader>{contents}</StyledBreakdownNoHeader>;
  229. }
  230. }
  231. const StyledBreakdown = styled('div')`
  232. font-size: ${p => p.theme.fontSizeMedium};
  233. margin-bottom: ${space(4)};
  234. `;
  235. const StyledBreakdownNoHeader = styled('div')`
  236. font-size: ${p => p.theme.fontSizeMedium};
  237. margin: ${space(2)} ${space(3)};
  238. `;
  239. const OpsLine = styled('div')`
  240. display: flex;
  241. justify-content: space-between;
  242. margin-bottom: ${space(0.5)};
  243. * + * {
  244. margin-left: ${space(0.5)};
  245. }
  246. `;
  247. const OpsDot = styled('div')`
  248. content: '';
  249. display: block;
  250. width: 8px;
  251. min-width: 8px;
  252. height: 8px;
  253. margin-right: ${space(1)};
  254. border-radius: 100%;
  255. `;
  256. const OpsContent = styled('div')`
  257. display: flex;
  258. align-items: center;
  259. `;
  260. const OpsNameContainer = styled(OpsContent)`
  261. overflow: hidden;
  262. `;
  263. const OpsName = styled('div')`
  264. white-space: nowrap;
  265. overflow: hidden;
  266. text-overflow: ellipsis;
  267. `;
  268. const Dur = styled('div')`
  269. color: ${p => p.theme.gray300};
  270. font-variant-numeric: tabular-nums;
  271. `;
  272. const Pct = styled('div')`
  273. min-width: 40px;
  274. text-align: right;
  275. font-variant-numeric: tabular-nums;
  276. `;
  277. function mergeInterval(intervals: TimeWindowSpan[]): TimeWindowSpan[] {
  278. // sort intervals by start timestamps
  279. intervals.sort((first: TimeWindowSpan, second: TimeWindowSpan) => {
  280. if (first[0] < second[0]) {
  281. // sort first before second
  282. return -1;
  283. }
  284. if (second[0] < first[0]) {
  285. // sort second before first
  286. return 1;
  287. }
  288. return 0;
  289. });
  290. // array of disjoint intervals
  291. const merged: TimeWindowSpan[] = [];
  292. for (const currentInterval of intervals) {
  293. if (merged.length === 0) {
  294. merged.push(currentInterval);
  295. continue;
  296. }
  297. const lastInterval = merged[merged.length - 1];
  298. const lastIntervalEnd = lastInterval[1];
  299. const [currentIntervalStart, currentIntervalEnd] = currentInterval;
  300. if (lastIntervalEnd < currentIntervalStart) {
  301. // if currentInterval does not overlap with lastInterval,
  302. // then add currentInterval
  303. merged.push(currentInterval);
  304. continue;
  305. }
  306. // currentInterval and lastInterval overlaps; so we merge these intervals
  307. // invariant: lastIntervalStart <= currentIntervalStart
  308. lastInterval[1] = Math.max(lastIntervalEnd, currentIntervalEnd);
  309. }
  310. return merged;
  311. }
  312. export default OpsBreakdown;