opsBreakdown.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. const endTimestamp = span.timestamp;
  98. if (!span.exclusive_time) {
  99. return intervals;
  100. }
  101. if (endTimestamp < startTimestamp) {
  102. // reverse timestamps
  103. startTimestamp = span.timestamp;
  104. }
  105. // invariant: startTimestamp <= endTimestamp
  106. let operationName = span.op;
  107. if (typeof operationName !== 'string') {
  108. // a span with no operation name is considered an 'unknown' op
  109. operationName = 'unknown';
  110. }
  111. const cover: TimeWindowSpan = [
  112. startTimestamp,
  113. startTimestamp + span.exclusive_time / 1000,
  114. ];
  115. const operationNameInterval = intervals[operationName];
  116. if (!Array.isArray(operationNameInterval)) {
  117. intervals[operationName] = [cover];
  118. return intervals;
  119. }
  120. operationNameInterval.push(cover);
  121. intervals[operationName] = mergeInterval(operationNameInterval);
  122. return intervals;
  123. },
  124. {}
  125. ) as OperationNameIntervals;
  126. const operationNameCoverage = Object.entries(operationNameIntervals).reduce(
  127. (
  128. acc: Partial<OperationNameCoverage>,
  129. [operationName, intervals]: [OperationName, TimeWindowSpan[]]
  130. ) => {
  131. const duration = intervals.reduce((sum: number, [start, end]) => {
  132. return sum + Math.abs(end - start);
  133. }, 0);
  134. acc[operationName] = duration;
  135. return acc;
  136. },
  137. {}
  138. ) as OperationNameCoverage;
  139. const sortedOpsBreakdown = Object.entries(operationNameCoverage).sort(
  140. (first: [OperationName, Duration], second: [OperationName, Duration]) => {
  141. const firstDuration = first[1];
  142. const secondDuration = second[1];
  143. if (firstDuration === secondDuration) {
  144. return 0;
  145. }
  146. if (firstDuration < secondDuration) {
  147. // sort second before first
  148. return 1;
  149. }
  150. // otherwise, sort first before second
  151. return -1;
  152. }
  153. );
  154. const breakdown = sortedOpsBreakdown
  155. .slice(0, topN)
  156. .map(([operationName, duration]: [OperationName, Duration]): OpStats => {
  157. return {
  158. name: operationName,
  159. // percentage to be recalculated after the ops breakdown group is decided
  160. percentage: 0,
  161. totalInterval: duration,
  162. };
  163. });
  164. const other = sortedOpsBreakdown.slice(topN).reduce(
  165. (accOther: OpStats, [_operationName, duration]: [OperationName, Duration]) => {
  166. accOther.totalInterval += duration;
  167. return accOther;
  168. },
  169. {
  170. name: OtherOperation,
  171. // percentage to be recalculated after the ops breakdown group is decided
  172. percentage: 0,
  173. totalInterval: 0,
  174. }
  175. );
  176. if (other.totalInterval > 0) {
  177. breakdown.push(other);
  178. }
  179. // calculate breakdown total duration
  180. const total = breakdown.reduce((sum: number, operationNameGroup) => {
  181. return sum + operationNameGroup.totalInterval;
  182. }, 0);
  183. // recalculate percentage values
  184. breakdown.forEach(operationNameGroup => {
  185. operationNameGroup.percentage = operationNameGroup.totalInterval / total;
  186. });
  187. return breakdown;
  188. }
  189. render() {
  190. const {hideHeader} = this.props;
  191. const event = this.getTransactionEvent();
  192. if (!event) {
  193. return null;
  194. }
  195. const breakdown = this.generateStats();
  196. const contents = breakdown.map(currOp => {
  197. const {name, percentage, totalInterval} = currOp;
  198. const isOther = name === OtherOperation;
  199. const operationName = typeof name === 'string' ? name : t('Other');
  200. const durLabel = Math.round(totalInterval * 1000 * 100) / 100;
  201. const pctLabel = isFinite(percentage) ? Math.round(percentage * 100) : '∞';
  202. const opsColor: string = pickBarColor(operationName);
  203. return (
  204. <OpsLine key={operationName}>
  205. <OpsNameContainer>
  206. <OpsDot style={{backgroundColor: isOther ? 'transparent' : opsColor}} />
  207. <OpsName>{operationName}</OpsName>
  208. </OpsNameContainer>
  209. <OpsContent>
  210. <Dur>{durLabel}ms</Dur>
  211. <Pct>{pctLabel}%</Pct>
  212. </OpsContent>
  213. </OpsLine>
  214. );
  215. });
  216. if (!hideHeader) {
  217. return (
  218. <StyledBreakdown>
  219. <SectionHeading>
  220. {t('Operation Breakdown')}
  221. <QuestionTooltip
  222. position="top"
  223. size="sm"
  224. containerDisplayMode="block"
  225. title={t(
  226. '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.'
  227. )}
  228. />
  229. </SectionHeading>
  230. {contents}
  231. </StyledBreakdown>
  232. );
  233. }
  234. return <StyledBreakdownNoHeader>{contents}</StyledBreakdownNoHeader>;
  235. }
  236. }
  237. const StyledBreakdown = styled('div')`
  238. font-size: ${p => p.theme.fontSizeMedium};
  239. margin-bottom: ${space(4)};
  240. `;
  241. const StyledBreakdownNoHeader = styled('div')`
  242. font-size: ${p => p.theme.fontSizeMedium};
  243. margin: ${space(2)} ${space(3)};
  244. `;
  245. const OpsLine = styled('div')`
  246. display: flex;
  247. justify-content: space-between;
  248. margin-bottom: ${space(0.5)};
  249. * + * {
  250. margin-left: ${space(0.5)};
  251. }
  252. `;
  253. const OpsDot = styled('div')`
  254. content: '';
  255. display: block;
  256. width: 8px;
  257. min-width: 8px;
  258. height: 8px;
  259. margin-right: ${space(1)};
  260. border-radius: 100%;
  261. `;
  262. const OpsContent = styled('div')`
  263. display: flex;
  264. align-items: center;
  265. `;
  266. const OpsNameContainer = styled(OpsContent)`
  267. overflow: hidden;
  268. `;
  269. const OpsName = styled('div')`
  270. white-space: nowrap;
  271. overflow: hidden;
  272. text-overflow: ellipsis;
  273. `;
  274. const Dur = styled('div')`
  275. color: ${p => p.theme.gray300};
  276. font-variant-numeric: tabular-nums;
  277. `;
  278. const Pct = styled('div')`
  279. min-width: 40px;
  280. text-align: right;
  281. font-variant-numeric: tabular-nums;
  282. `;
  283. function mergeInterval(intervals: TimeWindowSpan[]): TimeWindowSpan[] {
  284. // sort intervals by start timestamps
  285. intervals.sort((first: TimeWindowSpan, second: TimeWindowSpan) => {
  286. if (first[0] < second[0]) {
  287. // sort first before second
  288. return -1;
  289. }
  290. if (second[0] < first[0]) {
  291. // sort second before first
  292. return 1;
  293. }
  294. return 0;
  295. });
  296. // array of disjoint intervals
  297. const merged: TimeWindowSpan[] = [];
  298. for (const currentInterval of intervals) {
  299. if (merged.length === 0) {
  300. merged.push(currentInterval);
  301. continue;
  302. }
  303. const lastInterval = merged[merged.length - 1];
  304. const lastIntervalEnd = lastInterval[1];
  305. const [currentIntervalStart, currentIntervalEnd] = currentInterval;
  306. if (lastIntervalEnd < currentIntervalStart) {
  307. // if currentInterval does not overlap with lastInterval,
  308. // then add currentInterval
  309. merged.push(currentInterval);
  310. continue;
  311. }
  312. // currentInterval and lastInterval overlaps; so we merge these intervals
  313. // invariant: lastIntervalStart <= currentIntervalStart
  314. lastInterval[1] = Math.max(lastIntervalEnd, currentIntervalEnd);
  315. }
  316. return merged;
  317. }
  318. export default OpsBreakdown;