88 "os"
99
1010 "github.com/dop251/goja"
11+ "golang.org/x/sync/errgroup"
1112
1213 "github.com/SenseUnit/dumbproxy/dialer/dto"
1314 "github.com/SenseUnit/dumbproxy/jsext"
@@ -30,39 +31,48 @@ func NewJSRouter(filename string, instances int, factory func(string) (Dialer, e
3031
3132 instances = max (1 , instances )
3233 pool := make (chan JSRouterFunc , instances )
34+ initGroup , _ := errgroup .WithContext (context .Background ())
3335
3436 for i := 0 ; i < instances ; i ++ {
35- vm := goja .New ()
36- err := jsext .AddPrinter (vm , logger )
37- if err != nil {
38- return nil , fmt .Errorf ("can't add print function to runtime: %w" , err )
39- }
40- err = jsext .ConfigureRuntime (vm )
41- if err != nil {
42- return nil , fmt .Errorf ("can't configure runtime runtime: %w" , err )
43- }
44- vm .SetFieldNameMapper (goja .TagFieldNameMapper ("json" , true ))
45- _ , err = vm .RunString (string (script ))
46- if err != nil {
47- return nil , fmt .Errorf ("script run failed: %w" , err )
48- }
49-
50- var f JSRouterFunc
51- var routerFnJSVal goja.Value
52- if ex := vm .Try (func () {
53- routerFnJSVal = vm .Get ("getProxy" )
54- }); ex != nil {
55- return nil , fmt .Errorf ("\" getProxy\" function cannot be located in VM context: %w" , err )
56- }
57- if routerFnJSVal == nil {
58- return nil , errors .New ("\" getProxy\" function is not defined" )
59- }
60- err = vm .ExportTo (routerFnJSVal , & f )
61- if err != nil {
62- return nil , fmt .Errorf ("can't export \" getProxy\" function from JS VM: %w" , err )
63- }
64-
65- pool <- f
37+ initGroup .Go (func () error {
38+ vm := goja .New ()
39+ err := jsext .AddPrinter (vm , logger )
40+ if err != nil {
41+ return fmt .Errorf ("can't add print function to runtime: %w" , err )
42+ }
43+ err = jsext .ConfigureRuntime (vm )
44+ if err != nil {
45+ return fmt .Errorf ("can't configure runtime runtime: %w" , err )
46+ }
47+ vm .SetFieldNameMapper (goja .TagFieldNameMapper ("json" , true ))
48+ _ , err = vm .RunString (string (script ))
49+ if err != nil {
50+ return fmt .Errorf ("script run failed: %w" , err )
51+ }
52+
53+ var f JSRouterFunc
54+ var routerFnJSVal goja.Value
55+ if ex := vm .Try (func () {
56+ routerFnJSVal = vm .Get ("getProxy" )
57+ }); ex != nil {
58+ return fmt .Errorf ("\" getProxy\" function cannot be located in VM context: %w" , err )
59+ }
60+ if routerFnJSVal == nil {
61+ return errors .New ("\" getProxy\" function is not defined" )
62+ }
63+ err = vm .ExportTo (routerFnJSVal , & f )
64+ if err != nil {
65+ return fmt .Errorf ("can't export \" getProxy\" function from JS VM: %w" , err )
66+ }
67+
68+ pool <- f
69+ return nil
70+ })
71+ }
72+
73+ err = initGroup .Wait ()
74+ if err != nil {
75+ return nil , err
6676 }
6777
6878 return & JSRouter {
0 commit comments