|
1 | 1 | import type { Event } from '@sentry/types'; |
| 2 | +import { makeFifoCache } from '@sentry/utils'; |
2 | 3 |
|
3 | | -/** |
4 | | - * Creates a cache that evicts keys in fifo order |
5 | | - * @param size {Number} |
6 | | - */ |
7 | | -export function makeProfilingCache<Key extends string, Value extends Event>( |
8 | | - size: number, |
9 | | -): { |
10 | | - get: (key: Key) => Value | undefined; |
11 | | - add: (key: Key, value: Value) => void; |
12 | | - delete: (key: Key) => boolean; |
13 | | - clear: () => void; |
14 | | - size: () => number; |
15 | | -} { |
16 | | - // Maintain a fifo queue of keys, we cannot rely on Object.keys as the browser may not support it. |
17 | | - let evictionOrder: Key[] = []; |
18 | | - let cache: Record<string, Value> = {}; |
19 | | - |
20 | | - return { |
21 | | - add(key: Key, value: Value) { |
22 | | - while (evictionOrder.length >= size) { |
23 | | - // shift is O(n) but this is small size and only happens if we are |
24 | | - // exceeding the cache size so it should be fine. |
25 | | - const evictCandidate = evictionOrder.shift(); |
26 | | - |
27 | | - if (evictCandidate !== undefined) { |
28 | | - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete |
29 | | - delete cache[evictCandidate]; |
30 | | - } |
31 | | - } |
32 | | - |
33 | | - // in case we have a collision, delete the old key. |
34 | | - if (cache[key]) { |
35 | | - this.delete(key); |
36 | | - } |
37 | | - |
38 | | - evictionOrder.push(key); |
39 | | - cache[key] = value; |
40 | | - }, |
41 | | - clear() { |
42 | | - cache = {}; |
43 | | - evictionOrder = []; |
44 | | - }, |
45 | | - get(key: Key): Value | undefined { |
46 | | - return cache[key]; |
47 | | - }, |
48 | | - size() { |
49 | | - return evictionOrder.length; |
50 | | - }, |
51 | | - // Delete cache key and return true if it existed, false otherwise. |
52 | | - delete(key: Key): boolean { |
53 | | - if (!cache[key]) { |
54 | | - return false; |
55 | | - } |
56 | | - |
57 | | - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete |
58 | | - delete cache[key]; |
59 | | - |
60 | | - for (let i = 0; i < evictionOrder.length; i++) { |
61 | | - if (evictionOrder[i] === key) { |
62 | | - evictionOrder.splice(i, 1); |
63 | | - break; |
64 | | - } |
65 | | - } |
66 | | - |
67 | | - return true; |
68 | | - }, |
69 | | - }; |
70 | | -} |
71 | | - |
72 | | -export const PROFILING_EVENT_CACHE = makeProfilingCache<string, Event>(20); |
| 4 | +export const PROFILING_EVENT_CACHE = makeFifoCache<string, Event>(20); |
0 commit comments