opsBreakdown.tsx 10 KB

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