github.com/hyperledger-labs/bdls@v2.1.1+incompatible/core/chaincode/accesscontrol/interceptor.go (about)

     1  /*
     2  Copyright IBM Corp. All Rights Reserved.
     3  
     4  SPDX-License-Identifier: Apache-2.0
     5  */
     6  
     7  package accesscontrol
     8  
     9  import (
    10  	"fmt"
    11  
    12  	pb "github.com/hyperledger/fabric-protos-go/peer"
    13  	"google.golang.org/grpc"
    14  )
    15  
    16  type interceptor struct {
    17  	next pb.ChaincodeSupportServer
    18  	auth authorization
    19  }
    20  
    21  // ChaincodeStream defines a gRPC stream for sending
    22  // and receiving chaincode messages
    23  type ChaincodeStream interface {
    24  	// Send sends a chaincode message
    25  	Send(*pb.ChaincodeMessage) error
    26  	// Recv receives a chaincode message
    27  	Recv() (*pb.ChaincodeMessage, error)
    28  }
    29  
    30  type authorization func(message *pb.ChaincodeMessage, stream grpc.ServerStream) error
    31  
    32  func newInterceptor(srv pb.ChaincodeSupportServer, auth authorization) pb.ChaincodeSupportServer {
    33  	return &interceptor{
    34  		next: srv,
    35  		auth: auth,
    36  	}
    37  }
    38  
    39  // Register makes the interceptor implement ChaincodeSupportServer
    40  func (i *interceptor) Register(stream pb.ChaincodeSupport_RegisterServer) error {
    41  	is := &interceptedStream{
    42  		incMessages:  make(chan *pb.ChaincodeMessage, 1),
    43  		stream:       stream,
    44  		ServerStream: stream,
    45  		auth:         i.auth,
    46  	}
    47  	msg, err := stream.Recv()
    48  	if err != nil {
    49  		return fmt.Errorf("Recv() error: %v, closing connection", err)
    50  	}
    51  	err = is.auth(msg, is.ServerStream)
    52  	if err != nil {
    53  		return err
    54  	}
    55  	is.incMessages <- msg
    56  	close(is.incMessages)
    57  	return i.next.Register(is)
    58  }
    59  
    60  type interceptedStream struct {
    61  	incMessages chan *pb.ChaincodeMessage
    62  	stream      ChaincodeStream
    63  	grpc.ServerStream
    64  	auth authorization
    65  }
    66  
    67  // Send sends a chaincode message
    68  func (is *interceptedStream) Send(msg *pb.ChaincodeMessage) error {
    69  	return is.stream.Send(msg)
    70  }
    71  
    72  // Recv receives a chaincode message
    73  func (is *interceptedStream) Recv() (*pb.ChaincodeMessage, error) {
    74  	msg, ok := <-is.incMessages
    75  	if !ok {
    76  		return is.stream.Recv()
    77  	}
    78  	return msg, nil
    79  }