Small Refactoring

This commit is contained in:
riabovvo committed 2020-09-01 14:22:53 +03:00
1 parent 9ccc1c1728
commit 24d35e0505
9 files changed
+66 -71

No files matched your search

+2 -1
View File
@@ -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 {
+14 -13
View File
@@ -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
}
+4 -4
View File
@@ -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)
}
+12 -16
View File
@@ -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()
}
}
+8 -8
View File
@@ -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,
+2 -4
View File
@@ -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) {
+9 -20
View File
@@ -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 {
+3 -1
View File
@@ -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()
+12 -4
View File
@@ -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,
}