MSP-1021 refactor script service

This commit is contained in:
novikovmu committed 2022-09-22 17:55:39 +03:00
1 parent f62f6bb4e6
commit 40c8fb88cc
1 file changed
+69 -57
+69 -57
View File
@@ -1,34 +1,21 @@
package service package service
import ( import (
"context"
"crypto/sha256" "crypto/sha256"
"crypto/sha512" "crypto/sha512"
"encoding/hex" "encoding/hex"
"sync" "sync"
"sync/atomic"
"time" "time"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/integration-system/isp-lib/v2/scripts" "github.com/integration-system/isp-kit/log"
log "github.com/integration-system/isp-log" "github.com/integration-system/isp-script"
"github.com/pkg/errors" "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/conf"
"isp-script-service/domain" "isp-script-service/domain"
"isp-script-service/router"
) )
var Script = &scriptService{
scriptEngine: scripts.NewEngine(),
}
type scriptService struct {
store atomic.Value
scriptEngine *scripts.Engine
}
type scriptServiceCfg struct { type scriptServiceCfg struct {
Scripts map[string]CompiledScript Scripts map[string]CompiledScript
ExecutionTimeout time.Duration ExecutionTimeout time.Duration
@@ -40,28 +27,32 @@ type CompiledScript struct {
Compiled bool Compiled bool
} }
func (s *scriptService) ReceiveConfiguration(scriptDef []conf.ScriptDefinition, sharedScript string, executionTimeoutMs int) { type Router interface {
var compiled bool Invoke(methodPath string, request interface{}, metadata map[string]interface{}) (interface{}, error)
cfg := &scriptServiceCfg{
Scripts: make(map[string]CompiledScript),
ExecutionTimeout: time.Duration(executionTimeoutMs) * time.Millisecond,
SharedScript: sharedScript,
}
for i, value := range scriptDef {
compiled = true
scr, err := s.Create(value.Script, sharedScript)
if err != nil {
log.Errorf(log_code.CreateScriptFromConfigError, "create script from config (number %d): %v", i, err)
compiled = false
}
cfg.Scripts[value.Id] = CompiledScript{scr, compiled}
}
s.store.Store(cfg)
} }
func (s *scriptService) Execute(req domain.ExecuteRequest) *domain.ScriptResp { type Script struct {
cfg := s.loadCfg() store scriptServiceCfg
scr, err := s.Create(req.Script, cfg.SharedScript) scriptEngine *scripts.Engine
logger log.Logger
router Router
}
func NewScript(invoker Router, logger log.Logger, sd []conf.ScriptDefinition, shared string, timeout int) *Script {
scr := scriptsFromConfig(context.Background(), logger, sd, shared, timeout)
scriptInstance := Script{
store: scr,
scriptEngine: scripts.NewEngine(),
logger: logger,
router: invoker,
}
return &scriptInstance
}
func (s *Script) Execute(req domain.ExecuteRequest) *domain.ScriptResp {
cfg := s.store
scr, err := createScript(req.Script, cfg.SharedScript)
if err != nil { if err != nil {
return s.respError(err, domain.ErrorCompile) return s.respError(err, domain.ErrorCompile)
} }
@@ -69,19 +60,19 @@ func (s *scriptService) Execute(req domain.ExecuteRequest) *domain.ScriptResp {
return s.executeScript(CompiledScript{scr, true}, req.Arg, cfg.ExecutionTimeout) return s.executeScript(CompiledScript{scr, true}, req.Arg, cfg.ExecutionTimeout)
} }
func (s *scriptService) ExecuteById(req domain.ExecuteByIdRequest) (*domain.ScriptResp, error) { func (s *Script) ExecuteById(req domain.ExecuteByIdRequest) (*domain.ScriptResp, error) {
cfg := s.loadCfg() cfg := s.store
scr, ok := cfg.Scripts[req.Id] scr, ok := cfg.Scripts[req.Id]
if !ok { if !ok {
return nil, status.Errorf(codes.NotFound, "not defined script for id %s", req.Id) return nil, domain.ErrScriptNotFound
} }
return s.executeScript(scr, req.Arg, cfg.ExecutionTimeout), nil return s.executeScript(scr, req.Arg, cfg.ExecutionTimeout), nil
} }
func (s *scriptService) BatchExecute(req []domain.ExecuteByIdRequest) []domain.ScriptResp { func (s *Script) BatchExecute(req []domain.ExecuteByIdRequest) []domain.ScriptResp {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
cfg := s.loadCfg() cfg := s.store
response := make([]domain.ScriptResp, len(req)) response := make([]domain.ScriptResp, len(req))
for i := range req { for i := range req {
wg.Add(1) wg.Add(1)
@@ -99,9 +90,9 @@ func (s *scriptService) BatchExecute(req []domain.ExecuteByIdRequest) []domain.S
return response return response
} }
func (s *scriptService) BatchExecuteById(req domain.BatchExecuteByIdsRequest) []domain.ScriptResp { func (s *Script) BatchExecuteById(req domain.BatchExecuteByIdsRequest) []domain.ScriptResp {
wg := sync.WaitGroup{} wg := sync.WaitGroup{}
cfg := s.loadCfg() cfg := s.store
response := make([]domain.ScriptResp, len(req.Ids)) response := make([]domain.ScriptResp, len(req.Ids))
for i := range req.Ids { for i := range req.Ids {
wg.Add(1) wg.Add(1)
@@ -119,24 +110,17 @@ func (s *scriptService) BatchExecuteById(req domain.BatchExecuteByIdsRequest) []
return response return response
} }
func (*scriptService) Create(script, sharedScript string) (scripts.Script, error) {
return scripts.NewScript([]byte(sharedScript),
[]byte("(function() {\n"), []byte(script), []byte("\n})();"))
}
var errEmpty = errors.New("empty answer, maybe lost return") var errEmpty = errors.New("empty answer, maybe lost return")
func (s *scriptService) executeScript(scr CompiledScript, arg interface{}, timeout time.Duration) *domain.ScriptResp { func (s *Script) executeScript(scr CompiledScript, arg interface{}, timeout time.Duration) *domain.ScriptResp {
if !scr.Compiled { if !scr.Compiled {
return s.respError(errors.New("invalid script configuration"), domain.ErrorCompile) return s.respError(errors.New("invalid script configuration"), domain.ErrorCompile)
} }
response, err := s.scriptEngine.Execute(scr.Script, arg, response, err := s.scriptEngine.Execute(scr.Script, arg,
scripts.WithScriptTimeout(timeout), scripts.WithScriptTimeout(timeout),
// TODO: remove. invoke is deprecated, all functions should be inside `external` object
scripts.WithSet("invoke", router.Invoke),
scripts.WithSet("external", map[string]interface{}{ scripts.WithSet("external", map[string]interface{}{
"invoke": router.Invoke, "invoke": s.router.Invoke,
"hashSha256": Sha256, "hashSha256": Sha256,
"hashSha512": Sha512, "hashSha512": Sha512,
"generateUUIDv4": UUIDv4, "generateUUIDv4": UUIDv4,
@@ -154,7 +138,7 @@ func (s *scriptService) executeScript(scr CompiledScript, arg interface{}, timeo
} }
} }
func (*scriptService) respError(err error, errorType string) *domain.ScriptResp { func (*Script) respError(err error, errorType string) *domain.ScriptResp {
respError := domain.Error{ respError := domain.Error{
Type: errorType, Type: errorType,
Description: err.Error(), Description: err.Error(),
@@ -165,10 +149,6 @@ func (*scriptService) respError(err error, errorType string) *domain.ScriptResp
} }
} }
func (s *scriptService) loadCfg() *scriptServiceCfg {
return s.store.Load().(*scriptServiceCfg)
}
func Sha256(value string) string { func Sha256(value string) string {
sum := sha256.Sum256([]byte(value)) sum := sha256.Sum256([]byte(value))
return hex.EncodeToString(sum[:]) return hex.EncodeToString(sum[:])
@@ -187,3 +167,35 @@ func UUIDv4() string {
} }
return randomUUID.String() return randomUUID.String()
} }
func scriptsFromConfig(
ctx context.Context,
logger log.Logger,
scriptDef []conf.ScriptDefinition,
sharedScript string,
executionTimeoutMs int,
) scriptServiceCfg {
var compiled bool
cfg := scriptServiceCfg{
Scripts: make(map[string]CompiledScript),
ExecutionTimeout: time.Duration(executionTimeoutMs) * time.Millisecond,
SharedScript: sharedScript,
}
for _, value := range scriptDef {
compiled = true
scr, err := createScript(value.Script, sharedScript)
if err != nil {
logger.Error(ctx, errors.WithMessage(err, "create script from config"),
log.String("scriptId", value.Id))
compiled = false
}
cfg.Scripts[value.Id] = CompiledScript{scr, compiled}
}
return cfg
}
func createScript(script, sharedScript string) (scripts.Script, error) {
return scripts.NewScript([]byte(sharedScript),
[]byte("(function() {\n"), []byte(script), []byte("\n})();"))
}