flamegraphSearch.tsx 9.0 KB

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