-
Notifications
You must be signed in to change notification settings - Fork 255
Expand file tree
/
Copy pathcache.js
More file actions
78 lines (64 loc) · 1.94 KB
/
cache.js
File metadata and controls
78 lines (64 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
const configCache = new Map();
const bucketOwnerCache = new Map();
const namespace = {
bucket: 'bkt',
account: 'acc',
};
function cacheSet(cache, key, value, ttl) {
const expiry = Date.now() + ttl;
cache.set(key, { expiry, value });
}
function cacheGet(cache, key) {
const cachedValue = cache.get(key);
if (cachedValue === undefined) {
return undefined;
}
const { expiry, value } = cachedValue;
if (expiry <= Date.now()) {
cache.delete(key);
return undefined;
}
return value;
}
function cacheDelete(cache, key) {
cache.delete(key);
}
function cacheExpire(cache) {
const now = Date.now();
const toRemove = [];
for (const [key, { expiry }] of cache.entries()) {
if (expiry <= now) {
toRemove.push(key);
}
}
for (const key of toRemove) {
cache.delete(key);
}
return toRemove.length;
}
function formatKeyDecorator(fn) {
return (resourceClass, resourceId, ...args) => fn(`${resourceClass}:${resourceId}`, ...args);
}
const getCachedConfig = formatKeyDecorator(cacheGet.bind(null, configCache));
const setCachedConfig = formatKeyDecorator(cacheSet.bind(null, configCache));
const deleteCachedConfig = formatKeyDecorator(cacheDelete.bind(null, configCache));
const expireCachedConfigs = cacheExpire.bind(null, configCache);
const getCachedBucketOwner = cacheGet.bind(null, bucketOwnerCache);
const setCachedBucketOwner = cacheSet.bind(null, bucketOwnerCache);
const deleteCachedBucketOwner = cacheDelete.bind(null, bucketOwnerCache);
const expireCachedBucketOwners = cacheExpire.bind(null, bucketOwnerCache);
module.exports = {
namespace,
setCachedConfig,
getCachedConfig,
expireCachedConfigs,
deleteCachedConfig,
setCachedBucketOwner,
getCachedBucketOwner,
deleteCachedBucketOwner,
expireCachedBucketOwners,
// Do not access directly
// Used only for tests
configCache,
bucketOwnerCache,
};