flamegraphSearch.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import {useCallback, useEffect, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import Fuse from 'fuse.js';
  5. import SearchBar from 'sentry/components/searchBar';
  6. import {t} from 'sentry/locale';
  7. import {CanvasPoolManager} from 'sentry/utils/profiling/canvasScheduler';
  8. import {Flamegraph} from 'sentry/utils/profiling/flamegraph';
  9. import type {FlamegraphSearch as FlamegraphSearchResults} from 'sentry/utils/profiling/flamegraph/flamegraphStateProvider/flamegraphSearch';
  10. import {useFlamegraphSearch} from 'sentry/utils/profiling/flamegraph/useFlamegraphSearch';
  11. import {
  12. FlamegraphFrame,
  13. getFlamegraphFrameSearchId,
  14. } from 'sentry/utils/profiling/flamegraphFrame';
  15. import {memoizeByReference} from 'sentry/utils/profiling/profile/utils';
  16. import {isRegExpString, parseRegExp} from 'sentry/utils/profiling/validators/regExp';
  17. function sortFrameResults(
  18. frames: FlamegraphSearchResults['results']
  19. ): Array<FlamegraphFrame> {
  20. // If frames have the same start times, move frames with lower stack depth first.
  21. // This results in top down and left to right iteration
  22. return [...frames.values()]
  23. .map(f => f.frame)
  24. .sort((a, b) =>
  25. a.start === b.start
  26. ? numericSort(a.depth, b.depth, 'asc')
  27. : numericSort(a.start, b.start, 'asc')
  28. );
  29. }
  30. function findBestMatchFromFuseMatches(
  31. matches: ReadonlyArray<Fuse.FuseResultMatch>
  32. ): Fuse.RangeTuple | null {
  33. let bestMatch: Fuse.RangeTuple | null = null;
  34. let bestMatchLength = 0;
  35. let bestMatchStart = -1;
  36. for (let i = 0; i < matches.length; i++) {
  37. const match = matches[i];
  38. for (let j = 0; j < match.indices.length; j++) {
  39. const index = match.indices[j];
  40. const matchLength = index[1] - index[0];
  41. if (matchLength < 0) {
  42. // Fuse sometimes returns negative indices - we will just skip them for now.
  43. continue;
  44. }
  45. // We only override the match if the match is longer than the current best match
  46. // or if the matches are the same length, but the start is earlier in the string
  47. if (
  48. matchLength > bestMatchLength ||
  49. (matchLength === bestMatchLength && index[0] > bestMatchStart)
  50. ) {
  51. // Offset end by 1 else we are always trailing by 1 character.
  52. bestMatch = [index[0], index[1] + 1];
  53. bestMatchLength = matchLength;
  54. bestMatchStart = index[0];
  55. }
  56. }
  57. }
  58. return bestMatch;
  59. }
  60. function findBestMatchFromRegexpMatchArray(
  61. matches: RegExpMatchArray[]
  62. ): Fuse.RangeTuple | null {
  63. let bestMatch: Fuse.RangeTuple | null = null;
  64. let bestMatchLength = 0;
  65. let bestMatchStart = -1;
  66. for (let i = 0; i < matches.length; i++) {
  67. const index = matches[i].index;
  68. if (index === undefined) {
  69. continue;
  70. }
  71. // We only override the match if the match is longer than the current best match
  72. // or if the matches are the same length, but the start is earlier in the string
  73. if (
  74. matches[i].length > bestMatchLength ||
  75. (matches[i].length === bestMatchLength && index[0] > bestMatchStart)
  76. ) {
  77. bestMatch = [index, index + matches[i].length];
  78. bestMatchLength = matches[i].length;
  79. bestMatchStart = index;
  80. }
  81. }
  82. return bestMatch;
  83. }
  84. const memoizedSortFrameResults = memoizeByReference(sortFrameResults);
  85. function frameSearch(
  86. query: string,
  87. frames: ReadonlyArray<FlamegraphFrame>,
  88. index: Fuse<FlamegraphFrame>
  89. ): FlamegraphSearchResults['results'] {
  90. const results: FlamegraphSearchResults['results'] = new Map();
  91. if (isRegExpString(query)) {
  92. const [_, lookup, flags] = parseRegExp(query) ?? [];
  93. let matches = 0;
  94. try {
  95. if (!lookup) {
  96. throw new Error('Invalid RegExp');
  97. }
  98. for (let i = 0; i < frames.length; i++) {
  99. const frame = frames[i];
  100. const re = new RegExp(lookup, flags ?? 'g');
  101. const reMatches = Array.from(frame.frame.name.trim().matchAll(re));
  102. const match = findBestMatchFromRegexpMatchArray(reMatches);
  103. if (match) {
  104. const frameId = getFlamegraphFrameSearchId(frame);
  105. results.set(frameId, {
  106. frame,
  107. match,
  108. });
  109. matches += 1;
  110. }
  111. }
  112. } catch (e) {
  113. Sentry.captureMessage(e.message);
  114. }
  115. if (matches <= 0) {
  116. return results;
  117. }
  118. return results;
  119. }
  120. const fuseResults = index.search(query);
  121. if (fuseResults.length <= 0) {
  122. return results;
  123. }
  124. for (let i = 0; i < fuseResults.length; i++) {
  125. const fuseFrameResult = fuseResults[i];
  126. const frame = fuseFrameResult.item;
  127. const frameId = getFlamegraphFrameSearchId(frame);
  128. const match = findBestMatchFromFuseMatches(fuseFrameResult.matches ?? []);
  129. if (match) {
  130. results.set(frameId, {
  131. frame,
  132. match,
  133. });
  134. }
  135. }
  136. return results;
  137. }
  138. const numericSort = (
  139. a: null | undefined | number,
  140. b: null | undefined | number,
  141. direction: 'asc' | 'desc'
  142. ): number => {
  143. if (a === b) {
  144. return 0;
  145. }
  146. if (a === null || a === undefined) {
  147. return 1;
  148. }
  149. if (b === null || b === undefined) {
  150. return -1;
  151. }
  152. return direction === 'asc' ? a - b : b - a;
  153. };
  154. interface FlamegraphSearchProps {
  155. canvasPoolManager: CanvasPoolManager;
  156. flamegraphs: Flamegraph | Flamegraph[];
  157. }
  158. function FlamegraphSearch({
  159. flamegraphs,
  160. canvasPoolManager,
  161. }: FlamegraphSearchProps): React.ReactElement | null {
  162. const [search, dispatchSearch] = useFlamegraphSearch();
  163. const [didInitialSearch, setDidInitialSearch] = useState(!search.query);
  164. const allFrames = useMemo(() => {
  165. if (Array.isArray(flamegraphs)) {
  166. return flamegraphs.reduce(
  167. (acc: FlamegraphFrame[], graph) => acc.concat(graph.frames),
  168. []
  169. );
  170. }
  171. return flamegraphs.frames;
  172. }, [flamegraphs]);
  173. const searchIndex = useMemo(() => {
  174. return new Fuse(allFrames, {
  175. keys: ['frame.name'],
  176. threshold: 0.3,
  177. includeMatches: true,
  178. findAllMatches: true,
  179. ignoreLocation: true,
  180. });
  181. }, [allFrames]);
  182. const onZoomIntoFrame = useCallback(
  183. (frame: FlamegraphFrame) => {
  184. canvasPoolManager.dispatch('zoom at frame', [frame, 'min']);
  185. canvasPoolManager.dispatch('highlight frame', [frame, 'selected']);
  186. },
  187. [canvasPoolManager]
  188. );
  189. useEffect(() => {
  190. if (typeof search.index !== 'number') {
  191. return;
  192. }
  193. const frames = memoizedSortFrameResults(search.results);
  194. if (frames[search.index]) {
  195. onZoomIntoFrame(frames[search.index]);
  196. }
  197. }, [search.results, search.index, onZoomIntoFrame]);
  198. const handleChange: (value: string) => void = useCallback(
  199. value => {
  200. if (!value) {
  201. dispatchSearch({type: 'clear search'});
  202. return;
  203. }
  204. dispatchSearch({
  205. type: 'set results',
  206. payload: {
  207. results: frameSearch(value, allFrames, searchIndex),
  208. query: value,
  209. },
  210. });
  211. },
  212. [dispatchSearch, allFrames, searchIndex]
  213. );
  214. useEffect(() => {
  215. if (didInitialSearch || allFrames.length === 0) {
  216. return;
  217. }
  218. handleChange(search.query);
  219. setDidInitialSearch(true);
  220. }, [didInitialSearch, handleChange, allFrames, search.query]);
  221. const onNextSearchClick = useCallback(() => {
  222. const frames = memoizedSortFrameResults(search.results);
  223. if (!frames.length) {
  224. return;
  225. }
  226. if (search.index === null || search.index === frames.length - 1) {
  227. dispatchSearch({type: 'set search index position', payload: 0});
  228. return;
  229. }
  230. dispatchSearch({
  231. type: 'set search index position',
  232. payload: search.index + 1,
  233. });
  234. }, [search.results, search.index, dispatchSearch]);
  235. const onPreviousSearchClick = useCallback(() => {
  236. const frames = memoizedSortFrameResults(search.results);
  237. if (!frames.length) {
  238. return;
  239. }
  240. if (search.index === null || search.index === 0) {
  241. dispatchSearch({
  242. type: 'set search index position',
  243. payload: frames.length - 1,
  244. });
  245. return;
  246. }
  247. dispatchSearch({
  248. type: 'set search index position',
  249. payload: search.index - 1,
  250. });
  251. }, [search.results, search.index, dispatchSearch]);
  252. const handleKeyDown = useCallback(
  253. (evt: React.KeyboardEvent<HTMLInputElement>) => {
  254. if (evt.key === 'ArrowDown') {
  255. evt.preventDefault();
  256. onNextSearchClick();
  257. } else if (evt.key === 'ArrowUp') {
  258. evt.preventDefault();
  259. onPreviousSearchClick();
  260. }
  261. },
  262. [onNextSearchClick, onPreviousSearchClick]
  263. );
  264. return (
  265. <StyledSearchBar
  266. placeholder={t('Find Frames')}
  267. query={search.query}
  268. onChange={handleChange}
  269. onKeyDown={handleKeyDown}
  270. />
  271. );
  272. }
  273. const StyledSearchBar = styled(SearchBar)`
  274. .search-input {
  275. height: 28px;
  276. }
  277. flex: 1 1 100%;
  278. `;
  279. export {FlamegraphSearch};