From 24d35e0505adc9ee5a1e1587a6a823e5172270fb Mon Sep 17 00:00:00 2001 From: riabovvo Date: Tue, 1 Sep 2020 14:22:53 +0300 Subject: [PATCH] Small Refactoring --- adapter/custom_date.go | 3 ++- adapter/custom_date_test.go | 27 ++++++++++++++------------- controller/script.go | 8 ++++---- engine_script_test.go | 28 ++++++++++++---------------- main.go | 16 ++++++++-------- router/client.go | 6 ++---- script/goja.go | 29 +++++++++-------------------- script/goja_test.go | 4 +++- service/script.go | 16 ++++++++++++---- 9 files changed, 66 insertions(+), 71 deletions(-) diff --git a/adapter/custom_date.go b/adapter/custom_date.go index 86db6b3..359dc3d 100644 --- a/adapter/custom_date.go +++ b/adapter/custom_date.go @@ -49,7 +49,7 @@ var ( } ) -func getCustomData(data map[string]interface{}, id string, version int64) map[string]interface{} { +func GetCustomData(data map[string]interface{}, id string, version int64) map[string]interface{} { jq := jsonq.NewQuery(data) m := make(map[string]interface{}, 6) @@ -94,6 +94,7 @@ func expandArrayWithMapping( ) { docs, err := src.ArrayOfObjects(arrayPath) l := len(docs) + //nolint if err == nil && l > 0 { documents := make(map[string][]interface{}, l) for _, d := range docs { diff --git a/adapter/custom_date_test.go b/adapter/custom_date_test.go index a50c1d6..fbe3229 100644 --- a/adapter/custom_date_test.go +++ b/adapter/custom_date_test.go @@ -1,8 +1,14 @@ -package adapter +package adapter_test import ( "encoding/json" "io/ioutil" + "isp-script-service/adapter" + "isp-script-service/conf" + "isp-script-service/controller" + "isp-script-service/domain" + "isp-script-service/script" + "isp-script-service/service" "log" "os" "testing" @@ -10,11 +16,6 @@ import ( "github.com/integration-system/isp-lib/v2/config" jsoniter "github.com/json-iterator/go" "github.com/stretchr/testify/assert" - "isp-script-service/conf" - "isp-script-service/controller" - "isp-script-service/domain" - "isp-script-service/script" - "isp-script-service/service" ) const ( @@ -29,8 +30,10 @@ const ( scriptFile = "custom_date.js" ) -var data map[string]interface{} -var request = domain.ExecuteRequest{} +var ( + data map[string]interface{} + request = domain.ExecuteRequest{} +) func init() { config.InitRemoteConfig(&conf.RemoteConfig{}, []byte(remoteConf)) @@ -68,7 +71,7 @@ func TestCustomDate(t *testing.T) { } executeResult, _ := json.Marshal(execute.Result) - customDate := getCustomData(data, id, version) + customDate := adapter.GetCustomData(data, id, version) customDateResult, _ := json.Marshal(customDate) if !a.Equal(string(customDateResult), string(executeResult)) { @@ -78,9 +81,7 @@ func TestCustomDate(t *testing.T) { func BenchmarkGoCustomData(b *testing.B) { for i := 0; i < b.N; i++ { - _ = getCustomData(data, id, version) - //json.Marshal(customDate) - + _ = adapter.GetCustomData(data, id, version) } } @@ -134,7 +135,6 @@ func BenchmarkJsoniterJson(b *testing.B) { panic(err) } } - } func readFile(name string) ([]byte, error) { @@ -148,5 +148,6 @@ func readFile(name string) ([]byte, error) { if err != nil { return nil, err } + return obj, nil } diff --git a/controller/script.go b/controller/script.go index a26aabc..793de79 100644 --- a/controller/script.go +++ b/controller/script.go @@ -18,7 +18,7 @@ type scriptController struct{} // @Param body body domain.ExecuteByIdRequest true "Идентифиактор скрипта" // @Success 200 {object} domain.ScriptResp // @Failure 404 {object} structure.GrpcError -// @Router /script/execute_by_id [POST] +// @Router /script/execute_by_id [POST]. func (c scriptController) ExecuteById(req domain.ExecuteByIdRequest) (*domain.ScriptResp, error) { return service.Script.ExecuteById(req) } @@ -31,7 +31,7 @@ func (c scriptController) ExecuteById(req domain.ExecuteByIdRequest) (*domain.Sc // @Produce json // @Param body body domain.ExecuteRequest true "Скрипт необходимый к выполнению" // @Success 200 {object} domain.ScriptResp -// @Router /script/execute [POST] +// @Router /script/execute [POST]. func (c scriptController) Execute(req domain.ExecuteRequest) *domain.ScriptResp { return service.Script.Execute(req) } @@ -44,7 +44,7 @@ func (c scriptController) Execute(req domain.ExecuteRequest) *domain.ScriptResp // @Produce json // @Param body body []domain.ExecuteByIdRequest true "Набор идентфикаторов и аргументов" // @Success 200 {array} domain.ScriptResp -// @Router /script/batch_execute [POST] +// @Router /script/batch_execute [POST]. func (c scriptController) BatchExecute(req []domain.ExecuteByIdRequest) []domain.ScriptResp { return service.Script.BatchExecute(req) } @@ -57,7 +57,7 @@ func (c scriptController) BatchExecute(req []domain.ExecuteByIdRequest) []domain // @Produce json // @Param body body domain.BatchExecuteByIdsRequest true "Набор идентфикаторов и единый аргумент" // @Success 200 {array} domain.ScriptResp -// @Router /script/batch_execute_by_ids [POST] +// @Router /script/batch_execute_by_ids [POST]. func (c scriptController) BatchExecuteById(req domain.BatchExecuteByIdsRequest) []domain.ScriptResp { return service.Script.BatchExecuteById(req) } diff --git a/engine_script_test.go b/engine_script_test.go index 1208dc2..8182942 100644 --- a/engine_script_test.go +++ b/engine_script_test.go @@ -1,4 +1,4 @@ -package main +package main_test import ( json2 "encoding/json" @@ -9,9 +9,9 @@ import ( "github.com/robertkrimen/otto" "github.com/robertkrimen/otto/parser" "github.com/stretchr/testify/assert" - "github.com/yuin/gopher-lua" + lua "github.com/yuin/gopher-lua" "github.com/yuin/gopher-lua/parse" - "layeh.com/gopher-json" + json "layeh.com/gopher-json" ) const ( @@ -58,7 +58,7 @@ var ( }, } srcString []byte - expecting = make(map[string]interface{}, 0) + expecting = make(map[string]interface{}) ) func init() { @@ -107,7 +107,6 @@ func TestGoja(t *testing.T) { runTime := goja.New() runTime.Set("b", recordsExample) _, err := runTime.RunProgram(prog) - if err != nil { t.Fatal(err) } @@ -121,13 +120,6 @@ func TestGopherLua(t *testing.T) { l := lua.NewState() defer l.Close() - /*f, err := l.LoadString(` - println(src) - dst = src - `) - if !assert.NoError(err) { - return - }*/ b, _ := json2.Marshal(recordsExample) val, err := json.Decode(l, b) if !assert.NoError(err) { @@ -142,7 +134,10 @@ func TestGopherLua(t *testing.T) { } dst := l.GetGlobal("dst") b, err = json.Encode(dst) - m := make(map[string]interface{}, 0) + if !assert.NoError(err) { + return + } + m := make(map[string]interface{}) err = json2.Unmarshal(b, &m) if !assert.NoError(err) { return @@ -186,7 +181,6 @@ func BenchmarkGoja(b *testing.B) { runTime := goja.New() runTime.Set("b", recordsExample) _, err := runTime.RunProgram(prog) - if err != nil { return } @@ -223,12 +217,14 @@ func BenchmarkGopherLua(b *testing.B) { dst := l.GetGlobal("dst") c, err := json.Encode(dst) - m := make(map[string]interface{}, 0) + if err != nil { + panic(err) + } + m := make(map[string]interface{}) err = json2.Unmarshal(c, &m) if err != nil { panic(err) } - l.Close() } } diff --git a/main.go b/main.go index 24346f5..ef2a2d3 100644 --- a/main.go +++ b/main.go @@ -2,12 +2,11 @@ package main import ( "context" - "os" - "isp-script-service/conf" "isp-script-service/helper" "isp-script-service/router" "isp-script-service/service" + "os" "github.com/integration-system/isp-lib/v2/backend" "github.com/integration-system/isp-lib/v2/bootstrap" @@ -19,9 +18,7 @@ import ( "google.golang.org/grpc" ) -var ( - version = "1.0.0" -) +var version = "1.0.0" // @title isp-script-service // @version 1.0.0 @@ -49,6 +46,7 @@ func main() { func socketConfiguration(cfg interface{}) structure.SocketConfiguration { appConfig := cfg.(*conf.Configuration) + return structure.SocketConfiguration{ Host: appConfig.ConfigServiceAddress.IP, Port: appConfig.ConfigServiceAddress.Port, @@ -71,19 +69,21 @@ func onRemoteConfigReceive(remoteConfig, oldRemoteConfig *conf.RemoteConfig) { } func onLocalConfigLoad(cfg *conf.Configuration) { + //nolint + msgSize := 1024 * 1024 * 512 metric.InitProfiling(cfg.ModuleName) handlers := helper.GetAllHandlers() service := backend.GetDefaultService(cfg.ModuleName, handlers...) backend.StartBackendGrpcServer( cfg.GrpcInnerAddress, service, - grpc.MaxRecvMsgSize(1024*1024*512), - grpc.MaxSendMsgSize(1024*1024*512), + grpc.MaxRecvMsgSize(msgSize), + grpc.MaxSendMsgSize(msgSize), ) - } func routesData(localConfig interface{}) bootstrap.ModuleInfo { cfg := localConfig.(*conf.Configuration) + return bootstrap.ModuleInfo{ ModuleName: cfg.ModuleName, ModuleVersion: version, diff --git a/router/client.go b/router/client.go index e84f6a5..84e6cb4 100644 --- a/router/client.go +++ b/router/client.go @@ -8,10 +8,8 @@ import ( md "google.golang.org/grpc/metadata" ) -var ( - Client = backend.NewRxGrpcClient( - backend.WithDialOptions(grpc.WithInsecure()), - ) +var Client = backend.NewRxGrpcClient( + backend.WithDialOptions(grpc.WithInsecure()), ) func Invoke(methodPath string, request interface{}, metadata map[string]interface{}) (interface{}, error) { diff --git a/script/goja.go b/script/goja.go index 740962b..9d15ac9 100644 --- a/script/goja.go +++ b/script/goja.go @@ -2,13 +2,13 @@ package script import ( "errors" + "isp-script-service/conf" + "isp-script-service/router" "sync" "time" "github.com/dop251/goja" "github.com/integration-system/isp-lib/v2/config" - "isp-script-service/conf" - "isp-script-service/router" ) var pool = &sync.Pool{ @@ -20,6 +20,7 @@ var pool = &sync.Pool{ func initVm() *goja.Runtime { vm := goja.New() vm.Set("invoke", router.Invoke) + return vm } @@ -30,13 +31,17 @@ func (*Goja) Compile(script string) (Script, error) { if err != nil { return nil, err } + return &GojaProgram{prog: prog}, nil } +var errUnknownEngine = errors.New("unknown engine") + func (*Goja) Execute(program Script, arg interface{}) (interface{}, error) { value, ok := program.Src().(*goja.Program) + if !ok { - return nil, errors.New("unknown engine") + return nil, errUnknownEngine } vm := pool.Get().(*goja.Runtime) @@ -56,24 +61,8 @@ func (*Goja) Execute(program Script, arg interface{}) (interface{}, error) { if err != nil { return nil, err } + return res.Export(), nil - /*go func() { - result, err := vm.RunProgram(value) - if err != nil { - errorCh <- err - return - } - resultCh <- result.Export() - }() - select { - case result := <-resultCh: - return result, nil - case err := <-errorCh: - return nil, err - case <-time.After(awaitTime): - vm.Interrupt("time exceeded") - return nil, errors.New("time exceeded") - }*/ } type GojaProgram struct { diff --git a/script/goja_test.go b/script/goja_test.go index 50d1130..3d2c41c 100644 --- a/script/goja_test.go +++ b/script/goja_test.go @@ -1,4 +1,4 @@ -package script +package script_test import ( "errors" @@ -31,6 +31,7 @@ func TestGoja_AddFunction(t *testing.T) { a.Equal("string", varchar) a.Equal(0, integer) a.Equal("test", object) + return "test", nil } vm := goja.New() @@ -43,6 +44,7 @@ func TestGoja_AddFunction(t *testing.T) { a.Equal("string", varchar) a.Equal(0, integer) a.Equal("test", object) + //nolint return "test", errors.New("TEST") } vm = goja.New() diff --git a/service/script.go b/service/script.go index c347d22..9136a54 100644 --- a/service/script.go +++ b/service/script.go @@ -2,6 +2,10 @@ package service import ( "fmt" + log_code "isp-script-service/codes" + "isp-script-service/conf" + "isp-script-service/domain" + "isp-script-service/script" "sync" "sync/atomic" @@ -10,10 +14,6 @@ import ( "github.com/pkg/errors" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - log_code "isp-script-service/codes" - "isp-script-service/conf" - "isp-script-service/domain" - "isp-script-service/script" ) var Script = &scriptService{} @@ -28,6 +28,7 @@ func (s *scriptService) ReceiveConfiguration(scriptDef []conf.ScriptDefinition) scr, err := s.Create(value.Script) if err != nil { log.Errorf(log_code.CreateScriptFromConfigError, "create script from config (number %d): %v", i, err) + continue } newStore[value.Id] = scr @@ -40,6 +41,7 @@ func (s *scriptService) Execute(req domain.ExecuteRequest) *domain.ScriptResp { if err != nil { return s.respError(err, domain.ErrorCompile) } + return s.executeScript(scr, req.Arg) } @@ -48,6 +50,7 @@ func (s *scriptService) ExecuteById(req domain.ExecuteByIdRequest) (*domain.Scri if scr == nil { return nil, status.Errorf(codes.NotFound, "not defined script for id %s", req.Id) } + return s.executeScript(scr, req.Arg), nil } @@ -67,6 +70,7 @@ func (s *scriptService) BatchExecute(req []domain.ExecuteByIdRequest) []domain.S }(i) } wg.Wait() + return response } @@ -86,12 +90,14 @@ func (s *scriptService) BatchExecuteById(req domain.BatchExecuteByIdsRequest) [] }(i) } wg.Wait() + return response } func (*scriptService) Create(scr string) (script.Script, error) { cfg := config.GetRemote().(*conf.RemoteConfig) scr = fmt.Sprintf("%s%s%s%s", cfg.SharedScript, "(function() {", scr, "})();") + return script.Default().Compile(scr) } @@ -103,6 +109,7 @@ func (s *scriptService) executeScript(scr script.Script, arg interface{}) *domai if response == nil { return s.respError(errors.New("empty answer, maybe lost return"), domain.ErrorRunTime) } + return &domain.ScriptResp{ Result: response, } @@ -113,6 +120,7 @@ func (*scriptService) respError(err error, errorType string) *domain.ScriptResp Type: errorType, Description: err.Error(), } + return &domain.ScriptResp{ Error: &respError, }