Skip to content

Commit

Permalink
enhancement: Ability to set gRPC stats handler (#17)
Browse files Browse the repository at this point in the history
Otel library has finally moved to using `stats.Handler` to record gRPC
traces and metrics. This means that we need a way for users to set a
`stats.Handler` on the connection established by the Cerbos client.

Signed-off-by: Charith Ellawala <[email protected]>

---------

Signed-off-by: Charith Ellawala <[email protected]>
  • Loading branch information
charithe authored Nov 13, 2023
1 parent 04bf051 commit f881af4
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions cerbos/grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,22 +12,25 @@ import (
"os"
"time"

effectv1 "github.com/cerbos/cerbos/api/genpb/cerbos/effect/v1"
enginev1 "github.com/cerbos/cerbos/api/genpb/cerbos/engine/v1"
requestv1 "github.com/cerbos/cerbos/api/genpb/cerbos/request/v1"
svcv1 "github.com/cerbos/cerbos/api/genpb/cerbos/svc/v1"
grpc_retry "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/retry"
"github.com/rs/xid"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/stats"

effectv1 "github.com/cerbos/cerbos/api/genpb/cerbos/effect/v1"
enginev1 "github.com/cerbos/cerbos/api/genpb/cerbos/engine/v1"
requestv1 "github.com/cerbos/cerbos/api/genpb/cerbos/request/v1"
svcv1 "github.com/cerbos/cerbos/api/genpb/cerbos/svc/v1"

"github.com/cerbos/cerbos-sdk-go/internal"
)

var _ Client[*GRPCClient, PrincipalCtx] = (*GRPCClient)(nil)

type config struct {
statsHandler stats.Handler
address string
tlsAuthority string
tlsCACert string
Expand Down Expand Up @@ -133,6 +136,13 @@ func WithUnaryInterceptors(interceptors ...grpc.UnaryClientInterceptor) Opt {
}
}

// WithStatsHandler sets the gRPC stats handler for the connection.
func WithStatsHandler(handler stats.Handler) Opt {
return func(c *config) {
c.statsHandler = handler
}
}

// New creates a new Cerbos client.
func New(address string, opts ...Opt) (*GRPCClient, error) {
grpcConn, _, err := mkConn(address, opts...)
Expand Down Expand Up @@ -172,6 +182,10 @@ func mkConn(address string, opts ...Opt) (*grpc.ClientConn, *config, error) {
func mkDialOpts(conf *config) ([]grpc.DialOption, error) {
dialOpts := []grpc.DialOption{grpc.WithUserAgent(conf.userAgent)}

if conf.statsHandler != nil {
dialOpts = append(dialOpts, grpc.WithStatsHandler(conf.statsHandler))
}

if conf.connectTimeout > 0 {
dialOpts = append(dialOpts, grpc.WithConnectParams(grpc.ConnectParams{MinConnectTimeout: conf.connectTimeout}))
}
Expand Down

0 comments on commit f881af4

Please sign in to comment.