88 lines
2.6 KiB
Go
88 lines
2.6 KiB
Go
package grpcserver
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
|
|
"git.coopgo.io/coopgo-platform/multimodal-routing/handlers"
|
|
"git.coopgo.io/coopgo-platform/multimodal-routing/servers/grpc/proto"
|
|
"github.com/paulmach/orb/geojson"
|
|
"github.com/rs/zerolog/log"
|
|
"github.com/spf13/viper"
|
|
"google.golang.org/grpc"
|
|
"google.golang.org/grpc/codes"
|
|
"google.golang.org/grpc/reflection"
|
|
"google.golang.org/grpc/status"
|
|
)
|
|
|
|
type MultimodalRoutingServer struct {
|
|
Handler *handlers.MultimodalRoutingHandler
|
|
|
|
proto.UnimplementedMultimodalRoutingServer
|
|
}
|
|
|
|
func NewMultimodalRoutingServer(handler *handlers.MultimodalRoutingHandler) *MultimodalRoutingServer {
|
|
return &MultimodalRoutingServer{
|
|
Handler: handler,
|
|
}
|
|
}
|
|
|
|
func (s *MultimodalRoutingServer) Search(ctx context.Context, req *proto.SearchRequest) (*proto.SearchResponse, error) {
|
|
departure, err := geojson.UnmarshalFeature([]byte(req.Departure.Serialized))
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("error decoding departure")
|
|
return nil, status.Errorf(codes.Internal, "could not read departure: %w", err)
|
|
}
|
|
destination, err := geojson.UnmarshalFeature([]byte(req.Destination.Serialized))
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("error decoding destination")
|
|
return nil, status.Errorf(codes.Internal, "could not read destination: %w", err)
|
|
}
|
|
departureDate := req.DepartureDate.AsTime()
|
|
journeys, err := s.Handler.Search(*departure, *destination, departureDate)
|
|
if err != nil {
|
|
log.Error().Err(err).Any("departure", departure).Any("destination", destination).Time("departure date", departureDate).Msg("error retrieving carpools")
|
|
}
|
|
|
|
results := []*proto.FeatureCollection{}
|
|
for _, c := range journeys {
|
|
serialized, err := c.MarshalJSON()
|
|
if err != nil {
|
|
log.Error().Err(err).Any("carpool object", c).Msg("could not serialize carpool response")
|
|
continue
|
|
}
|
|
results = append(results, &proto.FeatureCollection{Serialized: string(serialized)})
|
|
}
|
|
|
|
return &proto.SearchResponse{
|
|
Results: results,
|
|
}, nil
|
|
}
|
|
|
|
func Run(failed chan error, cfg *viper.Viper, handler *handlers.MultimodalRoutingHandler) {
|
|
var (
|
|
dev_env = cfg.GetBool("dev_env")
|
|
address = fmt.Sprintf(":%s", cfg.GetString("services.grpc.port"))
|
|
)
|
|
|
|
server := grpc.NewServer()
|
|
|
|
proto.RegisterMultimodalRoutingServer(server, NewMultimodalRoutingServer(handler))
|
|
l, err := net.Listen("tcp", address)
|
|
if err != nil {
|
|
failed <- fmt.Errorf("error trying to listen to network port : %w", err)
|
|
return
|
|
}
|
|
|
|
if dev_env {
|
|
log.Info().Msg("gRPC server reflexion activated")
|
|
reflection.Register(server)
|
|
}
|
|
|
|
log.Info().Str("address", address).Msg("running gRPC server")
|
|
if err := server.Serve(l); err != nil {
|
|
failed <- fmt.Errorf("error in grpc server : %w", err)
|
|
}
|
|
}
|