flamegraph.ts 9.2 KB

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