qps.js
1.97 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
'use strict';
const logger = global.yoho.logger;
const cache = global.yoho.cache.master;
const config = global.yoho.config;
const Promise = require('bluebird');
const _ = require('lodash');
// 超出访问限制ip限制访问1小时
const limiterIpTime = 3600;
// 页面访问限制
const MAX_TIMES = config.REQUEST_LIMIT;
const limiterKey = 'limiter2';
module.exports = async({user}, next) => {
if (!user.app || !user.ip) {
return next();
}
// 存储规则的cache keys
let ruleKeys = {};
let getOp = {};
_.forEach(MAX_TIMES, (val, key) => {
ruleKeys[key] = `${user.app}:${limiterKey}:${key}:max:${user.ip}`;
getOp[key] = cache.getAsync(ruleKeys[key]);
});
getOp.human = cache.getAsync(`${user.app}:${limiterKey}:ishuman:${user.ip}`);
return Promise.props(getOp).then((results) => {
if (results.human) { // 经过验证码之后1小时有效期内不再验证qps
logger.info('[qps] this user[%o] is being marked as human', user);
return {};
}
// 遍历限制规则,若满足返回相应处理策略, 否则页面访问次数加1
let operation = {};
_.forEach(MAX_TIMES, (val, key) => {
let cacheKey = ruleKeys[key];
if (!results[key]) {
operation[cacheKey] = cache.setAsync(cacheKey, 1, +key);
} else if (+results[key] > +val) {
logger.info('[qps] this user[%j] is being marked as rejected', user);
operation[`${user.app}:${limiterKey}:${user.ip}`] = cache.setAsync(`${user.app}:${limiterKey}:${user.ip}`, 1, limiterIpTime);
} else {
operation[cacheKey] = cache.incrAsync(cacheKey, 1);
}
});
return Promise.props(operation);
}).then((result) => {
// logger.debug('[qps] user[%j] result[%j]', user, result); // eslint-disable-line
}).catch(err=>{
logger.error(err);
}).finally(() => {
next();
});
};