github.com/badrootd/nibiru-cometbft@v0.37.5-0.20240307173500-2a75559eee9b/abci/server/grpc_server.go (about)

     1  package server
     2  
     3  import (
     4  	"net"
     5  
     6  	"google.golang.org/grpc"
     7  
     8  	"github.com/badrootd/nibiru-cometbft/abci/types"
     9  	cmtnet "github.com/badrootd/nibiru-cometbft/libs/net"
    10  	"github.com/badrootd/nibiru-cometbft/libs/service"
    11  )
    12  
    13  type GRPCServer struct {
    14  	service.BaseService
    15  
    16  	proto    string
    17  	addr     string
    18  	listener net.Listener
    19  	server   *grpc.Server
    20  
    21  	app types.ABCIApplicationServer
    22  }
    23  
    24  // NewGRPCServer returns a new gRPC ABCI server
    25  func NewGRPCServer(protoAddr string, app types.ABCIApplicationServer) service.Service {
    26  	proto, addr := cmtnet.ProtocolAndAddress(protoAddr)
    27  	s := &GRPCServer{
    28  		proto:    proto,
    29  		addr:     addr,
    30  		listener: nil,
    31  		app:      app,
    32  	}
    33  	s.BaseService = *service.NewBaseService(nil, "ABCIServer", s)
    34  	return s
    35  }
    36  
    37  // OnStart starts the gRPC service.
    38  func (s *GRPCServer) OnStart() error {
    39  
    40  	ln, err := net.Listen(s.proto, s.addr)
    41  	if err != nil {
    42  		return err
    43  	}
    44  
    45  	s.listener = ln
    46  	s.server = grpc.NewServer()
    47  	types.RegisterABCIApplicationServer(s.server, s.app)
    48  
    49  	s.Logger.Info("Listening", "proto", s.proto, "addr", s.addr)
    50  	go func() {
    51  		if err := s.server.Serve(s.listener); err != nil {
    52  			s.Logger.Error("Error serving gRPC server", "err", err)
    53  		}
    54  	}()
    55  	return nil
    56  }
    57  
    58  // OnStop stops the gRPC server.
    59  func (s *GRPCServer) OnStop() {
    60  	s.server.Stop()
    61  }