Skip to content

Commit

Permalink
fix: Stop policy eval when context is done
Browse files Browse the repository at this point in the history
  • Loading branch information
Hamsajj committed Mar 29, 2024
1 parent 1d36885 commit 4d4ba5d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 5 deletions.
24 changes: 19 additions & 5 deletions act/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,26 @@ func (p *Policy) MustCompile(extraOpts ...expr.Option) error {
}

func (p *Policy) Eval(ctx context.Context, input Input) (any, error) {
output, err := expr.Run(p.prg, input)
if err != nil {
return false, err
result := make(chan interface{})
errChan := make(chan error)

go func() {
output, err := expr.Run(p.prg, input)
if err != nil {
errChan <- err
return
}
result <- output
}()

select {
case <-ctx.Done():
return nil, ctx.Err()
case out := <-result:
return out, nil
case err := <-errChan:
return nil, err
}

return output, nil
}

func MustNewPolicy(
Expand Down
26 changes: 26 additions & 0 deletions act/policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package act

import (
"context"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)

func TestPolicy_Eval(t *testing.T) {

t.Run("it should eval program correctly", func(t *testing.T) {
policy := MustNewPolicy("test", "1 + 1", map[string]any{"log": "enabled"})
resp, err := policy.Eval(context.Background(), Input{})
require.NoError(t, err)
assert.Equal(t, 2, resp)
})

t.Run("it should stop eval if context is timed out", func(t *testing.T) {
policy := MustNewPolicy("test", "repeat(\"Hi\", 100000)", map[string]any{"log": "enabled"})
ctx, cancel := context.WithTimeout(context.Background(), 10)
defer cancel()
_, err := policy.Eval(ctx, Input{})
require.ErrorIs(t, err, context.DeadlineExceeded)
})
}

0 comments on commit 4d4ba5d

Please sign in to comment.