refactoring

This commit is contained in:
ykomissarov committed 2019-11-21 11:39:20 +03:00
1 parent 7acc4ebbd6
commit b4541f6c1b
14 files changed
+118 -110

No files matched your search

Generated
+1
View File
@@ -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",
+1 -1
View File
@@ -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()
}
+15 -12
View File
@@ -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,
+2 -2
View File
@@ -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",
},
}
+2 -2
View File
@@ -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)
}
+23 -23
View File
@@ -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)
}
}
+50
View File
@@ -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
}
-46
View File
@@ -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
}
+4 -4
View File
@@ -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"
}
}
}
+7 -7
View File
@@ -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 {
+3 -3
View File
@@ -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
+4 -4
View File
@@ -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;
DROP TABLE requests;
+1 -1
View File
@@ -16,5 +16,5 @@ var (
}))
SnapshotRep SnapshotRepository = snapshotRepository{rxClient: DbClient}
UnloadRep UnloadRepository = unloadRepository{rxClient: DbClient}
RequestsRep RequestsRepository = requestsRepository{rxClient: DbClient}
)
+5 -5
View File
@@ -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
}