-
Notifications
You must be signed in to change notification settings - Fork 5
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add concurrent limiter and router concurrent limiter middleware
- Loading branch information
Showing
6 changed files
with
568 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,168 @@ | ||
// MIT License | ||
|
||
// Copyright (c) 2020 Tree Xie | ||
|
||
// Permission is hereby granted, free of charge, to any person obtaining a copy | ||
// of this software and associated documentation files (the "Software"), to deal | ||
// in the Software without restriction, including without limitation the rights | ||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
// copies of the Software, and to permit persons to whom the Software is | ||
// furnished to do so, subject to the following conditions: | ||
|
||
// The above copyright notice and this permission notice shall be included in all | ||
// copies or substantial portions of the Software. | ||
|
||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
// SOFTWARE. | ||
|
||
package middleware | ||
|
||
import ( | ||
"errors" | ||
"net/http" | ||
"strings" | ||
|
||
"github.com/tidwall/gjson" | ||
"github.com/vicanso/elton" | ||
"github.com/vicanso/hes" | ||
) | ||
|
||
var ( | ||
// ErrSubmitTooFrequently submit too frequently | ||
ErrSubmitTooFrequently = &hes.Error{ | ||
StatusCode: http.StatusBadRequest, | ||
Message: "submit too frequently", | ||
Category: ErrConcurrentLimiterCategory, | ||
} | ||
ErrRequireLockFunction = errors.New("require lock function") | ||
) | ||
|
||
const ( | ||
ipKey = ":ip" | ||
headerKey = "h:" | ||
queryKey = "q:" | ||
paramKey = "p:" | ||
// ErrConcurrentLimiterCategory concurrent limiter error category | ||
ErrConcurrentLimiterCategory = "elton-concurrent-limiter" | ||
) | ||
|
||
type ( | ||
// ConcurrentLimiterLock lock the key | ||
ConcurrentLimiterLock func(string, *elton.Context) (bool, func(), error) | ||
// Config concurrent limiter config | ||
ConcurrentLimiterConfig struct { | ||
// Keys keys for generate lock id | ||
Keys []string | ||
// Lock lock function | ||
Lock ConcurrentLimiterLock | ||
Skipper elton.Skipper | ||
} | ||
// concurrentLimiterKeyInfo the concurrent key's info | ||
concurrentLimiterKeyInfo struct { | ||
Name string | ||
Params bool | ||
Query bool | ||
Header bool | ||
Body bool | ||
IP bool | ||
} | ||
) | ||
|
||
// New create a concurrent limiter middleware | ||
func NewConcurrentLimiter(config ConcurrentLimiterConfig) elton.Handler { | ||
|
||
if config.Lock == nil { | ||
panic(ErrRequireLockFunction) | ||
} | ||
keys := make([]*concurrentLimiterKeyInfo, 0) | ||
// 根据配置生成key的处理 | ||
for _, key := range config.Keys { | ||
if key == ipKey { | ||
keys = append(keys, &concurrentLimiterKeyInfo{ | ||
IP: true, | ||
}) | ||
continue | ||
} | ||
if strings.HasPrefix(key, headerKey) { | ||
keys = append(keys, &concurrentLimiterKeyInfo{ | ||
Name: key[2:], | ||
Header: true, | ||
}) | ||
continue | ||
} | ||
if strings.HasPrefix(key, queryKey) { | ||
keys = append(keys, &concurrentLimiterKeyInfo{ | ||
Name: key[2:], | ||
Query: true, | ||
}) | ||
continue | ||
} | ||
if strings.HasPrefix(key, paramKey) { | ||
keys = append(keys, &concurrentLimiterKeyInfo{ | ||
Name: key[2:], | ||
Params: true, | ||
}) | ||
continue | ||
} | ||
keys = append(keys, &concurrentLimiterKeyInfo{ | ||
Name: key, | ||
Body: true, | ||
}) | ||
} | ||
skipper := config.Skipper | ||
if skipper == nil { | ||
skipper = elton.DefaultSkipper | ||
} | ||
keyLength := len(keys) | ||
return func(c *elton.Context) (err error) { | ||
if skipper(c) { | ||
return c.Next() | ||
} | ||
sb := new(strings.Builder) | ||
// 先申请假定每个value的长度 | ||
sb.Grow(8 * keyLength) | ||
// 获取 lock 的key | ||
for i, key := range keys { | ||
v := "" | ||
name := key.Name | ||
if key.IP { | ||
v = c.RealIP() | ||
} else if key.Header { | ||
v = c.GetRequestHeader(name) | ||
} else if key.Query { | ||
query := c.Query() | ||
v = query[name] | ||
} else if key.Params { | ||
v = c.Param(name) | ||
} else { | ||
v = gjson.GetBytes(c.RequestBody, name).String() | ||
} | ||
sb.WriteString(v) | ||
if i < keyLength-1 { | ||
sb.WriteRune(',') | ||
} | ||
} | ||
lockKey := sb.String() | ||
|
||
success, unlock, err := config.Lock(lockKey, c) | ||
if err != nil { | ||
err = hes.Wrap(err) | ||
return | ||
} | ||
if !success { | ||
err = ErrSubmitTooFrequently | ||
return | ||
} | ||
|
||
if unlock != nil { | ||
defer unlock() | ||
} | ||
|
||
return c.Next() | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
// MIT License | ||
|
||
// Copyright (c) 2020 Tree Xie | ||
|
||
// Permission is hereby granted, free of charge, to any person obtaining a copy | ||
// of this software and associated documentation files (the "Software"), to deal | ||
// in the Software without restriction, including without limitation the rights | ||
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
// copies of the Software, and to permit persons to whom the Software is | ||
// furnished to do so, subject to the following conditions: | ||
|
||
// The above copyright notice and this permission notice shall be included in all | ||
// copies or substantial portions of the Software. | ||
|
||
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
// SOFTWARE. | ||
|
||
package middleware | ||
|
||
import ( | ||
"errors" | ||
"net/http/httptest" | ||
"sync" | ||
"testing" | ||
"time" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/vicanso/elton" | ||
) | ||
|
||
func TestNoLockFunction(t *testing.T) { | ||
assert := assert.New(t) | ||
defer func() { | ||
r := recover() | ||
assert.Equal(r.(error), ErrRequireLockFunction) | ||
}() | ||
|
||
NewConcurrentLimiter(ConcurrentLimiterConfig{}) | ||
} | ||
|
||
func TestConcurrentLimiter(t *testing.T) { | ||
m := new(sync.Map) | ||
fn := NewConcurrentLimiter(ConcurrentLimiterConfig{ | ||
Keys: []string{ | ||
":ip", | ||
"h:X-Token", | ||
"q:type", | ||
"p:id", | ||
"account", | ||
}, | ||
Lock: func(key string, c *elton.Context) (success bool, unlock func(), err error) { | ||
if key != "192.0.2.1,xyz,1,123,tree.xie" { | ||
err = errors.New("key is invalid") | ||
return | ||
} | ||
_, loaded := m.LoadOrStore(key, 1) | ||
// 如果已存在,则获取销失败 | ||
if loaded { | ||
return | ||
} | ||
success = true | ||
// 删除锁 | ||
unlock = func() { | ||
m.Delete(key) | ||
} | ||
return | ||
}, | ||
}) | ||
|
||
req := httptest.NewRequest("POST", "/users/login?type=1", nil) | ||
resp := httptest.NewRecorder() | ||
c := elton.NewContext(resp, req) | ||
req.Header.Set("X-Token", "xyz") | ||
c.RequestBody = []byte(`{ | ||
"account": "tree.xie" | ||
}`) | ||
c.Params = new(elton.RouteParams) | ||
c.Params.Add("id", "123") | ||
|
||
t.Run("first", func(t *testing.T) { | ||
assert := assert.New(t) | ||
done := false | ||
c.Next = func() error { | ||
done = true | ||
return nil | ||
} | ||
err := fn(c) | ||
assert.Nil(err) | ||
assert.True(done) | ||
}) | ||
|
||
t.Run("too frequently", func(t *testing.T) { | ||
assert := assert.New(t) | ||
done := false | ||
c.Next = func() error { | ||
time.Sleep(100 * time.Millisecond) | ||
done = true | ||
return nil | ||
} | ||
go func() { | ||
time.Sleep(10 * time.Millisecond) | ||
e := fn(c) | ||
assert.Equal(e.Error(), "category=elton-concurrent-limiter, message=submit too frequently") | ||
}() | ||
err := fn(c) | ||
// 登录限制,192.0.2.1,xyz,1,123,tree.xie | ||
assert.Nil(err) | ||
assert.True(done) | ||
}) | ||
|
||
t.Run("lock function return error", func(t *testing.T) { | ||
assert := assert.New(t) | ||
c.Params = new(elton.RouteParams) | ||
err := fn(c) | ||
assert.Equal(err.Error(), "message=key is invalid") | ||
}) | ||
} |
Oops, something went wrong.