Skip to content

Commit f4bb557

Browse files
committed
Add: glob in fetch delay
1 parent 3272660 commit f4bb557

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed

src/lib/fetch-delay.js

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,34 +13,46 @@ pref.ready().then(() => {
1313
});
1414

1515
const lock = createLockPool({maxActiveReader: 3});
16-
let meta = new Map;
16+
let rules = [];
1717

1818
function update() {
19-
const newMeta = new Map;
19+
const newRules = [];
2020
for (const lines of parseText(pref.get('fetchDelay'))) {
2121
const [origin, delay] = lines[0].trim().split(/\s+/);
2222
const delayMs = Number(delay) * 1000;
23-
newMeta.set(origin, {
24-
...meta.get(origin),
23+
const oldRule = rules.find(rule => rule.origin === origin);
24+
newRules.push({
25+
...oldRule,
26+
origin,
2527
delayMs
2628
});
2729
}
28-
meta = newMeta;
30+
rules = newRules;
31+
}
32+
33+
function matchGlob(pattern, string) {
34+
if (!pattern.includes("*")) {
35+
return pattern === string;
36+
}
37+
return new RegExp(`^${pattern.replace(/\*/g, ".*")}$`).test(string);
2938
}
3039

3140
export async function fetchDelay(url, cb) {
3241
const origin = new URL(url).origin;
33-
if (meta.has(origin)) {
34-
return await lock.write([origin], async () => {
35-
const t = (meta.get(origin).lastFetch || 0) + meta.get(origin).delayMs - Date.now();
42+
const rule = rules.find(rule => matchGlob(rule.origin, origin));
43+
// calculate the delay if there is a matching rule
44+
if (rule) {
45+
return await lock.write([rule.origin], async () => {
46+
const t = (rule.lastFetch || 0) + rule.delayMs - Date.now();
3647
await delay(t > 0 ? t : 0);
3748
try {
3849
return await cb();
3950
} finally {
40-
meta.get(origin).lastFetch = Date.now();
51+
rule.lastFetch = Date.now();
4152
}
4253
});
4354
}
55+
// no matching rule, just fetch, still restricted by the maxActiveReader
4456
return await lock.read([origin], cb);
4557
}
4658

0 commit comments

Comments
 (0)