eventedProfile.tsx 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. import {lastOfArray} from 'sentry/utils/array/lastOfArray';
  2. import {CallTreeNode} from 'sentry/utils/profiling/callTreeNode';
  3. import type {Frame} from 'sentry/utils/profiling/frame';
  4. import {formatTo} from 'sentry/utils/profiling/units/units';
  5. import {Profile} from './profile';
  6. import type {createFrameIndex} from './utils';
  7. export class EventedProfile extends Profile {
  8. calltree: CallTreeNode[] = [this.callTree];
  9. stack: Frame[] = [];
  10. lastValue = 0;
  11. samplingIntervalApproximation = 0;
  12. static FromProfile(
  13. eventedProfile: Profiling.EventedProfile,
  14. frameIndex: ReturnType<typeof createFrameIndex>,
  15. options: {
  16. type: 'flamechart' | 'flamegraph';
  17. frameFilter?: (frame: Frame) => boolean;
  18. }
  19. ): EventedProfile {
  20. const profile = new EventedProfile({
  21. duration: eventedProfile.endValue - eventedProfile.startValue,
  22. startedAt: eventedProfile.startValue,
  23. endedAt: eventedProfile.endValue,
  24. name: eventedProfile.name,
  25. unit: eventedProfile.unit,
  26. threadId: eventedProfile.threadID,
  27. type: options.type,
  28. });
  29. // If frames are offset, we need to set lastValue to profile start, so that delta between
  30. // samples is correctly offset by the start value.
  31. profile.lastValue = Math.max(0, eventedProfile.startValue);
  32. profile.samplingIntervalApproximation = formatTo(
  33. 10,
  34. 'milliseconds',
  35. eventedProfile.unit
  36. );
  37. for (const event of eventedProfile.events) {
  38. const frame = frameIndex[event.frame];
  39. if (!frame) {
  40. throw new Error(`Cannot retrieve event: ${event.frame} from frame index`);
  41. }
  42. if (options.frameFilter && !options.frameFilter(frame)) {
  43. continue;
  44. }
  45. switch (event.type) {
  46. // Open a new frame
  47. case 'O': {
  48. profile.enterFrame(frame, event.at);
  49. break;
  50. }
  51. // Close a frame
  52. case 'C': {
  53. profile.leaveFrame(frame, event.at);
  54. break;
  55. }
  56. default: {
  57. throw new TypeError(`Unknown event type ${event.type}`);
  58. }
  59. }
  60. }
  61. const built = profile.build();
  62. // The way the samples are constructed assumes that the trees are always appended to the
  63. // calltree. This is not the case for flamegraphs where nodes are mutated in place.
  64. // Because that assumption is invalidated with flamegraphs, we need to filter
  65. // out duplicate samples and their weights.
  66. if (options.type === 'flamegraph') {
  67. const visited = new Set();
  68. const samples: CallTreeNode[] = [];
  69. const weights: number[] = [];
  70. for (let i = 0; i < built.samples.length; i++) {
  71. const sample = built.samples[i];
  72. if (visited.has(sample)) {
  73. continue;
  74. }
  75. visited.add(sample);
  76. samples.push(sample);
  77. weights.push(sample.totalWeight);
  78. }
  79. built.samples = samples;
  80. built.weights = weights;
  81. }
  82. return built;
  83. }
  84. addWeightToFrames(weight: number): void {
  85. const weightDelta = weight - this.lastValue;
  86. for (const frame of this.stack) {
  87. frame.totalWeight += weightDelta;
  88. }
  89. const top = lastOfArray(this.stack);
  90. if (top) {
  91. top.selfWeight += weight;
  92. }
  93. }
  94. addWeightsToNodes(value: number) {
  95. const delta = value - this.lastValue;
  96. for (const node of this.calltree) {
  97. node.totalWeight += delta;
  98. }
  99. const stackTop = lastOfArray(this.calltree);
  100. if (stackTop) {
  101. stackTop.selfWeight += delta;
  102. }
  103. }
  104. enterFrame(frame: Frame, at: number): void {
  105. this.addWeightToFrames(at);
  106. this.addWeightsToNodes(at);
  107. const lastTop = lastOfArray(this.calltree);
  108. if (lastTop) {
  109. const sampleDelta = at - this.lastValue;
  110. if (sampleDelta < 0) {
  111. throw new Error(
  112. 'Sample delta cannot be negative, samples may be corrupt or out of order'
  113. );
  114. }
  115. // If the sample timestamp is not the same as the same as of previous frame,
  116. // we can deduce that this is a new sample and need to push it on the stack
  117. if (sampleDelta > 0) {
  118. this.samples.push(lastTop);
  119. this.weights.push(sampleDelta);
  120. }
  121. // If we are in flamegraph mode, we will look for any children of the current stack top
  122. // that may contain the frame we are entering. If we find one, we will use that as the
  123. // new stack top (this essentially makes it a graph). This does not apply flamecharts,
  124. // where chronological order matters, in that case we can only look at the last child of the
  125. // current stack top and use that as the new stack top if the frames match, else we create a new child
  126. let node: CallTreeNode;
  127. if (this.type === 'flamegraph') {
  128. const last = lastTop.children.find(c => c.frame === frame);
  129. if (last) {
  130. node = last;
  131. } else {
  132. node = new CallTreeNode(frame, lastTop);
  133. lastTop.children.push(node);
  134. }
  135. } else {
  136. const last = lastOfArray(lastTop.children);
  137. if (last && !last.isLocked() && last.frame === frame) {
  138. node = last;
  139. } else {
  140. node = new CallTreeNode(frame, lastTop);
  141. lastTop.children.push(node);
  142. }
  143. }
  144. // TODO: This is On^2, because we iterate over all frames in the stack to check if our
  145. // frame is a recursive frame. We could do this in O(1) by keeping a map of frames in the stack with their respective indexes
  146. // We check the stack in a top-down order to find the first recursive frame.
  147. let start = this.calltree.length - 1;
  148. while (start >= 0) {
  149. if (this.calltree[start].frame === node.frame) {
  150. // The recursion edge is bidirectional
  151. this.calltree[start].recursive = node;
  152. node.recursive = this.calltree[start];
  153. break;
  154. }
  155. start--;
  156. }
  157. this.calltree.push(node);
  158. }
  159. this.stack.push(frame);
  160. this.lastValue = at;
  161. }
  162. leaveFrame(_event: Frame, at: number): void {
  163. this.addWeightToFrames(at);
  164. this.addWeightsToNodes(at);
  165. this.trackSampleStats(at);
  166. const leavingStackTop = this.calltree.pop();
  167. if (leavingStackTop === undefined) {
  168. throw new Error('Unbalanced stack');
  169. }
  170. // Lock the stack node, so we make sure we dont mutate it in the future.
  171. // The samples should be ordered by timestamp when processed so we should never
  172. // iterate over them again in the future.
  173. leavingStackTop.lock();
  174. const sampleDelta = at - this.lastValue;
  175. leavingStackTop.count += Math.ceil(
  176. leavingStackTop.totalWeight / this.samplingIntervalApproximation
  177. );
  178. if (sampleDelta > 0) {
  179. this.samples.push(leavingStackTop);
  180. this.weights.push(sampleDelta);
  181. // Keep track of the minFrameDuration
  182. this.minFrameDuration = Math.min(sampleDelta, this.minFrameDuration);
  183. }
  184. this.stack.pop();
  185. this.lastValue = at;
  186. }
  187. build(): EventedProfile {
  188. if (this.calltree.length > 1) {
  189. throw new Error('Unbalanced append order stack');
  190. }
  191. this.duration = Math.max(
  192. this.duration,
  193. this.weights.reduce((a, b) => a + b, 0)
  194. );
  195. // We had no frames with duration > 0, so set min duration to timeline duration
  196. // which effectively disables any zooming on the flamegraphs
  197. if (
  198. this.minFrameDuration === Number.POSITIVE_INFINITY ||
  199. this.minFrameDuration === 0
  200. ) {
  201. this.minFrameDuration = this.duration;
  202. }
  203. return this;
  204. }
  205. }