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