Skip to content

Commit fb698e9

Browse files
authored
internal: move the deprecated makeFifoCache implementation in the SDK (#4353)
1 parent 98fb43f commit fb698e9

File tree

1 file changed

+69
-2
lines changed

1 file changed

+69
-2
lines changed
+69-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,72 @@
1-
import { makeFifoCache } from '@sentry/core';
2-
31
import type { AndroidCombinedProfileEvent, CombinedProfileEvent } from './types';
42

53
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

Comments
 (0)