Skip to content

Commit 117ac00

Browse files
committed
jsfilter: parallelize startup of VMs
1 parent e9de78b commit 117ac00

File tree

1 file changed

+39
-29
lines changed

1 file changed

+39
-29
lines changed

access/jsfilter.go

Lines changed: 39 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"os"
99

1010
"github.com/dop251/goja"
11+
"golang.org/x/sync/errgroup"
1112

1213
"github.com/SenseUnit/dumbproxy/jsext"
1314
clog "github.com/SenseUnit/dumbproxy/log"
@@ -32,39 +33,48 @@ func NewJSFilter(filename string, instances int, logger *clog.CondLogger, next F
3233

3334
instances = max(1, instances)
3435
pool := make(chan JSFilterFunc, instances)
36+
initGroup, _ := errgroup.WithContext(context.Background())
3537

3638
for i := 0; i < instances; i++ {
37-
vm := goja.New()
38-
err = jsext.AddPrinter(vm, logger)
39-
if err != nil {
40-
return nil, fmt.Errorf("can't add print function to runtime: %w", err)
41-
}
42-
err = jsext.ConfigureRuntime(vm)
43-
if err != nil {
44-
return nil, fmt.Errorf("can't configure runtime: %w", err)
45-
}
46-
vm.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
47-
_, err = vm.RunString(string(script))
48-
if err != nil {
49-
return nil, fmt.Errorf("script run failed: %w", err)
50-
}
39+
initGroup.Go(func() error {
40+
vm := goja.New()
41+
err := jsext.AddPrinter(vm, logger)
42+
if err != nil {
43+
return fmt.Errorf("can't add print function to runtime: %w", err)
44+
}
45+
err = jsext.ConfigureRuntime(vm)
46+
if err != nil {
47+
return fmt.Errorf("can't configure runtime: %w", err)
48+
}
49+
vm.SetFieldNameMapper(goja.TagFieldNameMapper("json", true))
50+
_, err = vm.RunString(string(script))
51+
if err != nil {
52+
return fmt.Errorf("script run failed: %w", err)
53+
}
5154

52-
var f JSFilterFunc
53-
var accessFnJSVal goja.Value
54-
if ex := vm.Try(func() {
55-
accessFnJSVal = vm.Get("access")
56-
}); ex != nil {
57-
return nil, fmt.Errorf("\"access\" function cannot be located in VM context: %w", err)
58-
}
59-
if accessFnJSVal == nil {
60-
return nil, errors.New("\"access\" function is not defined")
61-
}
62-
err = vm.ExportTo(accessFnJSVal, &f)
63-
if err != nil {
64-
return nil, fmt.Errorf("can't export \"access\" function from JS VM: %w", err)
65-
}
55+
var f JSFilterFunc
56+
var accessFnJSVal goja.Value
57+
if ex := vm.Try(func() {
58+
accessFnJSVal = vm.Get("access")
59+
}); ex != nil {
60+
return fmt.Errorf("\"access\" function cannot be located in VM context: %w", err)
61+
}
62+
if accessFnJSVal == nil {
63+
return errors.New("\"access\" function is not defined")
64+
}
65+
err = vm.ExportTo(accessFnJSVal, &f)
66+
if err != nil {
67+
return fmt.Errorf("can't export \"access\" function from JS VM: %w", err)
68+
}
6669

67-
pool <- f
70+
pool <- f
71+
return nil
72+
})
73+
}
74+
75+
err = initGroup.Wait()
76+
if err != nil {
77+
return nil, err
6878
}
6979

7080
return &JSFilter{

0 commit comments

Comments
 (0)