flamegraph.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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.node.aggregate_duration_ns = this.root.children.reduce(
  123. (acc, frame) => acc + frame.node.aggregate_duration_ns,
  124. 0
  125. );
  126. this.root.end = this.root.start + weight;
  127. this.root.frame.totalWeight += weight;
  128. let width = 0;
  129. if (this.profile.type === 'flamegraph' && weight > 0) {
  130. width = weight;
  131. } else if (this.profile.duration > 0) {
  132. width = configSpace ? configSpace.width : this.profile.duration;
  133. } else {
  134. // If the profile duration is 0, set the flamegraph duration
  135. // to 1 second so we can render a placeholder grid
  136. width =
  137. this.profile.unit === 'nanoseconds'
  138. ? 1e9
  139. : this.profile.unit === 'microseconds'
  140. ? 1e6
  141. : this.profile.unit === 'milliseconds'
  142. ? 1e3
  143. : 1;
  144. }
  145. this.configSpace = new Rect(0, 0, width, this.depth);
  146. }
  147. buildCallOrderChart(profile: Profile): FlamegraphFrame[] {
  148. const frames: FlamegraphFrame[] = [];
  149. const stack: FlamegraphFrame[] = [];
  150. let idx = 0;
  151. const openFrame = (node: CallTreeNode, value: number) => {
  152. const parent = stack[stack.length - 1] ?? this.root;
  153. const frame: FlamegraphFrame = {
  154. key: idx,
  155. frame: node.frame,
  156. node,
  157. parent,
  158. children: [],
  159. depth: 0,
  160. start: value,
  161. end: value,
  162. };
  163. if (parent) {
  164. parent.children.push(frame);
  165. } else {
  166. this.root.children.push(frame);
  167. }
  168. stack.push(frame);
  169. idx++;
  170. };
  171. const closeFrame = (_: CallTreeNode, value: number) => {
  172. const stackTop = stack.pop();
  173. if (!stackTop) {
  174. // This is unreachable because the profile importing logic already checks this
  175. throw new Error('Unbalanced stack');
  176. }
  177. stackTop.end = value;
  178. stackTop.depth = stack.length;
  179. if (stackTop.end - stackTop.start === 0) {
  180. return;
  181. }
  182. frames.push(stackTop);
  183. this.depth = Math.max(stackTop.depth, this.depth);
  184. };
  185. profile.forEach(openFrame, closeFrame);
  186. return frames;
  187. }
  188. buildSortedChart(
  189. profile: Profile,
  190. sortFn: (tree: CallTreeNode) => void
  191. ): FlamegraphFrame[] {
  192. const frames: FlamegraphFrame[] = [];
  193. const stack: FlamegraphFrame[] = [];
  194. sortFn(profile.callTree);
  195. const virtualRoot: FlamegraphFrame = {
  196. key: -1,
  197. frame: CallTreeNode.Root.frame,
  198. node: CallTreeNode.Root,
  199. parent: null,
  200. children: [],
  201. depth: 0,
  202. start: 0,
  203. end: 0,
  204. };
  205. this.root = virtualRoot;
  206. let idx = 0;
  207. const openFrame = (node: CallTreeNode, value: number) => {
  208. const parent = stack[stack.length - 1] ?? this.root;
  209. const frame: FlamegraphFrame = {
  210. key: idx,
  211. frame: node.frame,
  212. node,
  213. parent,
  214. children: [],
  215. depth: 0,
  216. start: value,
  217. end: value,
  218. profileIds: profile.callTreeNodeProfileIdMap.get(node),
  219. };
  220. if (parent) {
  221. parent.children.push(frame);
  222. } else {
  223. this.root.children.push(frame);
  224. }
  225. stack.push(frame);
  226. idx++;
  227. };
  228. const closeFrame = (_node: CallTreeNode, value: number) => {
  229. const stackTop = stack.pop();
  230. if (!stackTop) {
  231. throw new Error('Unbalanced stack');
  232. }
  233. stackTop.end = value;
  234. stackTop.depth = stack.length;
  235. // Dont draw 0 width frames
  236. if (stackTop.end - stackTop.start === 0) {
  237. return;
  238. }
  239. frames.push(stackTop);
  240. this.depth = Math.max(stackTop.depth, this.depth);
  241. };
  242. function visit(node: CallTreeNode, start: number) {
  243. if (!node.frame.isRoot) {
  244. openFrame(node, start);
  245. }
  246. let childTime = 0;
  247. node.children.forEach(child => {
  248. visit(child, start + childTime);
  249. childTime += child.totalWeight;
  250. });
  251. if (!node.frame.isRoot) {
  252. closeFrame(node, start + node.totalWeight);
  253. }
  254. }
  255. visit(profile.callTree, 0);
  256. return frames;
  257. }
  258. findAllMatchingFramesBy(
  259. query: string,
  260. fields: (keyof FlamegraphFrame['frame'])[]
  261. ): FlamegraphFrame[] {
  262. const matches: FlamegraphFrame[] = [];
  263. if (!fields.length) {
  264. throw new Error('No fields provided');
  265. }
  266. if (fields.length === 1) {
  267. for (let i = 0; i < this.frames.length; i++) {
  268. if (this.frames[i].frame[fields[0]] === query) {
  269. matches.push(this.frames[i]);
  270. }
  271. }
  272. return matches;
  273. }
  274. for (let i = 0; i < this.frames.length; i++) {
  275. for (let j = fields.length; j--; ) {
  276. if (this.frames[i].frame[fields[j]] === query) {
  277. matches.push(this.frames[i]);
  278. }
  279. }
  280. }
  281. return matches;
  282. }
  283. findAllMatchingFrames(frameName?: string, framePackage?: string): FlamegraphFrame[] {
  284. framePackage = tryTrimPackage(framePackage);
  285. const matches: FlamegraphFrame[] = [];
  286. for (let i = 0; i < this.frames.length; i++) {
  287. if (
  288. this.frames[i].frame.name === frameName &&
  289. // the framePackage can match either the package or the module
  290. // this is an artifact of how we previously used image
  291. (tryTrimPackage(this.frames[i].frame.package) === framePackage ||
  292. this.frames[i].frame.module === framePackage)
  293. ) {
  294. matches.push(this.frames[i]);
  295. }
  296. }
  297. return matches;
  298. }
  299. }
  300. function tryTrimPackage(pkg?: string): string | undefined {
  301. return pkg ? trimPackage(pkg) : pkg;
  302. }