refactoring

This commit is contained in:
DeniskaRediska committed 2019-11-27 15:28:36 +03:00
1 parent 1ffe9e4a62
commit 909a26eace
5 files changed
+90 -101

No files matched your search

+69 -79
View File
@@ -15,8 +15,7 @@ import (
"time"
)
var Worker = &worker{
process: false,
var worker = &accountingWorker{
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
@@ -27,33 +26,56 @@ type (
Snapshot() (map[string]state.Snapshot, int64)
}
worker struct {
mx sync.RWMutex
process bool
accountingWorker struct {
accountingStorage map[int32]Accounting
requestsStoring map[int32]bool
}
)
func (w *worker) Consumer(list []structure.AddressConfiguration) bool {
func NewConnectionConsumer(list []structure.AddressConfiguration) bool {
accountingSetting := config.GetRemote().(*conf.RemoteConfig).AccountingSetting
w.ReceiveConfiguration(accountingSetting)
worker.init(accountingSetting)
return true
}
func (w *worker) ReceiveConfiguration(conf conf.Accounting) {
w.Close()
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() {
snapshot.Stop()
if storage != nil {
storage.Stop()
}
}
func (w *accountingWorker) init(accountingSetting conf.Accounting) {
Close()
newAccountingStorage := make(map[int32]Accounting)
newRequestsStoring := make(map[int32]bool)
process := false
if conf.Enable {
if err := InitStoringTask(conf.Storing); err != nil {
if accountingSetting.Enable {
if err := InitStoringTask(accountingSetting.Storing); err != nil {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
for _, s := range conf.Setting {
for _, s := range accountingSetting.Setting {
newRequestsStoring[s.ApplicationId] = s.EnableStoring
limitStates, patternArray, err := state.InitLimitState(s.Limits)
@@ -61,58 +83,22 @@ func (w *worker) ReceiveConfiguration(conf conf.Accounting) {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
}
version := w.recoveryAccounting(s.ApplicationId, limitStates)
newAccountingStorage[s.ApplicationId] = &accountant{
version: version,
matcher: matcher.NewCacheableMatcher(patternArray),
limitStates: limitStates,
mx: sync.Mutex{},
}
accounting := w.recoveryAccounting(s.ApplicationId, limitStates, patternArray)
newAccountingStorage[s.ApplicationId] = accounting
}
if snapshotTimeout, err := time.ParseDuration(conf.SnapshotTimeout); err != nil {
if snapshotTimeout, err := time.ParseDuration(accountingSetting.SnapshotTimeout); err != nil {
log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err)
} else {
go snapshot.Start(snapshotTimeout)
}
process = true
}
w.mx.Lock()
w.requestsStoring = newRequestsStoring
w.accountingStorage = newAccountingStorage
w.process = process
w.mx.Unlock()
}
func (w *worker) AcceptRequest(appId int32, path string) bool {
w.mx.RLock()
defer w.mx.RUnlock()
if accouter, ok := w.accountingStorage[appId]; !ok {
if w.requestsStoring[appId] {
storage.TakeRequest(appId, path, time.Now())
}
return true
} else {
ok := accouter.Accept(path)
if ok && w.requestsStoring[appId] {
storage.TakeRequest(appId, path, time.Now())
}
return ok
}
}
func (w *worker) Close() {
snapshot.Stop()
if storage != nil {
storage.Stop()
}
}
func (w *worker) takeSnapshot() []entity.Snapshot {
w.mx.RLock()
func (w *accountingWorker) takeSnapshot() []entity.Snapshot {
response := make([]entity.Snapshot, 0, len(w.accountingStorage))
for appId, account := range w.accountingStorage {
@@ -124,40 +110,44 @@ func (w *worker) takeSnapshot() []entity.Snapshot {
Version: version,
})
}
w.mx.RUnlock()
return response
}
func (w *worker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState) int64 {
version := int64(0)
w.mx.RLock()
if w.process {
if acc, ok := w.accountingStorage[appId]; ok {
cashLimitState, cashVersion := acc.Snapshot()
dbSnapshot, err := model.SnapshotRep.GetByApplication(appId)
if err != nil {
log.Warn(log_code.ErrorSnapshotAccounting, err)
}
func (w *accountingWorker) recoveryAccounting(appId int32, limitStates map[string]state.LimitState, patternArray []string) *accountant {
var (
version = int64(0)
importNotComplete = true
)
if dbSnapshot != nil && dbSnapshot.Version > cashVersion {
w.importLimitState(limitStates, dbSnapshot.LimitState)
} else {
w.importLimitState(limitStates, cashLimitState)
}
}
} else {
if snapshot, err := model.SnapshotRep.GetByApplication(appId); err != nil {
log.Warn(log_code.ErrorSnapshotAccounting, err)
} else if snapshot != nil {
version = snapshot.Version
w.importLimitState(limitStates, snapshot.LimitState)
dbSnapshot, err := model.SnapshotRep.GetByApplication(appId)
if err != nil {
log.Warn(log_code.ErrorSnapshotAccounting, err)
}
if cash, ok := w.accountingStorage[appId]; ok {
cashLimitState, cashVersion := cash.Snapshot()
if dbSnapshot != nil && dbSnapshot.Version < cashVersion {
version = cashVersion
w.importLimitState(limitStates, cashLimitState)
importNotComplete = false
}
}
w.mx.RUnlock()
return version
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 *worker) importLimitState(limitStates map[string]state.LimitState, snapshot map[string]state.Snapshot) {
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)
+16 -17
View File
@@ -64,17 +64,17 @@ var (
func TestAccounting(t *testing.T) {
a := assert.New(t)
model.SnapshotRep = newSnapshotRepository(false)
Worker.ReceiveConfiguration(accountingSetting)
ReceiveConfiguration(accountingSetting)
req := reqExample[4]
for _, path := range req.path {
a.True(Worker.AcceptRequest(req.appId, path))
a.True(AcceptRequest(req.appId, path))
}
expected := true
req = reqExample[0]
for _, path := range req.path {
a.Equal(expected, Worker.AcceptRequest(req.appId, path))
a.Equal(expected, AcceptRequest(req.appId, path))
expected = !expected
time.Sleep(50 * time.Millisecond)
}
@@ -82,27 +82,27 @@ func TestAccounting(t *testing.T) {
//expected == true
req = reqExample[1]
for _, path := range req.path {
a.Equal(expected, Worker.AcceptRequest(req.appId, 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], Worker.AcceptRequest(req.appId, path))
a.Equal(expectedArray[key], AcceptRequest(req.appId, path))
}
//expected == true
req = reqExample[3]
for _, path := range req.path {
a.Equal(expected, Worker.AcceptRequest(req.appId, path))
a.Equal(expected, AcceptRequest(req.appId, path))
}
Worker.ReceiveConfiguration(accountingSetting)
ReceiveConfiguration(accountingSetting)
req = reqExample[4]
for _, path := range req.path {
a.False(Worker.AcceptRequest(req.appId, path))
a.False(AcceptRequest(req.appId, path))
}
}
@@ -111,20 +111,19 @@ func TestWorker_recoveryAccounting(t *testing.T) {
snapshotRep := newSnapshotRepository(true)
model.SnapshotRep = snapshotRep
oldWorker := &worker{
process: false,
oldWorker := &accountingWorker{
accountingStorage: make(map[int32]Accounting),
requestsStoring: make(map[int32]bool),
}
Worker.ReceiveConfiguration(accountingSetting)
oldWorker.ReceiveConfiguration(accountingSetting)
worker.init(accountingSetting)
oldWorker.init(accountingSetting)
request := "1_3_5"
for range request {
a.True(Worker.AcceptRequest(1, "mdm-master/group6/method"))
a.True(AcceptRequest(1, "mdm-master/group6/method"))
}
a.False(Worker.AcceptRequest(1, "mdm-master/group6/method"))
a.False(AcceptRequest(1, "mdm-master/group6/method"))
time.Sleep(time.Millisecond * 300)
a.True(snapshotRep.Wait())
@@ -133,9 +132,9 @@ func TestWorker_recoveryAccounting(t *testing.T) {
a.NotNil(snapshot)
a.Equal(len(request), int(snapshot.Version))
Worker = oldWorker
Worker.ReceiveConfiguration(accountingSetting)
a.False(Worker.AcceptRequest(1, "mdm-master/group6/method"))
worker = oldWorker
ReceiveConfiguration(accountingSetting)
a.False(AcceptRequest(1, "mdm-master/group6/method"))
}
type snapshotRepository struct {
+1 -1
View File
@@ -52,6 +52,6 @@ func (s *snapshotTask) Stop() {
}
func (s *snapshotTask) saveSnapshot() error {
snapshotList := Worker.takeSnapshot()
snapshotList := worker.takeSnapshot()
return model.SnapshotRep.Update(snapshotList)
}
+1 -1
View File
@@ -88,7 +88,7 @@ func (handlerHelper) AuthenticateAccountingProxy(ctx *fasthttp.RequestCtx) domai
return domain.Create().SetError(err)
}
if !accounting.Worker.AcceptRequest(applicationId, path) {
if !accounting.AcceptRequest(applicationId, path) {
err := errors.New("accounting error")
utils.WriteError(ctx, "too many requests", codes.ResourceExhausted, nil)
return domain.Create().SetError(err)
+3 -3
View File
@@ -45,7 +45,7 @@ func main() {
bs.RequireModule(module, consumer, false)
}
bs.RequireModule(cfg.ModuleName, accounting.Worker.Consumer, false).
bs.RequireModule(cfg.ModuleName, accounting.NewConnectionConsumer, false).
OnShutdown(onShutdown).
OnRemoteConfigReceive(onRemoteConfigReceive).
Run()
@@ -64,7 +64,7 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) {
redis.Client.ReceiveConfiguration(remoteConfig.Redis)
authenticate.ReceiveConfiguration(remoteConfig.AuthCacheSetting)
accounting.Worker.ReceiveConfiguration(remoteConfig.AccountingSetting)
accounting.ReceiveConfiguration(remoteConfig.AccountingSetting)
metric.InitCollectors(remoteConfig.Metrics, oldRemoteConfig.Metrics)
metric.InitHttpServer(remoteConfig.Metrics)
@@ -88,7 +88,7 @@ func socketConfiguration(cfg interface{}) structure.SocketConfiguration {
func onShutdown(_ context.Context, _ os.Signal) {
server.Http.Close()
accounting.Worker.Close()
accounting.Close()
proxy.Close()
redis.Client.Close()
}