-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
97 lines (78 loc) · 2.62 KB
/
index.js
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
import fp from 'fastify-plugin'
import onFinished from 'on-finished'
import { RedisStore } from './lib/redisStore.js'
import { LocalStore } from './lib/localStore.js'
import { DEFAULT_OPTIONS, HEADERS } from './lib/constants.js'
import { calculateDelay, convertToMs } from './lib/helpers.js'
const slowDownPlugin = async (fastify, settings) => {
const options = { ...DEFAULT_OPTIONS, ...settings }
const store = settings.redis
? new RedisStore(
settings.redis,
'fastify-slow-down',
convertToMs(options.timeWindow)
)
: new LocalStore(convertToMs(options.timeWindow), options.inMemoryCacheSize)
const applySkip = async (req, reply, key) => {
await store.decrementOnKey(key)
if (options.headers && req.slowDown.remaining < options.delayAfter) {
reply.header(HEADERS.remaining, req.slowDown.remaining + 1)
}
}
fastify.decorateRequest('slowDown', null)
fastify.addHook('onClose', () => store.close())
fastify.addHook('onRequest', async (req, reply) => {
if (options.skip?.(req, reply)) {
return
}
const key = options.keyGenerator(req)
const { counter: requestCounter } = await store.incrementOnKey(key)
const delayMs = calculateDelay(requestCounter, options)
const hasDelay = delayMs > 0
const remainingRequests = Math.max(options.delayAfter - requestCounter, 0)
if (options.headers) {
reply.header(HEADERS.limit, options.delayAfter)
reply.header(HEADERS.remaining, remainingRequests)
hasDelay && reply.header(HEADERS.delay, delayMs)
}
req.slowDown = {
limit: options.delayAfter,
delay: hasDelay ? delayMs : undefined,
current: requestCounter,
remaining: remainingRequests
}
if (!hasDelay) {
return
}
if (requestCounter - 1 === options.delayAfter) {
options.onLimitReached?.(req, reply, options)
}
let timeout, resolve
const promise = new Promise(res => {
resolve = res
timeout = setTimeout(res, delayMs)
})
onFinished(req.raw, () => {
clearTimeout(timeout)
resolve('requestFinished')
})
const promiseResult = await promise
if (promiseResult === 'requestFinished') {
reply.send('')
return reply
}
})
fastify.addHook('onSend', async (req, reply) => {
const key = options.keyGenerator(req)
if (options.skipFailedRequests && reply.statusCode >= 400) {
await applySkip(req, reply, key)
}
if (options.skipSuccessfulRequests && reply.statusCode < 400) {
await applySkip(req, reply, key)
}
})
}
export default fp(slowDownPlugin, {
fastify: '5.x',
name: 'fastify-slow-down'
})