From b4541f6c1bb8e36074ec9220e7e5d6ae385e5923 Mon Sep 17 00:00:00 2001 From: ykomissarov Date: Thu, 21 Nov 2019 11:39:20 +0300 Subject: [PATCH] refactoring --- Gopkg.lock | 1 + accounting/accountant.go | 2 +- accounting/accounting.go | 27 ++++++------ accounting/accounting_test.go | 4 +- accounting/snapshot.go | 4 +- accounting/{unload.go => storing.go} | 46 ++++++++++---------- accounting/storing_test.go | 50 ++++++++++++++++++++++ accounting/unload_test.go | 46 -------------------- conf/default_remote_config.json | 8 ++-- conf/remote_config.go | 14 +++--- entity/entity.go | 6 +-- migrations/00002_2019-11-19_add_unload.sql | 8 ++-- model/client.go | 2 +- model/{unload.go => requests.go} | 10 ++--- 14 files changed, 118 insertions(+), 110 deletions(-) rename accounting/{unload.go => storing.go} (59%) create mode 100644 accounting/storing_test.go delete mode 100644 accounting/unload_test.go rename model/{unload.go => requests.go} (60%) diff --git a/Gopkg.lock b/Gopkg.lock index b6c7e69..35e8408 100644 --- a/Gopkg.lock +++ b/Gopkg.lock @@ -638,6 +638,7 @@ "github.com/integration-system/isp-lib/structure", "github.com/integration-system/isp-lib/utils", "github.com/integration-system/isp-log", + "github.com/integration-system/isp-log/stdcodes", "github.com/json-iterator/go", "github.com/pkg/errors", "github.com/rcrowley/go-metrics", diff --git a/accounting/accountant.go b/accounting/accountant.go index f4b6bb3..cde93b0 100644 --- a/accounting/accountant.go +++ b/accounting/accountant.go @@ -27,7 +27,7 @@ func (app *accountant) Accept(method string) bool { func (app *accountant) Snapshot() map[string]state.Snapshot { app.mx.Lock() - snapshotLimitState := make(map[string]state.Snapshot) + snapshotLimitState := make(map[string]state.Snapshot, len(app.limitStates)) for method, limitState := range app.limitStates { snapshotLimitState[method] = limitState.Export() } diff --git a/accounting/accounting.go b/accounting/accounting.go index ac88932..8fc7cbd 100644 --- a/accounting/accounting.go +++ b/accounting/accounting.go @@ -16,7 +16,7 @@ import ( var ( accountingWorking = false accountingStorage = make(map[int32]Accounting) - unloadingStorage = make(map[int32]bool) + requestsStoring = make(map[int32]bool) ) type Accounting interface { @@ -27,15 +27,15 @@ type Accounting interface { func ReceiveConfiguration(conf conf.Accounting) { Close() newAccountingStorage := make(map[int32]Accounting) - newUnloadingStorage := make(map[int32]bool) + newRequestsStoring := make(map[int32]bool) if conf.Enable { - if err := unload.Init(conf.Unload); err != nil { + if err := storage.Init(conf.Storing); err != nil { log.Fatal(stdcodes.ModuleInvalidRemoteConfig, err) } for _, s := range conf.Setting { - newUnloadingStorage[s.ApplicationId] = s.EnableUnload + newRequestsStoring[s.ApplicationId] = s.EnableStoring limitStates, patternArray, err := state.InitLimitState(s.Limits) if err != nil { @@ -62,29 +62,32 @@ func ReceiveConfiguration(conf conf.Accounting) { accountingWorking = false } - unloadingStorage = newUnloadingStorage + requestsStoring = newRequestsStoring accountingStorage = newAccountingStorage } func Accept(appId int32, path string) bool { - if unloadingStorage[appId] { - unload.TakeRequest(appId, path, time.Now()) - } - if accouter, ok := accountingStorage[appId]; !ok { + if requestsStoring[appId] { + storage.TakeRequest(appId, path, time.Now()) + } return true } else { - return accouter.Accept(path) + ok := accouter.Accept(path) + if ok && requestsStoring[appId] { + storage.TakeRequest(appId, path, time.Now()) + } + return ok } } func Close() { snapshot.Stop() - unload.Stop() + storage.Stop() } func takeSnapshot() []entity.Snapshot { - response := make([]entity.Snapshot, 0) + response := make([]entity.Snapshot, 0, len(accountingStorage)) for appId, account := range accountingStorage { response = append(response, entity.Snapshot{ AppId: appId, diff --git a/accounting/accounting_test.go b/accounting/accounting_test.go index 50fd95b..1389f83 100644 --- a/accounting/accounting_test.go +++ b/accounting/accounting_test.go @@ -26,8 +26,8 @@ var ( {Pattern: "mdm-master/group/method", MaxCount: 0, Timeout: "10s"}, }}, }, - Unload: conf.UnloadSetting{ - Count: 100, + Storing: conf.StoringSetting{ + Size: 100, Timeout: "1h", }, } diff --git a/accounting/snapshot.go b/accounting/snapshot.go index 6eea929..6e63173 100644 --- a/accounting/snapshot.go +++ b/accounting/snapshot.go @@ -34,7 +34,7 @@ func (s *snapshotTask) Start(timeout time.Duration) { case <-s.close: return case <-s.timeout: - if err := s.complete(); err != nil { + if err := s.saveSnapshot(); err != nil { log.Error(log_code.ErrorSnapshotAccounting, err) } s.timeout = time.After(timeout) @@ -51,7 +51,7 @@ func (s *snapshotTask) Stop() { s.mx.Unlock() } -func (s *snapshotTask) complete() error { +func (s *snapshotTask) saveSnapshot() error { snapshotList := takeSnapshot() return model.SnapshotRep.Update(snapshotList) } diff --git a/accounting/unload.go b/accounting/storing.go similarity index 59% rename from accounting/unload.go rename to accounting/storing.go index dc8b762..d10686a 100644 --- a/accounting/unload.go +++ b/accounting/storing.go @@ -10,31 +10,31 @@ import ( "time" ) -var unload = &unloadingTask{ +var storage = &storingTask{ mx: sync.Mutex{}, counter: 0, process: false, chanTimeout: make(chan time.Time), - chanCounter: make(chan []entity.Unload), + chanCounter: make(chan []entity.Request), chanClose: make(chan bool), } -type unloadingTask struct { - cache []entity.Unload +type storingTask struct { + buffer []entity.Request counter int process bool chanTimeout <-chan time.Time - chanCounter chan []entity.Unload + chanCounter chan []entity.Request chanClose chan bool mx sync.Mutex } -func (u *unloadingTask) Init(setting conf.UnloadSetting) error { +func (u *storingTask) Init(setting conf.StoringSetting) error { u.mx.Lock() u.process = true - u.cache = make([]entity.Unload, setting.Count) + u.buffer = make([]entity.Request, setting.Size) u.counter = 0 u.mx.Unlock() @@ -46,36 +46,36 @@ func (u *unloadingTask) Init(setting conf.UnloadSetting) error { return nil } -func (u *unloadingTask) TakeRequest(appId int32, method string, date time.Time) { +func (u *storingTask) TakeRequest(appId int32, method string, date time.Time) { u.mx.Lock() if !u.process { u.mx.Unlock() return } - u.cache[u.counter] = entity.Unload{ + u.buffer[u.counter] = entity.Request{ AppId: appId, Method: method, CreatedAt: date, } u.counter++ - if u.counter == len(u.cache) { - u.chanCounter <- u.cache + if u.counter == len(u.buffer) { + u.chanCounter <- u.buffer - oldLen := len(u.cache) + oldLen := len(u.buffer) u.counter = 0 - u.cache = make([]entity.Unload, oldLen) + u.buffer = make([]entity.Request, oldLen) } u.mx.Unlock() } -func (u *unloadingTask) Stop() { +func (u *storingTask) Stop() { u.mx.Lock() if u.process { if u.counter != 0 { - defer u.unload(u.cache[:u.counter]) + defer u.unload(u.buffer[:u.counter]) } u.chanClose <- true u.process = false @@ -83,25 +83,25 @@ func (u *unloadingTask) Stop() { u.mx.Unlock() } -func (u *unloadingTask) run(timeout time.Duration) { +func (u *storingTask) run(timeout time.Duration) { u.chanTimeout = time.After(timeout) for { select { case <-u.chanClose: return case cache := <-u.chanCounter: - u.unload(cache) + go u.unload(cache) u.chanTimeout = time.After(timeout) case <-u.chanTimeout: u.mx.Lock() if u.counter != 0 { - cache := u.cache[:u.counter] - oldLen := len(u.cache) + cache := u.buffer[:u.counter] + oldLen := len(u.buffer) u.counter = 0 - u.cache = make([]entity.Unload, oldLen) + u.buffer = make([]entity.Request, oldLen) u.mx.Unlock() - u.unload(cache) + go u.unload(cache) } else { u.mx.Unlock() } @@ -110,8 +110,8 @@ func (u *unloadingTask) run(timeout time.Duration) { } } -func (u *unloadingTask) unload(cache []entity.Unload) { - if err := model.UnloadRep.Insert(cache); err != nil { +func (u *storingTask) unload(cache []entity.Request) { + if err := model.RequestsRep.Insert(cache); err != nil { log.Error(log_code.ErrorUnloadAccounting, err) } } diff --git a/accounting/storing_test.go b/accounting/storing_test.go new file mode 100644 index 0000000..348ab8c --- /dev/null +++ b/accounting/storing_test.go @@ -0,0 +1,50 @@ +package accounting + +import ( + "github.com/stretchr/testify/assert" + "isp-gate-service/conf" + "isp-gate-service/entity" + "isp-gate-service/model" + "sync" + "testing" + "time" +) + +var unloadingSetting = conf.StoringSetting{ + Size: 3, + Timeout: "50ms", +} + +func TestStoringTask(t *testing.T) { + a := assert.New(t) + repository := &requestsRepository{cache: make([]entity.Request, 0)} + model.RequestsRep = repository + + err := storage.Init(unloadingSetting) + a.NoError(err) + + for i, j := range []string{"1", "2", "3", "4", "5"} { + storage.TakeRequest(int32(i), j, time.Now()) + } + a.Len(repository.cache, 3) + time.Sleep(time.Millisecond * 60) + a.Len(repository.cache, 5) + + for i, j := range []string{"1", "2", "3", "4", "5"} { + storage.TakeRequest(int32(i), j, time.Now()) + } + storage.Stop() + a.Len(repository.cache, 10) +} + +type requestsRepository struct { + cache []entity.Request + mx sync.Mutex +} + +func (r *requestsRepository) Insert(model []entity.Request) error { + r.mx.Lock() + r.cache = append(r.cache, model...) + r.mx.Unlock() + return nil +} diff --git a/accounting/unload_test.go b/accounting/unload_test.go deleted file mode 100644 index 127265a..0000000 --- a/accounting/unload_test.go +++ /dev/null @@ -1,46 +0,0 @@ -package accounting - -import ( - "github.com/stretchr/testify/assert" - "isp-gate-service/conf" - "isp-gate-service/entity" - "isp-gate-service/model" - "testing" - "time" -) - -var unloadingSetting = conf.UnloadSetting{ - Count: 3, - Timeout: "50ms", -} - -func TestUnloadingTask(t *testing.T) { - a := assert.New(t) - repository := &unloadRepository{cache: make([]entity.Unload, 0)} - model.UnloadRep = repository - - err := unload.Init(unloadingSetting) - a.NoError(err) - - for i, j := range []string{"1", "2", "3", "4", "5"} { - unload.TakeRequest(int32(i), j, time.Now()) - } - a.Len(repository.cache, 3) - time.Sleep(time.Millisecond * 60) - a.Len(repository.cache, 5) - - for i, j := range []string{"1", "2", "3", "4", "5"} { - unload.TakeRequest(int32(i), j, time.Now()) - } - unload.Stop() - a.Len(repository.cache, 10) -} - -type unloadRepository struct { - cache []entity.Unload -} - -func (r *unloadRepository) Insert(model []entity.Unload) error { - r.cache = append(r.cache, model...) - return nil -} diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index e6bc661..6a3fc01 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -21,7 +21,7 @@ "setting": [ { "applicationId": 0, - "enableUnload": false, + "enableStoring": false, "limits": [ { "timeout": "1s", @@ -31,8 +31,8 @@ ] } ], - "unload": { - "count": 1, + "storing": { + "size": 10000, "timeout": "30m" } }, @@ -71,4 +71,4 @@ "enableCash": false, "evictTimeout": "1m" } -} \ No newline at end of file +} diff --git a/conf/remote_config.go b/conf/remote_config.go index 9747ac7..7a70ecf 100644 --- a/conf/remote_config.go +++ b/conf/remote_config.go @@ -48,15 +48,15 @@ type ( } Accounting struct { - Enable bool `schema:"Статус работы учета,включает/отключает учет запросов"` - SnapshotTimeout string `schema:"Время частоты выгрузки учтенных запросов" valid:"required~Required"` + Enable bool `schema:"Учет запросов,включает/отключает учет запросов"` + SnapshotTimeout string `schema:"Частота выгрузки данных учета в БД" valid:"required~Required"` Setting []AccountingSetting `schema:"Настройка учета для приложений"` - Unload UnloadSetting `schema:"Настройка общей выгрзуки запросов"` + Storing StoringSetting `schema:"Настройка хранения запросов"` } AccountingSetting struct { ApplicationId int32 `valid:"required~Required" schema:"Идентификатор приложения"` - EnableUnload bool `schema:"Включает в общую выгрузку запросы для этого приложения"` + EnableStoring bool `schema:"Хранение запросов,если включено, каждый факт обработки запроса будет фиксироваться в БД"` Limits []LimitSetting `schema:"Настройка ограничений на запросы"` } @@ -66,9 +66,9 @@ type ( Timeout string `schema:"Время жизни одного запроса"` } - UnloadSetting struct { - Count int `schema:"Ограничение по количеству для выгрузки" valid:"required~Range(1|1000000)"` - Timeout string `schema:"Ограничение по времени для выгрузки" valid:"required~Required"` + StoringSetting struct { + Size int `schema:"Размер буфера,размер буфера,при достижении которого данные сбрасываются в БД" valid:"required,range(1|1000000)"` + Timeout string `schema:"Частота сброса,периодичность сброса данных в БД" valid:"required~Required"` } HttpSetting struct { diff --git a/entity/entity.go b/entity/entity.go index d67041a..36b6f96 100644 --- a/entity/entity.go +++ b/entity/entity.go @@ -6,13 +6,13 @@ import ( ) type Snapshot struct { - TableName string `sql:"gate_service.snapshot" json:"-"` + TableName string `sql:"?db_schema.snapshot" json:"-"` AppId int32 `sql:",pk"` LimitState map[string]state.Snapshot } -type Unload struct { - TableName string `sql:"gate_service.unload" json:"-"` +type Request struct { + TableName string `sql:"?db_schema.requests" json:"-"` Id int `sql:",pk"` AppId int32 Method string diff --git a/migrations/00002_2019-11-19_add_unload.sql b/migrations/00002_2019-11-19_add_unload.sql index ab2c6e6..a7de482 100644 --- a/migrations/00002_2019-11-19_add_unload.sql +++ b/migrations/00002_2019-11-19_add_unload.sql @@ -1,12 +1,12 @@ -- +goose Up -CREATE TABLE unload +CREATE TABLE requests ( id SERIAL8 PRIMARY KEY, - app_id INTEGER NOT NULL, + app_id INT4 NOT NULL, method VARCHAR(255) NOT NULL, - created_at TIMESTAMP NOT NULL + created_at TIMESTAMP NOT NULL DEFAULT now() ); -- +goose Down -DROP TABLE unload; \ No newline at end of file +DROP TABLE requests; diff --git a/model/client.go b/model/client.go index 21712bd..2616156 100644 --- a/model/client.go +++ b/model/client.go @@ -16,5 +16,5 @@ var ( })) SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient} - UnloadRep UnloadRepository = unloadRepository{rxClient: DbClient} + RequestsRep RequestsRepository = requestsRepository{rxClient: DbClient} ) diff --git a/model/unload.go b/model/requests.go similarity index 60% rename from model/unload.go rename to model/requests.go index 0e1e78e..c102b26 100644 --- a/model/unload.go +++ b/model/requests.go @@ -7,22 +7,22 @@ import ( ) type ( - UnloadRepository interface { - Insert([]entity.Unload) error + RequestsRepository interface { + Insert([]entity.Request) error } - unloadRepository struct { + requestsRepository struct { DB orm.DB rxClient *database.RxDbClient } ) -func (r unloadRepository) Insert(model []entity.Unload) error { +func (r requestsRepository) Insert(model []entity.Request) error { _, err := r.getDb().Model(&model).Insert() return err } -func (r unloadRepository) getDb() orm.DB { +func (r requestsRepository) getDb() orm.DB { if r.DB != nil { return r.DB }