Skip to content

Commit 04c526f

Browse files
authored
fix: don't share a base env across all executions (#7)
1 parent 6d64283 commit 04c526f

File tree

3 files changed

+34
-3
lines changed

3 files changed

+34
-3
lines changed

callable_test.go

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,18 @@ package jsonata
66

77
import (
88
"errors"
9+
"fmt"
910
"math"
1011
"reflect"
1112
"regexp"
1213
"sort"
1314
"strings"
15+
"sync"
1416
"testing"
1517

1618
"github.com/stepzen-dev/jsonata-go/jparse"
1719
"github.com/stepzen-dev/jsonata-go/jtypes"
20+
"github.com/stretchr/testify/assert"
1821
)
1922

2023
var (
@@ -2761,3 +2764,29 @@ func TestCallableParamCount(t *testing.T) {
27612764
}
27622765
}
27632766
}
2767+
2768+
func TestConcurrentGoCallable(t *testing.T) {
2769+
const src = `$contains(/^DEF-/)`
2770+
n := 100
2771+
var wg sync.WaitGroup
2772+
for i := 0; i < n; i++ {
2773+
id := fmt.Sprintf("ABC-%d", i)
2774+
if i%3 == 0 {
2775+
id = fmt.Sprintf("DEF-%d", i)
2776+
}
2777+
2778+
wg.Add(1)
2779+
go func() {
2780+
defer wg.Done()
2781+
result, err := MustCompile(src).Eval(id)
2782+
assert.NoError(t, err)
2783+
2784+
if strings.HasPrefix(id, "DEF-") {
2785+
assert.Equal(t, true, result)
2786+
} else {
2787+
assert.Equal(t, false, result)
2788+
}
2789+
}()
2790+
}
2791+
wg.Wait()
2792+
}

env.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ var (
6565
argCountEquals1 = jtypes.ArgCountEquals(1)
6666
)
6767

68-
var baseEnv = initBaseEnv(map[string]Extension{
68+
var standardFunctions = map[string]Extension{
6969

7070
// String functions
7171

@@ -385,7 +385,7 @@ var baseEnv = initBaseEnv(map[string]Extension{
385385
UndefinedHandler: nil,
386386
EvalContextHandler: nil,
387387
},
388-
})
388+
}
389389

390390
func initBaseEnv(exts map[string]Extension) *environment {
391391

jsonata.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,9 @@ func (e *Expr) newEnv(input reflect.Value) *environment {
232232

233233
tc := timeCallables(time.Now())
234234

235-
env := newEnvironment(baseEnv, len(tc)+len(e.registry)+1)
235+
// create a new base environment (with the standard functions) to
236+
// ensure each execution gets its own set of goCallables for functions.
237+
env := newEnvironment(initBaseEnv(standardFunctions), len(tc)+len(e.registry)+1)
236238

237239
env.bind("$", input)
238240
env.bindAll(tc)

0 commit comments

Comments
 (0)