flamegraph.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import {trimPackage} from 'sentry/components/events/interfaces/frame/utils';
  2. import {FlamegraphFrame} from 'sentry/utils/profiling/flamegraphFrame';
  3. import {Profile} from './profile/profile';
  4. import {SampledProfile} from './profile/sampledProfile';
  5. import {makeFormatter, makeTimelineFormatter} from './units/units';
  6. import {CallTreeNode} from './callTreeNode';
  7. import {Frame} from './frame';
  8. import {Rect} from './speedscope';
  9. function sortByTotalWeight(a: CallTreeNode, b: CallTreeNode) {
  10. return b.totalWeight - a.totalWeight;
  11. }
  12. function sortAlphabetically(a: CallTreeNode, b: CallTreeNode) {
  13. return a.frame.name.localeCompare(b.frame.name);
  14. }
  15. function makeTreeSort(sortFn: (a: CallTreeNode, b: CallTreeNode) => number) {
  16. return (root: CallTreeNode) => {
  17. const queue: CallTreeNode[] = [root];
  18. while (queue.length > 0) {
  19. const next = queue.pop()!;
  20. next.children.sort(sortFn);
  21. for (let i = 0; i < next.children.length; i++) {
  22. queue.push(next.children[i]);
  23. }
  24. }
  25. };
  26. }
  27. const alphabeticTreeSort = makeTreeSort(sortAlphabetically);
  28. const leftHeavyTreeSort = makeTreeSort(sortByTotalWeight);
  29. export class Flamegraph {
  30. profile: Profile;
  31. frames: ReadonlyArray<FlamegraphFrame> = [];
  32. profileIndex: number;
  33. inverted: boolean = false;
  34. sort: 'left heavy' | 'alphabetical' | 'call order' = 'call order';
  35. depth = 0;
  36. configSpace: Rect = Rect.Empty();
  37. root: FlamegraphFrame = {
  38. key: -1,
  39. parent: null,
  40. frame: new Frame({...Frame.Root}),
  41. node: new CallTreeNode(new Frame({...Frame.Root}), null),
  42. depth: -1,
  43. start: 0,
  44. end: 0,
  45. children: [],
  46. };
  47. formatter: (value: number) => string;
  48. timelineFormatter: (value: number) => string;
  49. static Empty(): Flamegraph {
  50. return new Flamegraph(Profile.Empty, 0, {
  51. inverted: false,
  52. sort: 'call order',
  53. });
  54. }
  55. static Example(): Flamegraph {
  56. return new Flamegraph(SampledProfile.Example, 0, {
  57. inverted: false,
  58. sort: 'call order',
  59. });
  60. }
  61. static From(
  62. from: Flamegraph,
  63. {
  64. inverted = false,
  65. sort = 'call order',
  66. }: {
  67. inverted?: Flamegraph['inverted'];
  68. sort?: Flamegraph['sort'];
  69. }
  70. ): Flamegraph {
  71. return new Flamegraph(from.profile, from.profileIndex, {
  72. inverted,
  73. sort,
  74. });
  75. }
  76. constructor(
  77. profile: Profile,
  78. profileIndex: number,
  79. {
  80. inverted = false,
  81. sort = 'call order',
  82. configSpace,
  83. }: {
  84. configSpace?: Rect;
  85. inverted?: boolean;
  86. sort?: 'left heavy' | 'alphabetical' | 'call order';
  87. } = {}
  88. ) {
  89. this.inverted = inverted;
  90. this.sort = sort;
  91. // @TODO check if we can get rid of this profile reference
  92. this.profile = profile;
  93. this.profileIndex = profileIndex;
  94. // If a custom config space is provided, use it and draw the chart in it
  95. switch (this.sort) {
  96. case 'left heavy': {
  97. this.frames = this.buildSortedChart(profile, leftHeavyTreeSort);
  98. break;
  99. }
  100. case 'alphabetical':
  101. if (this.profile.type === 'flamechart') {
  102. throw new TypeError('Flamechart does not support alphabetical sorting');
  103. }
  104. this.frames = this.buildSortedChart(profile, alphabeticTreeSort);
  105. break;
  106. case 'call order':
  107. if (this.profile.type === 'flamegraph') {
  108. throw new TypeError('Flamegraph does not support call order sorting');
  109. }
  110. this.frames = this.buildCallOrderChart(profile);
  111. break;
  112. default:
  113. throw new TypeError(`Unknown flamechart sort type: ${this.sort}`);
  114. }
  115. this.formatter = makeFormatter(profile.unit);
  116. this.timelineFormatter = makeTimelineFormatter(profile.unit);
  117. const weight = this.root.children.reduce(
  118. (acc, frame) => acc + frame.node.totalWeight,
  119. 0
  120. );
  121. this.root.node.totalWeight += weight;
  122. this.root.end = this.root.start + weight;
  123. this.root.frame.totalWeight += weight;
  124. let width = 0;
  125. if (this.profile.type === 'flamegraph' && weight > 0) {
  126. width = weight;
  127. } else if (this.profile.duration > 0) {
  128. width = configSpace ? configSpace.width : this.profile.duration;
  129. } else {
  130. // If the profile duration is 0, set the flamegraph duration
  131. // to 1 second so we can render a placeholder grid
  132. width =
  133. this.profile.unit === 'nanoseconds'
  134. ? 1e9
  135. : this.profile.unit === 'microseconds'
  136. ? 1e6
  137. : this.profile.unit === 'milliseconds'
  138. ? 1e3
  139. : 1;
  140. }
  141. this.configSpace = new Rect(0, 0, width, this.depth);
  142. }
  143. buildCallOrderChart(profile: Profile): FlamegraphFrame[] {
  144. const frames: FlamegraphFrame[] = [];
  145. const stack: FlamegraphFrame[] = [];
  146. let idx = 0;
  147. const openFrame = (node: CallTreeNode, value: number) => {
  148. const parent = stack[stack.length - 1] ?? this.root;
  149. const frame: FlamegraphFrame = {
  150. key: idx,
  151. frame: node.frame,
  152. node,
  153. parent,
  154. children: [],
  155. depth: 0,
  156. start: value,
  157. end: value,
  158. };
  159. if (parent) {
  160. parent.children.push(frame);
  161. } else {
  162. this.root.children.push(frame);
  163. }
  164. stack.push(frame);
  165. idx++;
  166. };
  167. const closeFrame = (_: CallTreeNode, value: number) => {
  168. const stackTop = stack.pop();
  169. if (!stackTop) {
  170. // This is unreachable because the profile importing logic already checks this
  171. throw new Error('Unbalanced stack');
  172. }
  173. stackTop.end = value;
  174. stackTop.depth = stack.length;
  175. if (stackTop.end - stackTop.start === 0) {
  176. return;
  177. }
  178. frames.push(stackTop);
  179. this.depth = Math.max(stackTop.depth, this.depth);
  180. };
  181. profile.forEach(openFrame, closeFrame);
  182. return frames;
  183. }
  184. buildSortedChart(
  185. profile: Profile,
  186. sortFn: (tree: CallTreeNode) => void
  187. ): FlamegraphFrame[] {
  188. const frames: FlamegraphFrame[] = [];
  189. const stack: FlamegraphFrame[] = [];
  190. sortFn(profile.callTree);
  191. const virtualRoot: FlamegraphFrame = {
  192. key: -1,
  193. frame: CallTreeNode.Root.frame,
  194. node: CallTreeNode.Root,
  195. parent: null,
  196. children: [],
  197. depth: 0,
  198. start: 0,
  199. end: 0,
  200. };
  201. this.root = virtualRoot;
  202. let idx = 0;
  203. const openFrame = (node: CallTreeNode, value: number) => {
  204. const parent = stack[stack.length - 1] ?? this.root;
  205. const frame: FlamegraphFrame = {
  206. key: idx,
  207. frame: node.frame,
  208. node,
  209. parent,
  210. children: [],
  211. depth: 0,
  212. start: value,
  213. end: value,
  214. profileIds: profile.callTreeNodeProfileIdMap.get(node),
  215. };
  216. if (parent) {
  217. parent.children.push(frame);
  218. } else {
  219. this.root.children.push(frame);
  220. }
  221. stack.push(frame);
  222. idx++;
  223. };
  224. const closeFrame = (_node: CallTreeNode, value: number) => {
  225. const stackTop = stack.pop();
  226. if (!stackTop) {
  227. throw new Error('Unbalanced stack');
  228. }
  229. stackTop.end = value;
  230. stackTop.depth = stack.length;
  231. // Dont draw 0 width frames
  232. if (stackTop.end - stackTop.start === 0) {
  233. return;
  234. }
  235. frames.push(stackTop);
  236. this.depth = Math.max(stackTop.depth, this.depth);
  237. };
  238. function visit(node: CallTreeNode, start: number) {
  239. if (!node.frame.isRoot) {
  240. openFrame(node, start);
  241. }
  242. let childTime = 0;
  243. node.children.forEach(child => {
  244. visit(child, start + childTime);
  245. childTime += child.totalWeight;
  246. });
  247. if (!node.frame.isRoot) {
  248. closeFrame(node, start + node.totalWeight);
  249. }
  250. }
  251. visit(profile.callTree, 0);
  252. return frames;
  253. }
  254. findAllMatchingFramesBy(
  255. query: string,
  256. fields: (keyof FlamegraphFrame['frame'])[]
  257. ): FlamegraphFrame[] {
  258. const matches: FlamegraphFrame[] = [];
  259. if (!fields.length) {
  260. throw new Error('No fields provided');
  261. }
  262. if (fields.length === 1) {
  263. for (let i = 0; i < this.frames.length; i++) {
  264. if (this.frames[i].frame[fields[0]] === query) {
  265. matches.push(this.frames[i]);
  266. }
  267. }
  268. return matches;
  269. }
  270. for (let i = 0; i < this.frames.length; i++) {
  271. for (let j = fields.length; j--; ) {
  272. if (this.frames[i].frame[fields[j]] === query) {
  273. matches.push(this.frames[i]);
  274. }
  275. }
  276. }
  277. return matches;
  278. }
  279. findAllMatchingFrames(frameName?: string, framePackage?: string): FlamegraphFrame[] {
  280. framePackage = tryTrimPackage(framePackage);
  281. const matches: FlamegraphFrame[] = [];
  282. for (let i = 0; i < this.frames.length; i++) {
  283. if (
  284. this.frames[i].frame.name === frameName &&
  285. // the framePackage can match either the package or the module
  286. // this is an artifact of how we previously used image
  287. (tryTrimPackage(this.frames[i].frame.package) === framePackage ||
  288. this.frames[i].frame.module === framePackage)
  289. ) {
  290. matches.push(this.frames[i]);
  291. }
  292. }
  293. return matches;
  294. }
  295. }
  296. function tryTrimPackage(pkg?: string): string | undefined {
  297. return pkg ? trimPackage(pkg) : pkg;
  298. }