@ -1,15 +1,20 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"context"
|
||||
"math/rand"
|
||||
"sync"
|
||||
|
||||
"github.com/dop251/goja"
|
||||
"github.com/dop251/goja_nodejs/eventloop"
|
||||
"github.com/pkg/errors"
|
||||
"gitlab.com/wpetit/goweb/logger"
|
||||
)
|
||||
|
||||
var ErrFuncDoesNotExist = errors.New("function does not exist")
|
||||
var (
|
||||
ErrFuncDoesNotExist = errors.New("function does not exist")
|
||||
ErUnknownError = errors.New("unknown error")
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
runtime *goja.Runtime
|
||||
@ -26,16 +31,18 @@ func (s *Server) Load(name string, src string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) ExecFuncByName(funcName string, args ...interface{}) (goja.Value, error) {
|
||||
func (s *Server) ExecFuncByName(ctx context.Context, funcName string, args ...interface{}) (goja.Value, error) {
|
||||
ctx = logger.With(ctx, logger.F("function", funcName), logger.F("args", args))
|
||||
|
||||
callable, ok := goja.AssertFunction(s.runtime.Get(funcName))
|
||||
if !ok {
|
||||
return nil, errors.WithStack(ErrFuncDoesNotExist)
|
||||
}
|
||||
|
||||
return s.Exec(callable, args...)
|
||||
return s.Exec(ctx, callable, args...)
|
||||
}
|
||||
|
||||
func (s *Server) Exec(callable goja.Callable, args ...interface{}) (goja.Value, error) {
|
||||
func (s *Server) Exec(ctx context.Context, callable goja.Callable, args ...interface{}) (goja.Value, error) {
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
value goja.Value
|
||||
@ -45,6 +52,25 @@ func (s *Server) Exec(callable goja.Callable, args ...interface{}) (goja.Value,
|
||||
wg.Add(1)
|
||||
|
||||
s.loop.RunOnLoop(func(vm *goja.Runtime) {
|
||||
logger.Debug(ctx, "executing callable")
|
||||
|
||||
defer wg.Done()
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
revoveredErr, ok := recovered.(error)
|
||||
if ok {
|
||||
logger.Error(ctx, "recovered runtime error", logger.E(errors.WithStack(revoveredErr)))
|
||||
|
||||
err = errors.WithStack(ErUnknownError)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
panic(recovered)
|
||||
}
|
||||
}()
|
||||
|
||||
jsArgs := make([]goja.Value, 0, len(args))
|
||||
for _, a := range args {
|
||||
jsArgs = append(jsArgs, vm.ToValue(a))
|
||||
@ -54,8 +80,6 @@ func (s *Server) Exec(callable goja.Callable, args ...interface{}) (goja.Value,
|
||||
if err != nil {
|
||||
err = errors.WithStack(err)
|
||||
}
|
||||
|
||||
wg.Done()
|
||||
})
|
||||
|
||||
wg.Wait()
|
||||
|
Reference in New Issue
Block a user