-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCache.ts
278 lines (242 loc) · 6.54 KB
/
Cache.ts
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
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
/** @format */
import _ from "lodash";
import isFQDN from "validator/lib/isFQDN";
import { EventEmitter } from "events";
import { Record } from "./Record";
/* eslint-disable no-magic-numbers */
const CLEAN_PERIOD_MILLIS = 600 * 1000;
const PERIOD_BETWEEN_CLEANS = 1000; // Number of elements between cleans
const MAX_LISTENERS_FOR_COUNTER = 4096;
const MILLIS_PER_SECOND = 1000;
/* eslint-enable no-magic-numbers */
interface HasIsEmpty {
isEmpty(): boolean;
}
interface IsNotEmpty {
isEmpty(): false;
}
interface IsEmpty {
isEmpty(): true;
}
type MightBeEmpty =
| IsNotEmpty
| IsEmpty
| HasIsEmpty
| false
| undefined
| null;
function itIsEmpty(it: MightBeEmpty): it is IsEmpty {
if (!it || _.isNil(it)) return false;
return it.isEmpty();
}
function itIsNotEmpty(it: MightBeEmpty): it is IsNotEmpty {
if (!it || _.isNil(it)) return false;
return !it.isEmpty();
}
interface RecordEntry<T extends Record.recordtype.Any> {
record: Record.Typed<T>;
ttl: number;
}
const counter = new (class Counter extends EventEmitter {
private pit = Number.MIN_SAFE_INTEGER;
private horizon = Number.MIN_SAFE_INTEGER;
private lastCleaned: number = Date.now();
private shouldFire() {
return (
this.lastUsedValue() % PERIOD_BETWEEN_CLEANS === 0 ||
this.lastCleaned + CLEAN_PERIOD_MILLIS < Date.now()
);
}
lastUsedValue() {
return this.pit;
}
private runClean() {
_.defer(
this.emit.bind(this),
"clean",
Math.max(this.lastUsedValue() - PERIOD_BETWEEN_CLEANS, this.horizon),
);
}
nextValue() {
if (this.lastUsedValue() === Number.MAX_SAFE_INTEGER) {
// Congrats, you cycled over -- we're resetting everything.
this.horizon = Number.MAX_SAFE_INTEGER;
this.runClean();
this.horizon = this.pit = Number.MIN_SAFE_INTEGER;
} else if (this.shouldFire()) {
this.runClean();
this.horizon = this.lastUsedValue();
this.lastCleaned = Date.now();
}
return this.pit++;
}
})();
counter.setMaxListeners(MAX_LISTENERS_FOR_COUNTER);
function reverseHostname(hostname: string): string[] {
if (!isFQDN(hostname)) {
throw new Error(
`Hostname to cache is not a fully qualified domain name (FQDN): ${JSON.stringify(
hostname,
)} (${typeof hostname})`,
);
}
return _.reject(_.reverse(hostname.split(".")), _.isEmpty);
}
/* eslint-disable no-use-before-define */
interface Subdomains {
[key: string]: ResultCache;
}
/* eslint-enable no-use-before-define */
class RecordCache<T extends Record.recordtype.Any> implements HasIsEmpty {
private readonly _records: RecordEntry<T>[];
private readonly _setAt = Date.now();
private readonly _setPit = counter.nextValue();
constructor(records: RecordEntry<T>[]) {
this._records = _.cloneDeep(records);
this._listenForClean();
}
_listenForClean(): void {
if (_.isEmpty(this._records)) return;
counter.once("clean", this.clean.bind(this));
}
get records(): RecordEntry<T>[] {
const now = Date.now();
return _.cloneDeep(
_.filter(this._records, (record) => {
if (_.isEmpty(record) || _.isEmpty(record.record)) return false;
const ttlSeconds = record.ttl;
return ttlSeconds * MILLIS_PER_SECOND + this._setAt >= now;
}),
);
}
private clean(horizon: number = Number.MIN_SAFE_INTEGER): void {
const { _setPit, _records } = this;
if (_.isEmpty(_records)) return;
if (_setPit <= horizon) {
_records.length = 0;
} else {
this._listenForClean();
}
}
isEmpty() {
this.clean();
return _.isEmpty(this._records);
}
}
type RecordMapping = {
[T in Record.recordtype.Any]: RecordCache<T>;
};
class ResultCache implements HasIsEmpty {
private readonly _mapping = {} as RecordMapping;
private readonly _subdomains = {} as Subdomains;
constructor() {
this._listenForClean();
}
_listenForClean(): void {
counter.once("clean", this.clean.bind(this));
}
isEmpty(): boolean {
this.clean();
return (
_.every(this._mapping, itIsEmpty) && _.every(this._subdomains, itIsEmpty)
);
}
private clean(): void {
_.forOwn(this._subdomains, (results, sub) => {
if (itIsEmpty(results)) {
_.unset(this._subdomains, sub);
}
});
_.forOwn(this._mapping, (records, rrtype) => {
if (itIsEmpty(records)) {
_.unset(this._mapping, rrtype);
}
});
this._listenForClean();
}
getRecordCache<T extends Record.recordtype.Any>(
rrtype: T,
): RecordCache<T> | false {
const cache = this._mapping[rrtype];
if (itIsNotEmpty(cache)) {
return cache as RecordCache<T>;
} else {
_.unset(this._mapping, rrtype);
return false;
}
}
getSubdomain(sub: string): ResultCache {
const oldSub = this._subdomains[sub];
if (!oldSub || _.isEmpty(oldSub)) {
return (this._subdomains[sub] = new ResultCache());
} else {
return oldSub;
}
}
private setRecordCache<T extends Record.recordtype.Any>(
rrtype: T,
records: RecordEntry<T>[],
): void {
if (_.isEmpty(_.compact(records))) {
_.unset(this._mapping, rrtype);
} else {
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
/* eslint-disable @typescript-eslint/no-explicit-any */
(this._mapping as any)[rrtype] = new RecordCache(records);
/* eslint-enable @typescript-eslint/no-unsafe-member-access */
/* eslint-enable @typescript-eslint/no-explicit-any */
}
}
setResult<T extends Record.recordtype.Any>(
domainParts: string[],
rrtype: T,
records: RecordEntry<T>[],
): void {
if (_.isEmpty(domainParts)) {
this.setRecordCache(rrtype, records);
} else {
const [head, ...rest] = domainParts;
this.getSubdomain(head).setResult(rest, rrtype, records);
}
}
getResult<T extends Record.recordtype.Any>(
domainParts: string[],
rrtype: T,
): Record.Typed<T>[] | false {
if (_.isEmpty(domainParts)) {
const result = this.getRecordCache(rrtype);
if (result !== false && itIsNotEmpty(result)) {
return _.map(result.records, "record");
} else {
return false;
}
} else {
const [head, ...rest] = domainParts;
return this.getSubdomain(head).getResult(rest, rrtype);
}
}
}
export default new (class DnsCache {
private readonly root = new ResultCache();
put<T extends Record.recordtype.Any>(
hostname: string,
rrtype: T,
records: RecordEntry<T>[],
): void {
records = _.compact(records);
if (_.isEmpty(hostname) || _.isEmpty(records)) return;
this.root.setResult(reverseHostname(hostname), rrtype, records);
}
check<T extends Record.recordtype.Any>(
hostname: string,
rrtype: T,
): false | Record.Typed<T>[] {
if (_.isEmpty(hostname)) return false;
const result = this.root.getResult(reverseHostname(hostname), rrtype);
if (result && !_.isEmpty(result)) {
return result;
} else {
return false;
}
}
})();