Authored by 周少峰

request limit

@@ -59,11 +59,6 @@ if (config.zookeeperServer) { @@ -59,11 +59,6 @@ if (config.zookeeperServer) {
59 59
60 app.enable('trust proxy'); 60 app.enable('trust proxy');
61 61
62 -// 请求限制中间件  
63 -if (!app.locals.devEnv) {  
64 - app.use(require('./doraemon/middleware/limiter'));  
65 -}  
66 -  
67 app.set('subdomain offset', 2); 62 app.set('subdomain offset', 2);
68 63
69 // 添加请求上下文 64 // 添加请求上下文
@@ -149,6 +144,12 @@ try { @@ -149,6 +144,12 @@ try {
149 app.use(mobileRefer()); 144 app.use(mobileRefer());
150 app.use(mobileCheck()); 145 app.use(mobileCheck());
151 app.use(user()); 146 app.use(user());
  147 +
  148 + // 请求限制中间件
  149 + if (!app.locals.devEnv) {
  150 + app.use(require('./doraemon/middleware/limiter'));
  151 + }
  152 +
152 app.use(seo()); 153 app.use(seo());
153 app.use(setPageInfo()); 154 app.use(setPageInfo());
154 app.use(layoutTools()); 155 app.use(layoutTools());
  1 +/**
  2 + * 限制页面访问次数,如超过限制次数,返回相应策略(目前是ip加入黑名单,跳转图形验证码页面,解除限制)
  3 + * 当前规则只针对未登录用户
  4 + */
  5 +
1 'use strict'; 6 'use strict';
2 7
3 const logger = global.yoho.logger; 8 const logger = global.yoho.logger;
4 const cache = global.yoho.cache.master; 9 const cache = global.yoho.cache.master;
5 const config = global.yoho.config; 10 const config = global.yoho.config;
6 -const ONE_DAY = 60 * 60 * 24;  
7 -const MAX_QPS = config.maxQps;  
8 -const MAX_QPS_10m = config.maxQps10m; // eslint-disable-line  
9 const _ = require('lodash'); 11 const _ = require('lodash');
10 12
11 -const PAGES = {  
12 - '/product/^\\/([\\d]+)(.*)/': 5,  
13 - '/product/list/index': 5,  
14 - '/product/search/index': 5  
15 -};  
16 -  
17 -function urlJoin(a, b) {  
18 - if (_.endsWith(a, '/') && _.startsWith(b, '/')) {  
19 - return a + b.substring(1, b.length);  
20 - } else if (!_.endsWith(a, '/') && !_.startsWith(b, '/')) {  
21 - return a + '/' + b;  
22 - } else {  
23 - return a + b;  
24 - } 13 +// 页面访问限制
  14 +const MAX_TIMES = {
  15 + // 30s 最多访问15次
  16 + 30: 15,
  17 + // 60s 最多访问15次
  18 + 60: 20,
  19 + // 100s 最多访问15次
  20 + 600: 100
25 } 21 }
26 22
27 module.exports = (limiter, policy) => { 23 module.exports = (limiter, policy) => {
28 - const req = limiter.req,  
29 - res = limiter.res,  
30 - next = limiter.next; // eslint-disable-line  
31 -  
32 - const key = `pc:limiter:${limiter.remoteIp}`;  
33 - const keyMax = `pc:limiter:max:${limiter.remoteIp}`;  
34 - const key10m = `pc:limiter:10m:${limiter.remoteIp}`;  
35 - const key10mMax = `pc:limiter:10m:max:${limiter.remoteIp}`;  
36 -  
37 - res.on('render', function() {  
38 - let route = req.route ? req.route.path : '';  
39 - let appPath = req.app.mountpath;  
40 -  
41 - if (_.isArray(route) && route.length > 0) {  
42 - route = route[0];  
43 - }  
44 -  
45 - let pageKey = urlJoin(appPath, route.toString()); // route may be a regexp  
46 - let pageIncr = PAGES[pageKey] || 0;  
47 -  
48 - if (pageIncr > 0) {  
49 - cache.incr(key, pageIncr, (err) => {}); // eslint-disable-line  
50 - cache.incr(key10m, pageIncr, (err) => {}); // eslint-disable-line  
51 - }  
52 - }); 24 + const req = limiter.req;
53 25
54 - return cache.getMultiAsync([key, key10m, keyMax, key10mMax]).then((results) => {  
55 - let result = results[key];  
56 - let result10m = results[key10m]; 26 + // 登录用户跳过
  27 + if (!_.isEmpty(req.user)) {
  28 + return Promise.resolve(true);
  29 + }
57 30
58 - logger.debug('qps limiter: ' + key + '@' + result + ' max: ' + MAX_QPS);  
59 - logger.debug('qps limiter:10m ' + key10m + '@' + result10m + ' max: ' + MAX_QPS_10m); // eslint-disable-line 31 + // 存储规则的cache keys
  32 + let ruleKeys = [];
60 33
61 - // 达到1分钟或是10分钟的访问限制,禁止访问  
62 - if (results[keyMax] === 1 || results[key10mMax] === 1) {  
63 - return Promise.resolve(policy);  
64 - } 34 + _.forEach(MAX_TIMES, (val, key) => {
  35 + ruleKeys.push(`${config.app}:limiter:${key}:max:${limiter.remoteIp}`); // eslint-disable-line
  36 + })
65 37
66 - // 默认数据设置  
67 - if (!result && !_.isNumber(result)) {  
68 - cache.setAsync(key, 1, 60); // 设置key,1m失效  
69 - } 38 + return cache.getMultiAsync(ruleKeys).then((results) => {
  39 + console.log(results);
70 40
71 - if (!result10m && !_.isNumber(result10m)) {  
72 - cache.setAsync(key10m, 1, 600); // 设置key,10m失效  
73 - } 41 + // 第一次访问
  42 + if (_.isEmpty(results)) {
  43 + _.forEach(ruleKeys, (val) => {
  44 + let cacheTime = val.match(/limiter:([^:]*)?:max/i)[1];
74 45
75 - // 第一次访问,都没计数,直接过  
76 - if (!result && !_.isNumber(result) && !result10m && !_.isNumber(result10m)) {  
77 - return Promise.resolve(true);  
78 - } 46 + cache.setAsync(val, 1, +cacheTime); // eslint-disable-line
  47 + })
79 48
80 - if (result === -1 || result10m === -1) {  
81 return Promise.resolve(true); 49 return Promise.resolve(true);
82 } 50 }
83 51
84 - // 判断 qps 10分钟  
85 - if (result10m === 9999) {  
86 - res.statusCode = 403;  
87 - return Promise.resolve(policy);  
88 - } else if (result10m > MAX_QPS_10m) { // eslint-disable-line  
89 - cache.setAsync(key10mMax, 1, ONE_DAY);  
90 - logger.debug('req limit', key10m); 52 + // 遍历限制规则,若满足返回相应处理策略, 否则页面访问次数加1
  53 + _.forEach(ruleKeys, (val) => {
  54 + let cacheTime = +val.match(/limiter:([^:]*)?:max/i)[1];
91 55
92 - return Promise.resolve(policy);  
93 - } 56 + if (!results[val]) {
  57 + cache.setAsync(val, 1, +cacheTime);
  58 + } else if (+results[val] > +MAX_TIMES[cacheTime]) {
  59 + return Promise.resolve(policy);
  60 + }
94 61
95 - // 判断 qps 1分钟  
96 - if (result === 9999) {  
97 - res.statusCode = 403;  
98 - return Promise.resolve(policy);  
99 - } else if (result > MAX_QPS) { // 判断 qps  
100 - cache.setAsync(keyMax, 1, ONE_DAY);  
101 - logger.debug('req limit', key);  
102 -  
103 - return Promise.resolve(policy);  
104 - } 62 + // 非异步请求访问记录加1
  63 + if (!req.xhr) {
  64 + cache.incrAsync(val, 1);
  65 + }
  66 + })
105 67
106 - cache.incrAsync(key, 1); // qps + 1  
107 - cache.incrAsync(key10m, 1); // qps + 1 68 + // 不满足任何限制规则,继续访问
108 return Promise.resolve(true); 69 return Promise.resolve(true);
109 - }); 70 + }).catch(err=>{logger.error(err)});
110 }; 71 };