Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions cue/cuex/runtime/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import (
"sync"

"cuelang.org/go/cue"
"cuelang.org/go/cue/ast"
cuejson "cuelang.org/go/encoding/json"
"k8s.io/apimachinery/pkg/runtime"

"github.com/kubevela/pkg/apis/cue/v1alpha1"
Expand Down Expand Up @@ -329,10 +331,15 @@ func (in *ExternalProviderFn) invoke(ctx context.Context, decoded any) (any, err
default:
return nil, fmt.Errorf("protocol %s not supported yet", in.Protocol)
}
ret := &map[string]any{}
if err := json.Unmarshal(bs, ret); err != nil {
// read by CUE, not encoding/json, so a number keeps its kind and digits:
// 200 is an int, not the float64 that prints as 2E+2
ret, err := cuejson.Extract("reply of "+in.Fn, bs)
if err != nil {
return nil, err
}
if _, ok := ret.(*ast.StructLit); !ok {
return nil, fmt.Errorf("external provider %s returned %s, want a JSON object", in.Fn, bytes.TrimSpace(bs))
}
return map[string]any{providers.ReturnsKey: ret}, nil
}

Expand Down
29 changes: 29 additions & 0 deletions cue/cuex/runtime/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -219,3 +219,32 @@ func TestProviderCustomHeader(t *testing.T) {
_, err := prd.Call(context.Background(), v)
require.NoError(t, err, "call to ExternalProviderFn failed")
}

func TestExternalProviderFnKeepsNumbersAsWritten(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`{"status": 200, "stars": 7926, "ratio": 0.5, "big": 9007199254740993}`))
}))
defer server.Close()
fn := runtime.ExternalProviderFn{Provider: v1alpha1.Provider{Protocol: v1alpha1.ProtocolHTTP, Endpoint: server.URL}}
ctx := cuecontext.New()
call := ctx.CompileString(`{$params: {}, $returns?: {...}}`)
check := func(t *testing.T, out cue.Value) {
text := ctx.CompileString(`r: _, s: "\(r.status) \(r.stars) \(r.ratio) \(r.big)"`).
FillPath(cue.ParsePath("r"), out.LookupPath(cue.ParsePath(providers.ReturnsKey)))
s, err := text.LookupPath(cue.ParsePath("s")).String()
require.NoError(t, err)
require.Equal(t, "200 7926 0.5 9007199254740993", s)
_, err = out.LookupPath(cue.ParsePath(providers.ReturnsKey)).Unify(ctx.CompileString(`{status: int}`)).LookupPath(cue.ParsePath("status")).Int64()
require.NoError(t, err, "an integer in the reply is an int")
}
t.Run("Call", func(t *testing.T) {
out, err := fn.Call(context.Background(), call)
require.NoError(t, err)
check(t, out)
})
t.Run("CallForResult", func(t *testing.T) {
ret, err := fn.CallForResult(context.Background(), call)
require.NoError(t, err)
check(t, call.FillPath(cue.ParsePath(""), ret))
})
}
Loading