-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathboundedRuntimeState.js
More file actions
138 lines (123 loc) · 4.75 KB
/
Copy pathboundedRuntimeState.js
File metadata and controls
138 lines (123 loc) · 4.75 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
'use strict';
const { BoundedTtlMap } = require('./boundedTtlMap.js');
function boundedDuration(value, maxDurationMs) {
const duration = Number(value);
if (!Number.isFinite(duration) || duration <= 0) return 0;
return Math.min(Math.floor(duration), maxDurationMs);
}
/** A fail-closed per-key cooldown. Active entries are never evicted for a new caller. */
class BoundedCooldownGate {
constructor({ name, maxKeys, maxDurationMs, now = Date.now } = {}) {
this._now = now;
this.maxDurationMs = requirePositiveInteger(maxDurationMs, 'maxDurationMs');
this.entries = new BoundedTtlMap({
name,
maxSize: maxKeys,
now,
isProtected: (entry, current) => Number(entry?.expiresAt) > current,
});
this.deniedByCooldown = 0;
this.deniedByCapacity = 0;
}
tryAcquire(key, durationMs) {
const duration = boundedDuration(durationMs, this.maxDurationMs);
if (duration === 0) return { ok: true, disabled: true, retryMs: 0 };
const now = this._now();
const existing = this.entries.get(key);
if (existing) {
this.deniedByCooldown += 1;
return { ok: false, reason: 'cooldown', retryMs: Math.max(0, existing.expiresAt - now) };
}
if (!this.entries.set(key, { expiresAt: now + duration })) {
this.deniedByCapacity += 1;
return { ok: false, reason: 'capacity', retryMs: duration };
}
return { ok: true, retryMs: 0 };
}
getMetrics() {
return { ...this.entries.getMetrics(), deniedByCooldown: this.deniedByCooldown, deniedByCapacity: this.deniedByCapacity };
}
}
/** A bounded, lossy notification de-duplicator. Capacity pressure suppresses notices. */
class BoundedNotificationThrottle {
constructor({ name, maxKeys, maxDurationMs, now = Date.now } = {}) {
this._now = now;
this.maxDurationMs = requirePositiveInteger(maxDurationMs, 'maxDurationMs');
this.entries = new BoundedTtlMap({ name, maxSize: maxKeys, now });
this.suppressed = 0;
}
shouldNotify(key, durationMs) {
const duration = boundedDuration(durationMs, this.maxDurationMs);
if (duration === 0) return true;
if (this.entries.get(key)) {
this.suppressed += 1;
return false;
}
// This map may evict an old notification key. A notification is not a
// security decision, so suppressing it on the unlikely admission error
// is preferable to retaining unbounded state.
if (!this.entries.set(key, { expiresAt: this._now() + duration })) {
this.suppressed += 1;
return false;
}
return true;
}
getMetrics() {
return { ...this.entries.getMetrics(), suppressed: this.suppressed };
}
}
/**
* Bounded cache for in-flight asynchronous acquisition (for example a Discord
* webhook). In-flight entries are protected: when every slot is in flight, the
* caller is rejected instead of duplicating a side effect.
*/
class BoundedAsyncCache {
constructor({ name, maxKeys, ttlMs, now = Date.now } = {}) {
this._now = now;
this.ttlMs = requirePositiveInteger(ttlMs, 'ttlMs');
this.entries = new BoundedTtlMap({
name,
maxSize: maxKeys,
now,
isProtected: entry => Boolean(entry?.pending),
});
this.admissionRejected = 0;
}
get(key) {
return this.entries.get(key)?.promise;
}
getOrCreate(key, create) {
const existing = this.get(key);
if (existing) return existing;
const entry = { pending: true, promise: null };
if (!this.entries.set(key, entry)) {
this.admissionRejected += 1;
const error = new Error('bounded async cache is full');
error.code = 'ASYNC_CACHE_FULL';
return Promise.reject(error);
}
const pending = Promise.resolve().then(create);
entry.promise = pending;
pending.then(
() => {
entry.pending = false;
entry.expiresAt = this._now() + this.ttlMs;
},
() => {
if (this.entries.get(key) === entry) this.entries.delete(key);
},
);
return pending;
}
delete(key) {
return this.entries.delete(key);
}
getMetrics() {
return { ...this.entries.getMetrics(), admissionRejected: this.admissionRejected };
}
}
function requirePositiveInteger(value, name) {
if (!Number.isSafeInteger(value) || value <= 0) throw new TypeError(`${name} must be a positive integer`);
return value;
}
module.exports = { BoundedCooldownGate, BoundedNotificationThrottle, BoundedAsyncCache, boundedDuration };