Skip to content

Commit

Permalink
Merge pull request #11 from isd-sgcu/feature/grpc-server
Browse files Browse the repository at this point in the history
Feature/grpc server
  • Loading branch information
bookpanda authored Dec 28, 2023
2 parents e759eab + d6ded3d commit c9989d9
Show file tree
Hide file tree
Showing 12 changed files with 200 additions and 25 deletions.
3 changes: 3 additions & 0 deletions config/config.example.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ database:
name: johnjud_db
username: root
password: root

service:
file: localhost:3004
2 changes: 1 addition & 1 deletion docker-compose.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ services:
volumes:
- postgres:/var/lib/postgresql/data
ports:
- "5433:5432"
- "5432:5432"

volumes:
postgres:
14 changes: 2 additions & 12 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ toolchain go1.21.5
require (
github.com/bxcodec/faker/v3 v3.8.1
github.com/google/uuid v1.5.0
github.com/isd-sgcu/johnjud-go-proto v0.0.8
github.com/isd-sgcu/johnjud-go-proto v0.0.9
github.com/pkg/errors v0.9.1
github.com/rs/zerolog v1.31.0
github.com/spf13/viper v1.18.2
Expand All @@ -26,43 +26,33 @@ require (
github.com/stretchr/objx v0.5.0 // indirect
golang.org/x/net v0.19.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f // indirect
google.golang.org/protobuf v1.31.0 // indirect
google.golang.org/protobuf v1.32.0 // indirect
)

require (
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/golang/protobuf v1.5.3 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/isd-sgcu/johnjud-go-proto v0.0.8
github.com/jackc/pgpassfile v1.0.0 // indirect
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect
github.com/jackc/pgx/v5 v5.4.3 // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.5 // indirect
github.com/magiconair/properties v1.8.7 // indirect
github.com/mattn/go-colorable v0.1.13 // indirect
github.com/mattn/go-isatty v0.0.19 // indirect
github.com/mitchellh/mapstructure v1.5.0 // indirect
github.com/pelletier/go-toml/v2 v2.1.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/sagikazarmark/locafero v0.4.0 // indirect
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
github.com/sourcegraph/conc v0.3.0 // indirect
github.com/spf13/afero v1.11.0 // indirect
github.com/spf13/cast v1.6.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/stretchr/testify v1.8.4
github.com/stretchr/objx v0.5.0 // indirect
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/atomic v1.9.0 // indirect
go.uber.org/multierr v1.9.0 // indirect
golang.org/x/crypto v0.16.0 // indirect
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20231120223509-83a465c0220f // indirect
google.golang.org/protobuf v1.31.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
4 changes: 4 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/isd-sgcu/johnjud-go-proto v0.0.8 h1:nIQBZgK2OFVrLjVtpeDgwows8poA7LhsIVE4hlbBC1o=
github.com/isd-sgcu/johnjud-go-proto v0.0.8/go.mod h1:HP0w9gC30b5WNnqeFBM9JJZud+pvyikz0+pGFSI/Wjw=
github.com/isd-sgcu/johnjud-go-proto v0.0.9 h1:cFfZ2JSpW0jg94Iv5zHQJGnoekj0eCQe42SJaTpnp3c=
github.com/isd-sgcu/johnjud-go-proto v0.0.9/go.mod h1:1OK6aiCgtXQiLhxp0r6iLEejYIRpckWQZDrCZ9Trbo4=
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk=
Expand Down Expand Up @@ -109,6 +111,8 @@ google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp0
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8=
google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I=
google.golang.org/protobuf v1.32.0 h1:pPC6BG5ex8PDFnkbrGU3EixyhKcQ2aDuBS36lqK/C7I=
google.golang.org/protobuf v1.32.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
Expand Down
8 changes: 4 additions & 4 deletions src/app/model/common.model.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
)

type Base struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;size:191"`
CreatedAt time.Time `json:"created_at" gorm:"type:datetime;autoCreateTime:nano"`
UpdatedAt time.Time `json:"updated_at" gorm:"type:datetime;autoUpdateTime:nano"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index;type:datetime"`
ID uuid.UUID `json:"id" gorm:"primary_key"`
CreatedAt time.Time `json:"created_at" gorm:"type:timestamp;autoCreateTime:nano"`
UpdatedAt time.Time `json:"updated_at" gorm:"type:timestamp;autoUpdateTime:nano"`
DeletedAt gorm.DeletedAt `json:"deleted_at" gorm:"index;type:timestamp"`
}

func (m *Base) BeforeCreate(_ *gorm.DB) error {
Expand Down
1 change: 1 addition & 0 deletions src/app/model/pet/pet.model.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,5 @@ type Pet struct {
Background string `json:"background" gorm:"tinytext"`
Address string `json:"address" gorm:"tinytext"`
Contact string `json:"contact" gorm:"tinytext"`
AdoptBy string `json:"adopt_by" gorm:"tinytext"`
}
10 changes: 5 additions & 5 deletions src/app/model/user/user.model.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,9 @@ import "github.com/isd-sgcu/johnjud-backend/src/app/model"

type User struct {
model.Base
Email string `json:"email" gorm:"type:tinytext"`
Password string `json:"password" gorm:"type:tinytext"`
Firstname string `json:"firstname" gorm:"type:tinytext"`
Lastname string `json:"lastname" gorm:"type:tinytext"`
Role string `json:"role" gorm:"type:tinytext"`
Email string `json:"email" gorm:"tinytext"`
Password string `json:"password" gorm:"tinytext"`
Firstname string `json:"firstname" gorm:"tinytext"`
Lastname string `json:"lastname" gorm:"tinytext"`
Role string `json:"role" gorm:"tinytext"`
}
1 change: 1 addition & 0 deletions src/app/service/like/like.service.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
)

type Service struct {
proto.UnimplementedLikeServiceServer
repository IRepository
}

Expand Down
7 changes: 5 additions & 2 deletions src/app/service/pet/pet.service.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
)

type Service struct {
proto.UnimplementedPetServiceServer
repository IRepository
imageService ImageService
}
Expand All @@ -36,7 +37,7 @@ type ImageService interface {
}

func NewService(repository IRepository, imageService ImageService) *Service {
return &Service{repository, imageService}
return &Service{repository: repository, imageService: imageService}
}

func (s *Service) Delete(ctx context.Context, req *proto.DeletePetRequest) (*proto.DeletePetResponse, error) {
Expand Down Expand Up @@ -138,7 +139,7 @@ func (s Service) FindOne(_ context.Context, req *proto.FindOnePetRequest) (res *
func (s *Service) Create(_ context.Context, req *proto.CreatePetRequest) (res *proto.CreatePetResponse, err error) {
raw, err := DtoToRaw(req.Pet)
if err != nil {
return nil, status.Error(codes.Internal, "error converting dto to raw")
return nil, status.Error(codes.Internal, "error converting dto to raw: "+err.Error())
}

imgUrls := []string{}
Expand Down Expand Up @@ -182,6 +183,7 @@ func RawToDto(in *pet.Pet, imgUrl []string) *proto.Pet {
Background: in.Background,
Address: in.Address,
Contact: in.Contact,
AdoptBy: in.AdoptBy,
}
}

Expand Down Expand Up @@ -233,6 +235,7 @@ func DtoToRaw(in *proto.Pet) (res *pet.Pet, err error) {
Background: in.Background,
Address: in.Address,
Contact: in.Contact,
AdoptBy: in.AdoptBy,
}, nil
}

Expand Down
5 changes: 5 additions & 0 deletions src/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,14 @@ type App struct {
Debug bool `mapstructure:"debug"`
}

type Service struct {
File string `mapstructure:"file"`
}

type Config struct {
App App `mapstructure:"app"`
Database Database `mapstructure:"database"`
Service Service `mapstructure:"service"`
}

func LoadConfig() (config *Config, err error) {
Expand Down
8 changes: 8 additions & 0 deletions src/database/postgresql.connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ import (
"fmt"
"strconv"

"github.com/isd-sgcu/johnjud-backend/src/app/model/like"
"github.com/isd-sgcu/johnjud-backend/src/app/model/pet"
"github.com/isd-sgcu/johnjud-backend/src/app/model/user"
"github.com/isd-sgcu/johnjud-backend/src/config"
"gorm.io/driver/postgres"
"gorm.io/gorm"
Expand All @@ -24,5 +27,10 @@ func InitPostgresDatabase(conf *config.Database, isDebug bool) (db *gorm.DB, err
return nil, err
}

err = db.AutoMigrate(&user.User{}, &like.Like{}, &pet.Pet{})
if err != nil {
return nil, err
}

return
}
162 changes: 161 additions & 1 deletion src/main.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,165 @@
package main

import (
"context"
"fmt"
"net"
"os"
"os/signal"
"sync"
"syscall"
"time"

likeRepo "github.com/isd-sgcu/johnjud-backend/src/app/repository/like"
petRepo "github.com/isd-sgcu/johnjud-backend/src/app/repository/pet"
imageSrv "github.com/isd-sgcu/johnjud-backend/src/app/service/image"
likeSrv "github.com/isd-sgcu/johnjud-backend/src/app/service/like"
petSrv "github.com/isd-sgcu/johnjud-backend/src/app/service/pet"
"github.com/isd-sgcu/johnjud-backend/src/config"
"github.com/isd-sgcu/johnjud-backend/src/database"
likePb "github.com/isd-sgcu/johnjud-go-proto/johnjud/backend/like/v1"
petPb "github.com/isd-sgcu/johnjud-go-proto/johnjud/backend/pet/v1"
imagePb "github.com/isd-sgcu/johnjud-go-proto/johnjud/file/image/v1"
"github.com/rs/zerolog/log"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/health"
"google.golang.org/grpc/health/grpc_health_v1"
"google.golang.org/grpc/reflection"
)

type operation func(ctx context.Context) error

func gracefulShutdown(ctx context.Context, timeout time.Duration, ops map[string]operation) <-chan struct{} {
wait := make(chan struct{})
go func() {
s := make(chan os.Signal, 1)

signal.Notify(s, syscall.SIGINT, syscall.SIGTERM, os.Interrupt)
sig := <-s

log.Info().
Str("service", "graceful shutdown").
Msgf("got signal \"%v\" shutting down service", sig)

timeoutFunc := time.AfterFunc(timeout, func() {
log.Error().
Str("service", "graceful shutdown").
Msgf("timeout %v ms has been elapsed, force exit", timeout.Milliseconds())
os.Exit(0)
})

defer timeoutFunc.Stop()

var wg sync.WaitGroup

for key, op := range ops {
wg.Add(1)
innerOp := op
innerKey := key
go func() {
defer wg.Done()

log.Info().
Str("service", "graceful shutdown").
Msgf("cleaning up: %v", innerKey)
if err := innerOp(ctx); err != nil {
log.Error().
Str("service", "graceful shutdown").
Err(err).
Msgf("%v: clean up failed: %v", innerKey, err.Error())
return
}

log.Info().
Str("service", "graceful shutdown").
Msgf("%v was shutdown gracefully", innerKey)
}()
}

wg.Wait()
close(wait)
}()

return wait
}

func main() {
// Code
conf, err := config.LoadConfig()
if err != nil {
log.Fatal().
Err(err).
Str("service", "backend").
Msg("Failed to load config")
}

db, err := database.InitPostgresDatabase(&conf.Database, conf.App.Debug)
if err != nil {
log.Fatal().
Err(err).
Str("service", "backend").
Msg("Failed to init postgres connection")
}

fileConn, err := grpc.Dial(conf.Service.File, grpc.WithTransportCredentials(insecure.NewCredentials()))
if err != nil {
log.Fatal().
Err(err).
Str("service", "johnjud-file").
Msg("Cannot connect to service")
}

lis, err := net.Listen("tcp", fmt.Sprintf(":%v", conf.App.Port))
if err != nil {
log.Fatal().
Err(err).
Str("service", "backend").
Msg("Failed to start service")
}

grpcServer := grpc.NewServer()

likeRepo := likeRepo.NewRepository(db)
likeService := likeSrv.NewService(likeRepo)

imageClient := imagePb.NewImageServiceClient(fileConn)
imageService := imageSrv.NewService(imageClient)
petRepo := petRepo.NewRepository(db)
petService := petSrv.NewService(petRepo, imageService)

grpc_health_v1.RegisterHealthServer(grpcServer, health.NewServer())
likePb.RegisterLikeServiceServer(grpcServer, likeService)
petPb.RegisterPetServiceServer(grpcServer, petService)

reflection.Register(grpcServer)
go func() {
log.Info().
Str("service", "backend").
Msgf("JohnJud backend starting at port %v", conf.App.Port)

if err := grpcServer.Serve(lis); err != nil {
log.Fatal().
Err(err).
Str("service", "backend").
Msg("Failed to start service")
}
}()

wait := gracefulShutdown(context.Background(), 2*time.Second, map[string]operation{
"server": func(ctx context.Context) error {
grpcServer.GracefulStop()
return nil
},
})

<-wait

grpcServer.GracefulStop()
log.Info().
Str("service", "backend").
Msg("Closing the listener")
lis.Close()
log.Info().
Str("service", "backend").
Msg("End the program")
}

0 comments on commit c9989d9

Please sign in to comment.