Skip to content

Commit

Permalink
server: make ConnectCallback take a context instead
Browse files Browse the repository at this point in the history
This makes the WithConnectCallback option for the server take a context
as its input instead of the rpc metadata. To obtain the metadata, the
callback function can extract it from the context.
  • Loading branch information
johningve committed Mar 4, 2022
1 parent e60f9a9 commit b131572
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 9 deletions.
13 changes: 5 additions & 8 deletions server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"github.com/relab/gorums/ordering"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/reflect/protoreflect"
)
Expand Down Expand Up @@ -65,8 +64,7 @@ func (s *orderingServer) NodeStream(srv ordering.Gorums_NodeStreamServer) error
ctx := srv.Context()

if s.opts.connectCallback != nil {
md, _ := metadata.FromIncomingContext(ctx)
s.opts.connectCallback(md)
s.opts.connectCallback(ctx)
}

go func() {
Expand Down Expand Up @@ -107,7 +105,7 @@ func (s *orderingServer) NodeStream(srv ordering.Gorums_NodeStreamServer) error
type serverOptions struct {
buffer uint
grpcOpts []grpc.ServerOption
connectCallback func(metadata.MD)
connectCallback func(context.Context)
}

// ServerOption is used to change settings for the GorumsServer
Expand All @@ -130,10 +128,9 @@ func WithGRPCServerOptions(opts ...grpc.ServerOption) ServerOption {

// WithConnectCallback registers a callback function that will be called by the server
// whenever a node connects or reconnects to the server. This allows access to the node's
// connection metadata, which is passed to the callback function.
//
// NOTE: if there is no metadata present, the metadata parameter will be nil.
func WithConnectCallback(callback func(metadata.MD)) ServerOption {
// stream context, which is passed to the callback function. The stream context can be
// used to extract the metadata and peer information, if available.
func WithConnectCallback(callback func(context.Context)) ServerOption {
return func(so *serverOptions) {
so.connectCallback = callback
}
Expand Down
7 changes: 6 additions & 1 deletion server_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gorums_test

import (
"context"
"net"
"testing"
"time"
Expand All @@ -15,7 +16,11 @@ func TestServerCallback(t *testing.T) {
var message string
signal := make(chan struct{})

srv := gorums.NewServer(gorums.WithConnectCallback(func(m metadata.MD) {
srv := gorums.NewServer(gorums.WithConnectCallback(func(ctx context.Context) {
m, ok := metadata.FromIncomingContext(ctx)
if !ok {
return
}
message = m.Get("message")[0]
signal <- struct{}{}
}))
Expand Down

0 comments on commit b131572

Please sign in to comment.