Skip to content

Commit

Permalink
Add metadata in binding response even in case of error (#7572)
Browse files Browse the repository at this point in the history
* Add binding metadata even in case of error.

Signed-off-by: Artur Souza <asouza.pro@gmail.com>

* ADD IT.

Signed-off-by: Artur Souza <asouza.pro@gmail.com>

* Fix lint.

Signed-off-by: Artur Souza <asouza.pro@gmail.com>

---------

Signed-off-by: Artur Souza <asouza.pro@gmail.com>
  • Loading branch information
artursouza committed Mar 1, 2024
1 parent 4ad926e commit 3ee7835
Show file tree
Hide file tree
Showing 4 changed files with 122 additions and 4 deletions.
14 changes: 13 additions & 1 deletion pkg/api/grpc/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import (
"golang.org/x/exp/slices"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
grpcMetadata "google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"

Expand Down Expand Up @@ -63,7 +64,10 @@ import (
"github.com/dapr/kit/logger"
)

const daprHTTPStatusHeader = "dapr-http-status"
const (
daprHTTPStatusHeader = "dapr-http-status"
metadataPrefix = "metadata."
)

// API is the gRPC interface for the Dapr gRPC API. It implements both the internal and external proto definitions.
type API interface {
Expand Down Expand Up @@ -495,6 +499,13 @@ func (a *api) InvokeBinding(ctx context.Context, in *runtimev1pb.InvokeBindingRe

diag.DefaultComponentMonitoring.OutputBindingEvent(context.Background(), in.GetName(), in.GetOperation(), err == nil, elapsed)

// Some bindings have metadata in the response even in case of error
if resp != nil {
for k, v := range resp.Metadata {
grpc.SetHeader(ctx, grpcMetadata.Pairs(metadataPrefix+k, v))
}
}

if err != nil {
err = status.Errorf(codes.Internal, messages.ErrInvokeOutputBinding, in.GetName(), err.Error())
apiServerLogger.Debug(err)
Expand All @@ -505,6 +516,7 @@ func (a *api) InvokeBinding(ctx context.Context, in *runtimev1pb.InvokeBindingRe
r.Data = resp.Data
r.Metadata = resp.Metadata
}

return r, nil
}

Expand Down
11 changes: 8 additions & 3 deletions pkg/api/http/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,14 @@ func (a *api) onOutputBindingMessage(reqCtx *fasthttp.RequestCtx) {

diag.DefaultComponentMonitoring.OutputBindingEvent(context.Background(), name, req.Operation, err == nil, elapsed)

if resp != nil {
// Set the metadata in the response even in case of error.
// HTTP binding, for example, returns metadata even for error.
for k, v := range resp.Metadata {
reqCtx.Response.Header.Add(metadataPrefix+k, v)
}
}

if err != nil {
msg := NewErrorResponse("ERR_INVOKE_OUTPUT_BINDING", fmt.Sprintf(messages.ErrInvokeOutputBinding, name, err))
fasthttpRespond(reqCtx, fasthttpResponseWithError(nethttp.StatusInternalServerError, msg))
Expand All @@ -581,9 +589,6 @@ func (a *api) onOutputBindingMessage(reqCtx *fasthttp.RequestCtx) {
if resp == nil {
fasthttpRespond(reqCtx, fasthttpResponseWithEmpty())
} else {
for k, v := range resp.Metadata {
reqCtx.Response.Header.Add(metadataPrefix+k, v)
}
fasthttpRespond(reqCtx, fasthttpResponseWithJSON(nethttp.StatusOK, resp.Data, resp.Metadata))
}
}
Expand Down
1 change: 1 addition & 0 deletions tests/integration/suite/daprd/binding/binding.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,5 @@ package binding

import (
_ "github.com/dapr/dapr/tests/integration/suite/daprd/binding/input"
_ "github.com/dapr/dapr/tests/integration/suite/daprd/binding/output"
)
100 changes: 100 additions & 0 deletions tests/integration/suite/daprd/binding/output/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/*
Copyright 2023 The Dapr Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implieh.
See the License for the specific language governing permissions and
limitations under the License.
*/

package output

import (
"context"
"fmt"
"net/http"
"strings"
"testing"
"time"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"google.golang.org/grpc"
grpcMetadata "google.golang.org/grpc/metadata"

"github.com/dapr/dapr/pkg/proto/runtime/v1"
"github.com/dapr/dapr/tests/integration/framework"
"github.com/dapr/dapr/tests/integration/framework/process/daprd"
prochttp "github.com/dapr/dapr/tests/integration/framework/process/http"
"github.com/dapr/dapr/tests/integration/framework/util"
"github.com/dapr/dapr/tests/integration/suite"
)

func init() {
suite.Register(new(bindingerrors))
}

type bindingerrors struct {
srv *prochttp.HTTP
daprd *daprd.Daprd
}

func (b *bindingerrors) Setup(t *testing.T) []framework.Option {
mux := http.NewServeMux()
mux.HandleFunc("/error_404", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusNotFound)
})

b.srv = prochttp.New(t, prochttp.WithHandler(mux))
b.daprd = daprd.New(t,
daprd.WithResourceFiles(fmt.Sprintf(`apiVersion: dapr.io/v1alpha1
kind: Component
metadata:
name: github-http-binding-404
spec:
type: bindings.http
version: v1
metadata:
- name: url
value: http://127.0.0.1:%d/error_404
`, b.srv.Port())))

return []framework.Option{
framework.WithProcesses(b.srv, b.daprd),
}
}

func (b *bindingerrors) Run(t *testing.T, ctx context.Context) {
b.daprd.WaitUntilRunning(t, ctx)

client := b.daprd.GRPCClient(t, ctx)
httpClient := util.HTTPClient(t)

assert.Eventually(t, func() bool {
reqURL := fmt.Sprintf("http://localhost:%d/v1.0/bindings/github-http-binding-404", b.daprd.HTTPPort())
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, strings.NewReader("{\"operation\":\"get\"}"))
require.NoError(t, err)
resp, err := httpClient.Do(req)
require.NoError(t, err)
defer resp.Body.Close()
return (resp.StatusCode == http.StatusInternalServerError) && (resp.Header.Get("Metadata.statuscode") == "404")
}, time.Second*5, 10*time.Millisecond)

assert.Eventually(t, func() bool {
req := runtime.InvokeBindingRequest{
Name: "github-http-binding-404",
Operation: "get",
}
var header grpcMetadata.MD
resp, err := client.InvokeBinding(ctx, &req, grpc.Header(&header))
require.Error(t, err)
require.Nil(t, resp)
statusCodeArr := header.Get("metadata.statuscode")
require.Len(t, statusCodeArr, 1)
return statusCodeArr[0] == "404"
}, time.Second*5, 10*time.Millisecond)
}

0 comments on commit 3ee7835

Please sign in to comment.