Skip to content

Commit

Permalink
chore: refactor protobuf generation, add health check.
Browse files Browse the repository at this point in the history
  • Loading branch information
grantlerduck committed Aug 25, 2024
1 parent 323191d commit cf063c3
Show file tree
Hide file tree
Showing 20 changed files with 2,175 additions and 1,403 deletions.
31 changes: 31 additions & 0 deletions adapters/rpc/health_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package rpc

import (
"context"

"google.golang.org/grpc/status"
"google.golang.org/grpc/codes"

health_v1 "github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/api/gen/v1/health"
)

type HealthRpcService struct {
health_v1.UnimplementedHealthServiceServer
serverHealthy bool
}

func (hrs *HealthRpcService) HealthCheck(
ctx context.Context,
request *health_v1.HealthCheckRequest,
) (*health_v1.HealthCheckResponse, error) {
if hrs.serverHealthy {
return &health_v1.HealthCheckResponse{
Status: health_v1.HealthCheckResponse_SERVING_STATUS_SERVING,
}, nil
}
return nil, status.Errorf(codes.Unavailable, "endpoints not available")
}

func (hrs *HealthRpcService) healthy(healthy bool) {
hrs.serverHealthy = healthy
}
28 changes: 14 additions & 14 deletions adapters/rpc/poi_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,18 +11,18 @@ import (
"google.golang.org/grpc/metadata"
status "google.golang.org/grpc/status"

v1 "github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/api/gen/v1"
poi_v1 "github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/api/gen/v1/poi"
)

type PoIRpcService struct {
v1.UnimplementedPoIServiceServer
poi_v1.UnimplementedPoIServiceServer
logger *zap.Logger
}

func (prs *PoIRpcService) PoI(
ctx context.Context,
request *v1.PoIRequest,
) (*v1.PoIResponse, error) {
request *poi_v1.PoIRequest,
) (*poi_v1.PoIResponse, error) {
id, err := prs.getCorrelationId(ctx)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "Header X-Correlation-Id not found")
Expand All @@ -31,11 +31,11 @@ func (prs *PoIRpcService) PoI(
"processing PoI rpc, returning fixture",
zap.String("X-Correlation-Id", id.String()),
)
return &v1.PoIResponse{
Poi: &v1.PoI{
return &poi_v1.PoIResponse{
Poi: &poi_v1.PoI{
Id: ksuid.New().String(),
Coordinate: &v1.Coordinate{Lat: 48.137, Lon: 11.576},
Address: &v1.Address{
Coordinate: &poi_v1.Coordinate{Lat: 48.137, Lon: 11.576},
Address: &poi_v1.Address{
Street: "Maximilianstrasse",
StreetNumber: "1b",
ZipCode: "123456",
Expand All @@ -48,22 +48,22 @@ func (prs *PoIRpcService) PoI(

func (prs *PoIRpcService) Proximity(
ctex context.Context,
request *v1.ProximityRequest,
) (*v1.ProximityResponse, error) {
request *poi_v1.ProximityRequest,
) (*poi_v1.ProximityResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Proximity not implemented")
}

func (prs *PoIRpcService) BBox(
ctx context.Context,
request *v1.BBoxRequest,
) (*v1.BBoxResponse, error) {
request *poi_v1.BBoxRequest,
) (*poi_v1.BBoxResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BBox not implemented")
}

func (prs *PoIRpcService) Route(
ctx context.Context,
request *v1.RouteRequest,
) (*v1.RouteResponse, error) {
request *poi_v1.RouteRequest,
) (*poi_v1.RouteResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Route not implemented")
}

Expand Down
61 changes: 43 additions & 18 deletions adapters/rpc/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,30 @@ import (
"fmt"
"net"
"net/http"
"time"

grpclogging "github.com/grpc-ecosystem/go-grpc-middleware/v2/interceptors/logging"
"github.com/grpc-ecosystem/grpc-gateway/v2/runtime"
"go.uber.org/zap"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"

v1 "github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/api/gen/v1"
"github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/app"
health_v1 "github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/api/gen/v1/health"
poi_v1 "github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/api/gen/v1/poi"
"github.com/grntlrduck-cloud/go-grpc-geohasing-service-sample/app"
)

type Server struct {
prs *PoIRpcService
hrs *HealthRpcService
rpcServer *grpc.Server
logger *zap.Logger
}

type NewServerProps struct {
Logger *zap.Logger
Ctx context.Context
Conf app.ServerConfig
Logger *zap.Logger
Ctx context.Context
Conf app.ServerConfig
}

type startHttpProxyProps struct {
Expand All @@ -37,11 +40,15 @@ type startHttpProxyProps struct {

type startRpcServerResult struct {
rpcServer *grpc.Server
hrs *HealthRpcService
prs *PoIRpcService
err error
}

func (s *Server) Stop() {
s.hrs.healthy(false)
s.logger.Info("set health endpoint to NOT_SERVING")
time.Sleep(1 * time.Second)
s.rpcServer.GracefulStop()
s.logger.Info("stopped gRPC server gracefully")
}
Expand Down Expand Up @@ -69,38 +76,40 @@ func NewServer(props NewServerProps) (*Server, error) {
res.rpcServer.GracefulStop()
return nil, err
}
props.Logger.Info("setting endpoints to SERVING")
res.hrs.healthy(true)

props.Logger.Info("finished initializing server")
return &Server{prs: res.prs, rpcServer: res.rpcServer, logger: props.Logger}, nil
return &Server{hrs: res.hrs, prs: res.prs, rpcServer: res.rpcServer, logger: props.Logger}, nil
}

func startRpcServer(logger *zap.Logger, endpoint string) *startRpcServerResult {
logger.Info("starting gRPC server")
lis, err := net.Listen("tcp", endpoint)
if err != nil {
logger.Error("failed to listen to port")
return &startRpcServerResult{nil, nil, err}
}
grpcOpts := []grpclogging.Option{
grpclogging.WithLogOnEvents(grpclogging.StartCall, grpclogging.FinishCall),
return &startRpcServerResult{nil, nil, nil, err}
}
server := grpc.NewServer(
grpc.ChainUnaryInterceptor(
grpclogging.UnaryServerInterceptor(InterceptorLogger(logger), grpcOpts...),
grpclogging.UnaryServerInterceptor(InterceptorLogger(logger)),
),
grpc.ChainStreamInterceptor(
grpclogging.StreamServerInterceptor(InterceptorLogger(logger), grpcOpts...),
grpclogging.StreamServerInterceptor(InterceptorLogger(logger)),
),
)
hrs := &HealthRpcService{}
health_v1.RegisterHealthServiceServer(server, hrs)
hrs.healthy(false)
prs := &PoIRpcService{logger: logger}
v1.RegisterPoIServiceServer(server, prs)
poi_v1.RegisterPoIServiceServer(server, prs)
go func() {
servErr := server.Serve(lis)
if servErr != nil {
logger.Panic("failed to start rpc server")
}
}()
return &startRpcServerResult{server, prs, nil}
return &startRpcServerResult{server, hrs, prs, nil}
}

// https://github.com/grpc-ecosystem/go-grpc-middleware/blob/main/interceptors/logging/examples/zap/example_test.go
Expand Down Expand Up @@ -131,7 +140,7 @@ func InterceptorLogger(l *zap.Logger) grpclogging.Logger {
case grpclogging.LevelDebug:
logger.Debug(msg)
case grpclogging.LevelInfo:
logger.Info(msg)
logger.Debug(msg)
case grpclogging.LevelWarn:
logger.Warn(msg)
case grpclogging.LevelError:
Expand All @@ -148,10 +157,26 @@ func startHttProxy(props startHttpProxyProps) error {
mux := runtime.NewServeMux(
runtime.WithIncomingHeaderMatcher(CustomMatcher),
)
opts := []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
err := v1.RegisterPoIServiceHandlerFromEndpoint(props.ctx, mux, props.rpcEndpoint, opts)
opts := []grpc.DialOption{
// TODO: configure security based on props
grpc.WithTransportCredentials(insecure.NewCredentials()),
// use zap logger for handlers
grpc.WithChainUnaryInterceptor(grpclogging.UnaryClientInterceptor(InterceptorLogger(props.logger))),
grpc.WithChainStreamInterceptor(grpclogging.StreamClientInterceptor(InterceptorLogger(props.logger))),
}
err := poi_v1.RegisterPoIServiceHandlerFromEndpoint(props.ctx, mux, props.rpcEndpoint, opts)
if err != nil {
props.logger.Error("failed to register http revers proxy handler for poi service")
return err
}
err = health_v1.RegisterHealthServiceHandlerFromEndpoint(
props.ctx,
mux,
props.rpcEndpoint,
opts,
)
if err != nil {
props.logger.Error("failed to register http revers proxy handler")
props.logger.Error("failed to register http revers proxy handler for health service")
return err
}
// Start HTTP server (and proxy calls to gRPC server endpoint)
Expand Down
Loading

0 comments on commit cf063c3

Please sign in to comment.