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 Apr 4, 2024
1 parent 1d36885 commit c3942bc
Show file tree
Hide file tree
Showing 2 changed files with 72 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
53 changes: 53 additions & 0 deletions act/policy_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
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{})
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{})
ctx, cancel := context.WithTimeout(context.Background(), 10)
defer cancel()
_, err := policy.Eval(ctx, Input{})
require.Error(t, err)
})

t.Run("it should fail because of runtime error", func(t *testing.T) {
policy := MustNewPolicy("test", `nonExistantVariable`, map[string]any{})
_, err := policy.Eval(context.Background(), Input{
Policy: map[string]any{"key": "value"},
})
require.ErrorIs(t, err, context.DeadlineExceeded)
})
}

func TestPolicy_MustCompile(t *testing.T) {
t.Run("it should compile policy correctly", func(t *testing.T) {
policy := Policy{
Name: "test",
Policy: "1 + 1",
Metadata: map[string]any{"log": "enabled"},
}
require.NoError(t, policy.MustCompile())
})

t.Run("it should fail to compile policy if there is an error", func(t *testing.T) {
policy := Policy{
Name: "test",
Policy: "1 + \"Hi\"",
Metadata: map[string]any{"log": "enabled"},
}
require.Error(t, policy.MustCompile())
})
}

0 comments on commit c3942bc

Please sign in to comment.