MSP-625 remove accounting
This commit is contained in:
1 parent
6a150402d2
commit
b0f871d032
17 files changed
+7
-1079
No files matched your search
@@ -1,41 +0,0 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
"isp-gate-service/accounting/state"
|
||||
"isp-gate-service/service/matcher"
|
||||
"sync"
|
||||
)
|
||||
|
||||
type accountant struct {
|
||||
mx sync.Mutex
|
||||
matcher matcher.Matcher
|
||||
limitStates map[string]state.LimitState
|
||||
version int64
|
||||
}
|
||||
|
||||
func (app *accountant) Accept(method string) bool {
|
||||
patternArray := app.matcher.Match(method)
|
||||
stateStorage := make([]state.LimitState, len(patternArray))
|
||||
for i, pattern := range patternArray {
|
||||
stateStorage[i] = app.limitStates[pattern]
|
||||
}
|
||||
|
||||
app.mx.Lock()
|
||||
resp := state.Update(stateStorage)
|
||||
if resp {
|
||||
app.version++
|
||||
}
|
||||
app.mx.Unlock()
|
||||
return resp
|
||||
}
|
||||
|
||||
func (app *accountant) Snapshot() (map[string]state.Snapshot, int64) {
|
||||
app.mx.Lock()
|
||||
version := app.version
|
||||
snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates))
|
||||
for method, limitState := range app.limitStates {
|
||||
snapshotLimitState[method] = limitState.Export()
|
||||
}
|
||||
app.mx.Unlock()
|
||||
return snapshotLimitState, version
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
"github.com/integration-system/isp-lib/v2/config"
|
||||
"github.com/integration-system/isp-lib/v2/structure"
|
||||
log "github.com/integration-system/isp-log"
|
||||
"isp-gate-service/accounting/state"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/repository"
|
||||
"isp-gate-service/service/matcher"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var worker = &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
|
||||
type (
|
||||
Accounting interface {
|
||||
Accept(string) bool
|
||||
Snapshot() (map[string]state.Snapshot, int64)
|
||||
}
|
||||
|
||||
accountingWorker struct {
|
||||
accountingStorage map[int32]Accounting
|
||||
requestsStoring map[int32]bool
|
||||
}
|
||||
)
|
||||
|
||||
func NewConnectionConsumer(list []structure.AddressConfiguration) bool {
|
||||
accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting
|
||||
worker.init(accountingSetting)
|
||||
return true
|
||||
}
|
||||
|
||||
func ReceiveConfiguration(accountingSetting conf.Accounting) {
|
||||
worker.init(accountingSetting)
|
||||
}
|
||||
|
||||
func AcceptRequest(appId int32, path string) bool {
|
||||
if accouter, ok := worker.accountingStorage[appId]; ok {
|
||||
ok := accouter.Accept(path)
|
||||
if ok && worker.requestsStoring[appId] {
|
||||
storage.TakeRequest(appId, path, time.Now())
|
||||
}
|
||||
return ok
|
||||
} else {
|
||||
if worker.requestsStoring[appId] {
|
||||
storage.TakeRequest(appId, path, time.Now())
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
func Close() {
|
||||
if snapshot != nil {
|
||||
snapshot.Stop()
|
||||
}
|
||||
if storage != nil {
|
||||
storage.Stop()
|
||||
}
|
||||
}
|
||||
|
||||
func (w *accountingWorker) init(accountingSetting conf.Accounting) {
|
||||
Close()
|
||||
|
||||
newAccountingStorage := make(map[int32]Accounting)
|
||||
newRequestsStoringStorage := make(map[int32]bool)
|
||||
|
||||
if accountingSetting.Enable {
|
||||
for _, s := range accountingSetting.Setting {
|
||||
limitStates, patternArray := state.InitLimitState(s.Limits)
|
||||
accounting := w.recoveryAccounting(s.ApplicationId, limitStates, patternArray)
|
||||
|
||||
newAccountingStorage[s.ApplicationId] = accounting
|
||||
newRequestsStoringStorage[s.ApplicationId] = s.EnableStoring
|
||||
}
|
||||
w.requestsStoring = newRequestsStoringStorage
|
||||
w.accountingStorage = newAccountingStorage
|
||||
InitStoringTask(accountingSetting.Storing)
|
||||
InitSnapshotTask(accountingSetting.SnapshotTimeout)
|
||||
} else {
|
||||
w.requestsStoring = newRequestsStoringStorage
|
||||
w.accountingStorage = newAccountingStorage
|
||||
}
|
||||
}
|
||||
|
||||
func (w *accountingWorker) takeSnapshot() []entity.Snapshot {
|
||||
lastStorage := w.accountingStorage
|
||||
|
||||
response := make([]entity.Snapshot, 0, len(lastStorage))
|
||||
for appId, account := range lastStorage {
|
||||
limitState, version := account.Snapshot()
|
||||
response = append(response, entity.Snapshot{
|
||||
AppId: appId,
|
||||
LimitState: limitState,
|
||||
Version: version,
|
||||
})
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func (w *accountingWorker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState, patternArray []string) *accountant {
|
||||
var (
|
||||
version = int64(0)
|
||||
importNotComplete = true
|
||||
)
|
||||
|
||||
dbSnapshot, err := repository.SnapshotRep.GetByApplication(appId)
|
||||
if err != nil {
|
||||
log.Warn(log_code.ErrorSnapshotAccounting, err)
|
||||
}
|
||||
|
||||
if cache, ok := w.accountingStorage[appId]; ok {
|
||||
cashLimitState, cashVersion := cache.Snapshot()
|
||||
|
||||
if dbSnapshot == nil || dbSnapshot.Version < cashVersion {
|
||||
version = cashVersion
|
||||
w.importLimitState(limitStates, cashLimitState)
|
||||
importNotComplete = false
|
||||
}
|
||||
}
|
||||
|
||||
if dbSnapshot != nil && importNotComplete {
|
||||
version = dbSnapshot.Version
|
||||
w.importLimitState(limitStates, dbSnapshot.LimitState)
|
||||
}
|
||||
|
||||
return &accountant{
|
||||
mx: sync.Mutex{},
|
||||
matcher: matcher.NewCacheableMatcher(patternArray),
|
||||
limitStates: limitStates,
|
||||
version: version,
|
||||
}
|
||||
}
|
||||
|
||||
func (w *accountingWorker) importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) {
|
||||
for method, limitState := range limitStates {
|
||||
if oldState, ok := snapshot[method]; ok {
|
||||
limitState.Import(oldState)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,205 +0,0 @@
|
||||
//nolint
|
||||
package accounting
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/repository"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
accountingSetting = conf.Accounting{
|
||||
Enable: true,
|
||||
SnapshotTimeout: "290ms",
|
||||
Setting: []conf.AccountingSetting{
|
||||
{ApplicationId: 1, Limits: []conf.LimitSetting{
|
||||
{Pattern: "mdm-master/group/method", MaxCount: 1, Timeout: "90ms"},
|
||||
{Pattern: "mdm-master/group3/method", MaxCount: 10, Timeout: "10s"},
|
||||
{Pattern: "mdm-master/group3/*", MaxCount: 5, Timeout: "10s"},
|
||||
{Pattern: "mdm-master/group4/method", MaxCount: 2, Timeout: "0s"},
|
||||
{Pattern: "mdm-master/group5/method", MaxCount: 3, Timeout: "10s"},
|
||||
{Pattern: "mdm-master/group6/method", MaxCount: 5, Timeout: "10s"},
|
||||
}},
|
||||
{ApplicationId: 2, Limits: []conf.LimitSetting{
|
||||
{Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"},
|
||||
}},
|
||||
},
|
||||
Storing: conf.StoringSetting{
|
||||
Size: 100,
|
||||
Timeout: "1h",
|
||||
},
|
||||
}
|
||||
|
||||
reqExample = []struct {
|
||||
appId int32
|
||||
path []string
|
||||
}{
|
||||
0: {appId: 1, path: []string{
|
||||
"mdm-master/group/method", "mdm-master/group/method", "mdm-master/group/method",
|
||||
"mdm-master/group/method", "mdm-master/group/method", "mdm-master/group/method",
|
||||
}},
|
||||
|
||||
1: {appId: 2, path: []string{
|
||||
"mdm-master/group3/method", "mdm-master/group/method", "mdm-master/group3/method",
|
||||
"mdm-master/group/method", "mdm-master/group3/method", "mdm-master/group/method",
|
||||
}},
|
||||
|
||||
2: {appId: 1, path: []string{
|
||||
"mdm-master/group3/method", "mdm-master/group3/method", "mdm-master/group3/method",
|
||||
"mdm-master/group3/method", "mdm-master/group3/method", "mdm-master/group3/method",
|
||||
}},
|
||||
3: {appId: 1, path: []string{
|
||||
"mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method",
|
||||
"mdm-master/group4/method", "mdm-master/group4/method", "mdm-master/group4/method",
|
||||
}},
|
||||
4: {appId: 1, path: []string{
|
||||
"mdm-master/group5/method", "mdm-master/group5/method", "mdm-master/group5/method",
|
||||
}},
|
||||
}
|
||||
)
|
||||
|
||||
func TestAccounting(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
snapshotRep := newSnapshotRepository(false)
|
||||
repository.SnapshotRep = snapshotRep
|
||||
worker = &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
worker.init(accountingSetting)
|
||||
|
||||
req := reqExample[4]
|
||||
for _, path := range req.path {
|
||||
a.True(AcceptRequest(req.appId, path))
|
||||
}
|
||||
|
||||
expected := true
|
||||
req = reqExample[0]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, AcceptRequest(req.appId, path))
|
||||
expected = !expected
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
|
||||
//expected == true
|
||||
req = reqExample[1]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, AcceptRequest(req.appId, path))
|
||||
expected = !expected
|
||||
}
|
||||
|
||||
req = reqExample[2]
|
||||
expectedArray := []bool{true, true, true, true, true, false}
|
||||
for key, path := range req.path {
|
||||
a.Equal(expectedArray[key], AcceptRequest(req.appId, path))
|
||||
}
|
||||
|
||||
//expected == true
|
||||
req = reqExample[3]
|
||||
for _, path := range req.path {
|
||||
a.Equal(expected, AcceptRequest(req.appId, path))
|
||||
}
|
||||
|
||||
worker.init(accountingSetting)
|
||||
|
||||
req = reqExample[4]
|
||||
for _, path := range req.path {
|
||||
a.False(AcceptRequest(req.appId, path))
|
||||
}
|
||||
}
|
||||
|
||||
func TestWorker_recoveryAccounting(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
snapshotRep := newSnapshotRepository(true)
|
||||
repository.SnapshotRep = snapshotRep
|
||||
|
||||
worker = &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
secondWorker := &accountingWorker{
|
||||
accountingStorage: make(map[int32]Accounting),
|
||||
requestsStoring: make(map[int32]bool),
|
||||
}
|
||||
|
||||
worker.init(accountingSetting)
|
||||
secondWorker.init(accountingSetting)
|
||||
|
||||
appId := int32(1)
|
||||
request := "1_3_5"
|
||||
for range request {
|
||||
a.True(AcceptRequest(appId, "mdm-master/group6/method"))
|
||||
}
|
||||
a.False(AcceptRequest(appId, "mdm-master/group6/method"))
|
||||
|
||||
time.Sleep(time.Millisecond * 300)
|
||||
a.True(snapshotRep.Wait())
|
||||
snapshot, err := repository.SnapshotRep.GetByApplication(appId)
|
||||
a.NoError(err)
|
||||
a.NotNil(snapshot)
|
||||
a.Equal(len(request), int(snapshot.Version))
|
||||
|
||||
Close()
|
||||
worker = secondWorker
|
||||
worker.init(accountingSetting)
|
||||
a.False(AcceptRequest(appId, "mdm-master/group6/method"))
|
||||
}
|
||||
|
||||
type snapshotRepository struct {
|
||||
enableWaitGroup bool
|
||||
wg sync.WaitGroup
|
||||
mx sync.Mutex
|
||||
cache map[int32]entity.Snapshot
|
||||
}
|
||||
|
||||
func newSnapshotRepository(enableWaitGroup bool) *snapshotRepository {
|
||||
return &snapshotRepository{
|
||||
enableWaitGroup: enableWaitGroup,
|
||||
wg: sync.WaitGroup{},
|
||||
cache: make(map[int32]entity.Snapshot),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *snapshotRepository) Wait() bool {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
r.wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
case <-time.After(time.Second):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (r *snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) {
|
||||
r.mx.Lock()
|
||||
defer r.mx.Unlock()
|
||||
|
||||
if snapshot, ok := r.cache[appId]; ok {
|
||||
return &snapshot, nil
|
||||
} else {
|
||||
return nil, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r *snapshotRepository) Update(list []entity.Snapshot) error {
|
||||
r.mx.Lock()
|
||||
defer r.mx.Unlock()
|
||||
|
||||
if r.enableWaitGroup {
|
||||
r.wg.Add(1)
|
||||
defer r.wg.Done()
|
||||
}
|
||||
|
||||
for _, s := range list {
|
||||
r.cache[s.AppId] = s
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,84 +0,0 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/repository"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var snapshot *snapshotTask
|
||||
|
||||
type snapshotTask struct {
|
||||
mx sync.Mutex
|
||||
wg sync.WaitGroup
|
||||
|
||||
process bool
|
||||
timeout <-chan time.Time
|
||||
close chan bool
|
||||
}
|
||||
|
||||
func InitSnapshotTask(snapshotTimeout string) {
|
||||
timeout, err := time.ParseDuration(snapshotTimeout)
|
||||
if err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
snapshot = newSnapshotTask(timeout)
|
||||
}
|
||||
|
||||
func (t *snapshotTask) Stop() {
|
||||
t.mx.Lock()
|
||||
if t.process {
|
||||
snapshotList := worker.takeSnapshot()
|
||||
if len(snapshotList) != 0 {
|
||||
defer func() {
|
||||
t.wg.Add(1)
|
||||
t.unload(snapshotList)
|
||||
t.wg.Wait()
|
||||
}()
|
||||
}
|
||||
t.process = false
|
||||
t.close <- true
|
||||
}
|
||||
t.mx.Unlock()
|
||||
}
|
||||
|
||||
func (t *snapshotTask) run(timeout time.Duration) {
|
||||
defer t.wg.Done()
|
||||
t.timeout = time.After(timeout)
|
||||
for {
|
||||
select {
|
||||
case <-t.close:
|
||||
return
|
||||
case <-t.timeout:
|
||||
list := worker.takeSnapshot()
|
||||
if len(list) > 0 {
|
||||
t.wg.Add(1)
|
||||
go t.unload(list)
|
||||
}
|
||||
t.timeout = time.After(timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *snapshotTask) unload(list []entity.Snapshot) {
|
||||
if err := repository.SnapshotRep.Update(list); err != nil {
|
||||
log.Error(log_code.ErrorSnapshotAccounting, err)
|
||||
}
|
||||
t.wg.Done()
|
||||
}
|
||||
|
||||
func newSnapshotTask(timeout time.Duration) *snapshotTask {
|
||||
task := &snapshotTask{
|
||||
process: true,
|
||||
timeout: make(chan time.Time),
|
||||
close: make(chan bool),
|
||||
}
|
||||
task.wg.Add(1)
|
||||
go task.run(timeout)
|
||||
return task
|
||||
}
|
||||
@@ -1,69 +0,0 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"isp-gate-service/conf"
|
||||
"time"
|
||||
)
|
||||
|
||||
type (
|
||||
LimitState interface {
|
||||
Import(Snapshot)
|
||||
Export() Snapshot
|
||||
check() (bool, int, time.Time)
|
||||
update(int, time.Time)
|
||||
}
|
||||
|
||||
Snapshot struct {
|
||||
Timeout time.Duration
|
||||
Datetime []time.Time
|
||||
Pattern string
|
||||
Pointer int
|
||||
}
|
||||
|
||||
updateRequest struct {
|
||||
pointer int
|
||||
requestTime time.Time
|
||||
}
|
||||
)
|
||||
|
||||
func InitLimitState(limits []conf.LimitSetting) (map[string]LimitState, []string) {
|
||||
limitStates := make(map[string]LimitState)
|
||||
patternArray := make([]string, len(limits))
|
||||
|
||||
for i, limit := range limits {
|
||||
timeout, err := time.ParseDuration(limit.Timeout)
|
||||
if err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
if timeout == 0 && limit.MaxCount != 0 {
|
||||
limit.MaxCount = 1
|
||||
}
|
||||
patternArray[i] = limit.Pattern
|
||||
limitStates[limit.Pattern] = &limiter{
|
||||
timeout: timeout,
|
||||
datetime: make([]time.Time, limit.MaxCount),
|
||||
pattern: limit.Pattern,
|
||||
pointer: -1,
|
||||
}
|
||||
}
|
||||
return limitStates, patternArray
|
||||
}
|
||||
|
||||
func Update(states []LimitState) bool {
|
||||
update := make([]updateRequest, len(states))
|
||||
for i, st := range states {
|
||||
if ok, point, requestTime := st.check(); ok {
|
||||
update[i] = updateRequest{pointer: point, requestTime: requestTime}
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
}
|
||||
for i, st := range states {
|
||||
u := update[i]
|
||||
st.update(u.pointer, u.requestTime)
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
type limiter struct {
|
||||
timeout time.Duration
|
||||
datetime []time.Time
|
||||
pattern string
|
||||
pointer int
|
||||
}
|
||||
|
||||
func (lim *limiter) Export() Snapshot {
|
||||
ls := *lim
|
||||
return Snapshot{
|
||||
Timeout: ls.timeout,
|
||||
Datetime: ls.datetime,
|
||||
Pattern: ls.pattern,
|
||||
Pointer: ls.pointer,
|
||||
}
|
||||
}
|
||||
|
||||
func (lim *limiter) Import(oldState Snapshot) {
|
||||
oldLim := limiter{
|
||||
timeout: oldState.Timeout,
|
||||
datetime: oldState.Datetime,
|
||||
pattern: oldState.Pattern,
|
||||
pointer: oldState.Pointer,
|
||||
}
|
||||
|
||||
lenOldDatetime := len(oldLim.datetime)
|
||||
lenNewDatetime := len(lim.datetime)
|
||||
|
||||
switch {
|
||||
case lenOldDatetime == lenNewDatetime:
|
||||
lim.datetime = oldLim.datetime
|
||||
lim.pointer = oldLim.pointer
|
||||
|
||||
case lenOldDatetime < lenNewDatetime:
|
||||
oldPointer := oldLim.pointer
|
||||
for i := range lim.datetime {
|
||||
oldLim.pointer++
|
||||
if oldLim.pointer >= len(oldLim.datetime) {
|
||||
oldLim.pointer = 0
|
||||
}
|
||||
|
||||
lim.datetime[i] = oldLim.datetime[oldLim.pointer]
|
||||
|
||||
if oldPointer == oldLim.pointer {
|
||||
lim.pointer = i
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
case lenOldDatetime > lenNewDatetime:
|
||||
for i := range lim.datetime {
|
||||
oldLim.pointer++
|
||||
if oldLim.pointer >= len(oldLim.datetime) {
|
||||
oldLim.pointer = 0
|
||||
}
|
||||
lim.datetime[i] = oldLim.datetime[oldLim.pointer]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (lim *limiter) check() (bool, int, time.Time) {
|
||||
if len(lim.datetime) == 0 {
|
||||
return false, 0, time.Time{}
|
||||
}
|
||||
if lim.timeout == 0 {
|
||||
return true, 0, time.Now()
|
||||
}
|
||||
|
||||
pointer := lim.pointer + 1
|
||||
if pointer >= len(lim.datetime) {
|
||||
pointer = 0
|
||||
}
|
||||
date := lim.datetime[pointer]
|
||||
requestTime := time.Now()
|
||||
account := requestTime.Sub(date) > lim.timeout
|
||||
|
||||
return account, pointer, requestTime
|
||||
}
|
||||
|
||||
func (lim *limiter) update(point int, requestTime time.Time) {
|
||||
lim.pointer = point
|
||||
lim.datetime[point] = requestTime
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
package state
|
||||
|
||||
import (
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLimiter(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
newLimiter := func(count int) *limiter {
|
||||
return &limiter{timeout: 5 * time.Second, pattern: "example", pointer: -1, datetime: make([]time.Time, count)}
|
||||
}
|
||||
|
||||
store12 := newLimiter(12)
|
||||
store10 := newLimiter(10)
|
||||
store7 := newLimiter(7)
|
||||
store5 := newLimiter(5)
|
||||
|
||||
for i := 0; i < 7; i++ {
|
||||
expectedTrue, pointer, reqTime := store10.check()
|
||||
a.True(expectedTrue)
|
||||
store10.update(pointer, reqTime)
|
||||
|
||||
expectedTrue, pointer, reqTime = store7.check()
|
||||
a.True(expectedTrue)
|
||||
store7.update(pointer, reqTime)
|
||||
}
|
||||
|
||||
expectedFalse, _, _ := store7.check()
|
||||
a.False(expectedFalse)
|
||||
|
||||
store12.Import(store7.Export())
|
||||
store5.Import(store10.Export())
|
||||
|
||||
a.Equal(store5.datetime[0], store10.datetime[store10.pointer+1])
|
||||
a.Equal(store12.datetime[0], store7.datetime[0])
|
||||
a.Equal(store12.datetime[store7.pointer], store7.datetime[store7.pointer])
|
||||
a.Equal(store12.datetime[store7.pointer+1], time.Time{})
|
||||
|
||||
expectedTrue, _, _ := store12.check()
|
||||
a.True(expectedTrue)
|
||||
|
||||
for i := 0; i < 3; i++ {
|
||||
expectedTrue, pointer, reqTime := store5.check()
|
||||
a.True(expectedTrue)
|
||||
store5.update(pointer, reqTime)
|
||||
}
|
||||
expectedFalse, _, _ = store5.check()
|
||||
a.False(expectedFalse)
|
||||
}
|
||||
@@ -1,131 +0,0 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
log "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/log_code"
|
||||
"isp-gate-service/repository"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
var storage *storingTask
|
||||
|
||||
type storingTask struct {
|
||||
buffer []entity.Request
|
||||
counter int
|
||||
|
||||
chanTimeout <-chan time.Time
|
||||
chanCounter chan []entity.Request
|
||||
chanClose chan bool
|
||||
|
||||
mx sync.Mutex
|
||||
wg sync.WaitGroup
|
||||
|
||||
process bool
|
||||
}
|
||||
|
||||
func InitStoringTask(setting conf.StoringSetting) {
|
||||
timeout, err := time.ParseDuration(setting.Timeout)
|
||||
if err != nil {
|
||||
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
|
||||
}
|
||||
|
||||
storage = newStoringTask(timeout, setting.Size)
|
||||
}
|
||||
|
||||
func (t *storingTask) TakeRequest(appId int32, method string, date time.Time) {
|
||||
t.mx.Lock()
|
||||
if !t.process {
|
||||
t.mx.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
t.buffer[t.counter] = entity.Request{
|
||||
AppId: appId,
|
||||
Method: method,
|
||||
CreatedAt: date,
|
||||
}
|
||||
|
||||
t.counter++
|
||||
if t.counter == len(t.buffer) {
|
||||
t.chanCounter <- t.buffer
|
||||
t.clearBuffer()
|
||||
}
|
||||
|
||||
t.mx.Unlock()
|
||||
}
|
||||
|
||||
func (t *storingTask) Stop() {
|
||||
t.mx.Lock()
|
||||
if t.process {
|
||||
if t.counter != 0 {
|
||||
buffer := t.clearBuffer()
|
||||
defer func() {
|
||||
t.wg.Add(1)
|
||||
t.unload(buffer)
|
||||
t.wg.Wait()
|
||||
}()
|
||||
}
|
||||
t.chanClose <- true
|
||||
t.process = false
|
||||
}
|
||||
t.mx.Unlock()
|
||||
}
|
||||
|
||||
func (t *storingTask) run(timeout time.Duration) {
|
||||
defer t.wg.Done()
|
||||
t.chanTimeout = time.After(timeout)
|
||||
for {
|
||||
select {
|
||||
case <-t.chanClose:
|
||||
return
|
||||
case cache := <-t.chanCounter:
|
||||
t.wg.Add(1)
|
||||
go t.unload(cache)
|
||||
t.chanTimeout = time.After(timeout)
|
||||
case <-t.chanTimeout:
|
||||
t.mx.Lock()
|
||||
if t.counter != 0 {
|
||||
buffer := t.clearBuffer()
|
||||
t.wg.Add(1)
|
||||
go t.unload(buffer)
|
||||
}
|
||||
t.mx.Unlock()
|
||||
t.chanTimeout = time.After(timeout)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (t *storingTask) unload(cache []entity.Request) {
|
||||
if err := repository.RequestsRep.Insert(cache); err != nil {
|
||||
log.Error(log_code.ErrorUnloadAccounting, err)
|
||||
}
|
||||
t.wg.Done()
|
||||
}
|
||||
|
||||
func (t *storingTask) clearBuffer() []entity.Request {
|
||||
oldBuffer := t.buffer[:t.counter]
|
||||
oldLen := len(t.buffer)
|
||||
t.counter = 0
|
||||
t.buffer = make([]entity.Request, oldLen)
|
||||
return oldBuffer
|
||||
}
|
||||
|
||||
func newStoringTask(timeout time.Duration, bufSize int) *storingTask {
|
||||
task := &storingTask{
|
||||
mx: sync.Mutex{},
|
||||
counter: 0,
|
||||
buffer: make([]entity.Request, bufSize),
|
||||
process: true,
|
||||
chanTimeout: make(chan time.Time),
|
||||
chanCounter: make(chan []entity.Request),
|
||||
chanClose: make(chan bool),
|
||||
}
|
||||
task.wg.Add(1)
|
||||
go task.run(timeout)
|
||||
|
||||
return task
|
||||
}
|
||||
@@ -1,112 +0,0 @@
|
||||
package accounting
|
||||
|
||||
import (
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/entity"
|
||||
"isp-gate-service/repository"
|
||||
)
|
||||
|
||||
var (
|
||||
timeoutSetting = conf.StoringSetting{
|
||||
Size: 3,
|
||||
Timeout: "30ms",
|
||||
}
|
||||
|
||||
bufferSetting = conf.StoringSetting{
|
||||
Size: 3,
|
||||
Timeout: "2s",
|
||||
}
|
||||
|
||||
unloadSetting = conf.StoringSetting{
|
||||
Size: 3,
|
||||
Timeout: "100ms",
|
||||
}
|
||||
)
|
||||
|
||||
func initStoring(setting conf.StoringSetting) *requestsRepository {
|
||||
rep := &requestsRepository{cache: make([]entity.Request, 0), wg: &sync.WaitGroup{}}
|
||||
repository.RequestsRep = rep
|
||||
InitStoringTask(setting)
|
||||
return rep
|
||||
}
|
||||
|
||||
func wait(wg *sync.WaitGroup) bool {
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
return true
|
||||
case <-time.After(time.Second):
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func TestStoringTask_Stop(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep := initStoring(bufferSetting)
|
||||
|
||||
rep.wg.Add(2)
|
||||
for i, j := range []string{"Stop_1", "Stop_2", "Stop_3", "Stop_4", "Stop_5"} {
|
||||
storage.TakeRequest(int32(i), j, time.Now())
|
||||
}
|
||||
storage.Stop()
|
||||
a.Len(rep.cache, 5)
|
||||
}
|
||||
|
||||
func TestStoringTask_Buffer(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep := initStoring(bufferSetting)
|
||||
|
||||
rep.wg.Add(1)
|
||||
for i, j := range []string{"Buffer_1", "Buffer_2", "Buffer_3", "Buffer_4", "Buffer_5"} {
|
||||
storage.TakeRequest(int32(i), j, time.Now())
|
||||
}
|
||||
a.True(wait(rep.wg))
|
||||
a.Len(rep.cache, 3)
|
||||
}
|
||||
|
||||
func TestStoringTask_Timeout(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep := initStoring(timeoutSetting)
|
||||
|
||||
rep.wg.Add(1)
|
||||
for i, j := range []string{"Timeout_1", "Timeout_2"} {
|
||||
storage.TakeRequest(int32(i), j, time.Now())
|
||||
}
|
||||
a.True(wait(rep.wg))
|
||||
a.Len(rep.cache, 2)
|
||||
}
|
||||
|
||||
func TestStoringTask_Unload(t *testing.T) {
|
||||
a := assert.New(t)
|
||||
rep := initStoring(unloadSetting)
|
||||
|
||||
rep.wg.Add(2)
|
||||
for i, j := range []string{"Unload_1", "Unload_2", "Unload_3", "Unload_4", "Unload_5"} {
|
||||
storage.TakeRequest(int32(i), j, time.Now())
|
||||
}
|
||||
a.True(wait(rep.wg))
|
||||
a.Len(rep.cache, 5)
|
||||
}
|
||||
|
||||
type requestsRepository struct {
|
||||
cache []entity.Request
|
||||
mx sync.Mutex
|
||||
wg *sync.WaitGroup
|
||||
}
|
||||
|
||||
func (r *requestsRepository) Insert(model []entity.Request) error {
|
||||
r.mx.Lock()
|
||||
r.cache = append(r.cache, model...)
|
||||
r.mx.Unlock()
|
||||
r.wg.Done()
|
||||
return nil
|
||||
}
|
||||
+6
-32
@@ -20,14 +20,12 @@ const (
|
||||
|
||||
type (
|
||||
RemoteConfig struct {
|
||||
Database structure.DBConfiguration `schema:"Настройка подключения к базе данных"`
|
||||
TokensSetting TokensSetting `schema:"Настройка секретов"`
|
||||
HttpSetting HttpSetting `schema:"Настройка сервера"`
|
||||
GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"`
|
||||
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
|
||||
JournalSetting Journal `schema:"Настройка журалирования"`
|
||||
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
|
||||
AccountingSetting Accounting `schema:"Настройка учета запросов"`
|
||||
TokensSetting TokensSetting `schema:"Настройка секретов"`
|
||||
HttpSetting HttpSetting `schema:"Настройка сервера"`
|
||||
GrpcSetting GrpcSetting `schema:"Настройка grpc соединения"`
|
||||
Metrics structure.MetricConfiguration `schema:"Настройка метрик"`
|
||||
JournalSetting Journal `schema:"Настройка журалирования"`
|
||||
Redis structure.RedisConfiguration `schema:"Настройка Redis" valid:"required~Required"`
|
||||
}
|
||||
|
||||
Journal struct {
|
||||
@@ -49,30 +47,6 @@ type (
|
||||
UserSecret string `schema:"Секрет для проверки токена пользователя"`
|
||||
}
|
||||
|
||||
Accounting struct {
|
||||
Enable bool `schema:"Учет запросов,включает/отключает учет запросов"`
|
||||
SnapshotTimeout string `schema:"Частота выгрузки ограничений для приложений" valid:"required~Required"`
|
||||
Setting []AccountingSetting `schema:"Настройка учета для приложений"`
|
||||
Storing StoringSetting `schema:"Настройка хранения всех запросов"`
|
||||
}
|
||||
|
||||
AccountingSetting struct {
|
||||
ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"`
|
||||
EnableStoring bool `schema:"Хранение запросов,если включено, каждый факт обработки запроса будет фиксироваться в БД"`
|
||||
Limits []LimitSetting `schema:"Настройка ограничений на запросы"`
|
||||
}
|
||||
|
||||
LimitSetting struct {
|
||||
Pattern string `valid:"required~Required" schema:"Шаблон пути,указывается путь для которого будут применяется ограничения; поддерживается '/*' для неполного совпадения"`
|
||||
MaxCount int `schema:"Количество запросов"`
|
||||
Timeout string `schema:"Время жизни одного запроса"`
|
||||
}
|
||||
|
||||
StoringSetting struct {
|
||||
Size int `schema:"Размер буфера,размер буфера,при достижении которого данные сбрасываются в БД" valid:"required,range(1|1000000)"`
|
||||
Timeout string `schema:"Частота выгрузки всех учтенных запросов,периодичность сброса данных в БД" valid:"required~Required"`
|
||||
}
|
||||
|
||||
HttpSetting struct {
|
||||
MaxRequestBodySizeBytes int64 `schema:"Максимальный размер тела запроса,в байтайх, по умолчанию: 512 MB"`
|
||||
}
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
package entity
|
||||
|
||||
import (
|
||||
"isp-gate-service/accounting/state"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Snapshot struct {
|
||||
TableName string `sql:"?db_schema.snapshot" json:"-"`
|
||||
AppId int32 `sql:",pk"`
|
||||
LimitState map[string]state.Snapshot
|
||||
Version int64
|
||||
}
|
||||
|
||||
type Request struct {
|
||||
TableName string `sql:"?db_schema.requests" json:"-"`
|
||||
Id int `sql:",pk"`
|
||||
AppId int32
|
||||
Method string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
@@ -16,7 +16,6 @@ require (
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/rcrowley/go-metrics v0.0.0-20200313005456-10cdbea86bc0
|
||||
github.com/spf13/cast v1.4.1
|
||||
github.com/stretchr/testify v1.7.1
|
||||
github.com/valyala/fasthttp v1.28.0
|
||||
golang.org/x/net v0.0.0-20220421235706-1d1ef9303861
|
||||
google.golang.org/grpc v1.46.0
|
||||
|
||||
@@ -10,7 +10,6 @@ import (
|
||||
"github.com/pkg/errors"
|
||||
"github.com/valyala/fasthttp"
|
||||
"google.golang.org/grpc/codes"
|
||||
"isp-gate-service/accounting"
|
||||
"isp-gate-service/authenticate"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/domain"
|
||||
@@ -25,8 +24,6 @@ const (
|
||||
execution = 1e6
|
||||
)
|
||||
|
||||
var errAccounting = errors.New("accounting error")
|
||||
|
||||
type Handler struct {
|
||||
logger log.Logger
|
||||
}
|
||||
@@ -110,12 +107,6 @@ func (h Handler) authenticateAccountingProxy(ctx *fasthttp.RequestCtx) (int32, i
|
||||
utils.WriteError(ctx, message, status, details)
|
||||
return appId, adminId, path, domain.Create().SetError(err)
|
||||
}
|
||||
|
||||
if !accounting.AcceptRequest(appId, path) {
|
||||
err := errAccounting
|
||||
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
|
||||
return appId, adminId, path, domain.Create().SetError(err)
|
||||
}
|
||||
}
|
||||
|
||||
return appId, adminId, path, p.ProxyRequest(ctx, path)
|
||||
|
||||
@@ -15,7 +15,6 @@ import (
|
||||
logrus "github.com/integration-system/isp-log"
|
||||
"github.com/integration-system/isp-log/stdcodes"
|
||||
"github.com/pkg/errors"
|
||||
"isp-gate-service/accounting"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/proxy"
|
||||
"isp-gate-service/redis"
|
||||
@@ -51,7 +50,7 @@ func main() {
|
||||
for module, consumer := range requiredModules {
|
||||
bs.RequireModule(module, consumer, false)
|
||||
}
|
||||
bs.RequireModule(cfg.ModuleName, accounting.NewConnectionConsumer, false).
|
||||
bs.
|
||||
OnShutdown(onShutdown).
|
||||
OnRemoteConfigReceive(onRemoteConfigReceive).
|
||||
Run()
|
||||
@@ -66,7 +65,6 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
|
||||
matcher.JournalMethods = matcher.NewAtLeastOneMatcher(remoteConfig.JournalSetting.MethodsPatterns)
|
||||
|
||||
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
|
||||
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
|
||||
|
||||
metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics)
|
||||
metric.InitHttpServer(remoteConfig.Metrics)
|
||||
@@ -98,7 +96,6 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
|
||||
|
||||
func onShutdown(_ context.Context, _ os.Signal) {
|
||||
server.Http.Close()
|
||||
accounting.Close()
|
||||
proxy.Close()
|
||||
_ = redis.Client.Close()
|
||||
if logger != nil {
|
||||
|
||||
@@ -14,7 +14,4 @@ var (
|
||||
database.WithInitializingErrorHandler(func(err *database.ErrorEvent) {
|
||||
log.Error(log_code.ErrorClientDatabase, err)
|
||||
}))
|
||||
|
||||
SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient}
|
||||
RequestsRep RequestsRepository = requestsRepository{rxClient: DbClient}
|
||||
)
|
||||
@@ -1,30 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"github.com/go-pg/pg/v9/orm"
|
||||
"github.com/integration-system/isp-lib/v2/database"
|
||||
"isp-gate-service/entity"
|
||||
)
|
||||
|
||||
type (
|
||||
RequestsRepository interface {
|
||||
Insert([]entity.Request) error
|
||||
}
|
||||
|
||||
requestsRepository struct {
|
||||
DB orm.DB
|
||||
rxClient *database.RxDbClient
|
||||
}
|
||||
)
|
||||
|
||||
func (r requestsRepository) Insert(model []entity.Request) error {
|
||||
_, err := r.getDb().Model(&model).Insert()
|
||||
return err
|
||||
}
|
||||
|
||||
func (r requestsRepository) getDb() orm.DB {
|
||||
if r.DB != nil {
|
||||
return r.DB
|
||||
}
|
||||
return r.rxClient.Unsafe()
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"github.com/go-pg/pg/v9"
|
||||
"github.com/integration-system/isp-lib/v2/database"
|
||||
"isp-gate-service/entity"
|
||||
|
||||
"github.com/go-pg/pg/v9/orm"
|
||||
)
|
||||
|
||||
type (
|
||||
SnapshotRepository interface {
|
||||
GetByApplication(int32) (*entity.Snapshot, error)
|
||||
Update([]entity.Snapshot) error
|
||||
}
|
||||
|
||||
snapshotRepository struct {
|
||||
DB orm.DB
|
||||
rxClient *database.RxDbClient
|
||||
}
|
||||
)
|
||||
|
||||
func (r snapshotRepository) Update(list []entity.Snapshot) error {
|
||||
_, err := r.getDb().Model(&list).OnConflict("(app_id) DO UPDATE").
|
||||
Set("version = EXCLUDED.version").
|
||||
Set("app_id = EXCLUDED.app_id").
|
||||
Set("limit_state = EXCLUDED.limit_state").
|
||||
Where("snapshot.version < EXCLUDED.version").
|
||||
Insert()
|
||||
return err
|
||||
}
|
||||
|
||||
func (r snapshotRepository) GetByApplication(appId int32) (*entity.Snapshot, error) {
|
||||
model := new(entity.Snapshot)
|
||||
if err := r.getDb().Model(model).Where("app_id = ?", appId).Select(); err != nil {
|
||||
if err == pg.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
} else {
|
||||
return model, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (r snapshotRepository) getDb() orm.DB {
|
||||
if r.DB != nil {
|
||||
return r.DB
|
||||
}
|
||||
return r.rxClient.Unsafe()
|
||||
}
|
||||
Reference in new issue
Block a user