opsBreakdown.tsx 10 KB

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