From 9c9a01965914e7d09694d7689fbfb4e8c2049bb4 Mon Sep 17 00:00:00 2001 From: UnicoYal Date: Fri, 20 Sep 2024 23:11:37 +0300 Subject: [PATCH] Fixes after review --- docker-compose.yml | 8 +--- .../api/validation/validation.proto | 2 +- validation-service/cmd/main.go | 6 +-- validation-service/config/config.go | 15 ++++++ validation-service/config/config_methods.go | 47 +++++++++++++++++++ validation-service/go.mod | 1 + validation-service/go.sum | 3 ++ .../internal/app/api/converter/converter.go | 2 +- .../internal/app/api/validation/handler.go | 4 +- .../internal/app/api/validation/validation.go | 2 +- validation-service/internal/app/app.go | 25 +++++----- .../internal/app/errors/errors.go | 10 ++-- .../internal/app/model/validation.go | 6 +-- .../service/validation/helpers/user_helper.go | 31 ++++++------ ...gistartion.go => validate_registration.go} | 14 +++--- .../app/service/validation/validation.go | 12 +++-- validation-service/internal/config/config.yml | 3 ++ .../internal/pb/validation/validation.pb.go | 8 ++-- 18 files changed, 138 insertions(+), 61 deletions(-) create mode 100644 validation-service/config/config.go create mode 100644 validation-service/config/config_methods.go rename validation-service/internal/app/service/validation/{validate_registartion.go => validate_registration.go} (71%) create mode 100644 validation-service/internal/config/config.yml diff --git a/docker-compose.yml b/docker-compose.yml index 5890667..93e1072 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,4 +1,4 @@ -version: '3' +version: '3.9' volumes: postgres_volume: @@ -17,8 +17,6 @@ services: redis: image: 'redis:latest' command: redis-server - ports: - - '6379:6379' volumes: - redis:/data networks: @@ -29,8 +27,6 @@ services: - "POSTGRES_DB=netflix" - "POSTGRES_USER=test" - "POSTGRES_PASSWORD=test" - ports: - - "5432:5432" volumes: - "postgres_volume:/var/lib/postgresql/data" networks: @@ -41,4 +37,4 @@ networks: netflix: default: external: - name: netflix + name: netflix # Не забыть создать сеть перед деплоем diff --git a/validation-service/api/validation/validation.proto b/validation-service/api/validation/validation.proto index f5d0fa9..a4f3709 100644 --- a/validation-service/api/validation/validation.proto +++ b/validation-service/api/validation/validation.proto @@ -10,7 +10,7 @@ message ValidateRegistrationRequest { string email = 1; string password = 2; string password_confirm = 3; - string sex = 4; + int32 sex = 4; google.protobuf.Timestamp bitrhdate = 5; } diff --git a/validation-service/cmd/main.go b/validation-service/cmd/main.go index 86763d0..22608c1 100644 --- a/validation-service/cmd/main.go +++ b/validation-service/cmd/main.go @@ -1,7 +1,6 @@ package main import ( - "context" "log" "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app" @@ -10,12 +9,11 @@ import ( const serverPort = 5050 func main() { - ctx := context.Background() - a, err := app.New(ctx, serverPort) + a, ctx, err := app.New() if err != nil { log.Fatal(err) } - a.Run() + a.Run(ctx) } diff --git a/validation-service/config/config.go b/validation-service/config/config.go new file mode 100644 index 0000000..4485748 --- /dev/null +++ b/validation-service/config/config.go @@ -0,0 +1,15 @@ +package config + +type Config struct { + Listener Listener `yaml:"listener"` +} + +type Listener struct { + Address string `yaml:"address"` + Port int `yaml:"port"` +} + +type ConfigContextKey struct { + Address string + Port int +} diff --git a/validation-service/config/config_methods.go b/validation-service/config/config_methods.go new file mode 100644 index 0000000..bc8f61a --- /dev/null +++ b/validation-service/config/config_methods.go @@ -0,0 +1,47 @@ +package config + +import ( + "context" + "os" + "path/filepath" + + "gopkg.in/yaml.v3" +) + +const cfgPath = "internal/config/config.yml" + +func GetConfigFromContext(ctx context.Context) *Config { + value, ok := ctx.Value(ConfigContextKey{}).(*Config) + if !ok { + return nil + } + + return value +} + +func CreateConfigContext() (context.Context, error) { + ctx := context.Background() + config, err := readConf() + if err != nil { + return nil, err + } + + return context.WithValue(ctx, ConfigContextKey{}, config), nil +} + +func readConf() (*Config, error) { + cfg := &Config{} + + filename, _ := filepath.Abs(cfgPath) + data, err := os.ReadFile(filename) + if err != nil { + return nil, err + } + + err = yaml.Unmarshal(data, cfg) + if err != nil { + return nil, err + } + + return cfg, nil +} diff --git a/validation-service/go.mod b/validation-service/go.mod index 3c2d8fe..dc0c7ac 100644 --- a/validation-service/go.mod +++ b/validation-service/go.mod @@ -13,4 +13,5 @@ require ( golang.org/x/text v0.16.0 // indirect google.golang.org/genproto/googleapis/rpc v0.0.0-20240604185151-ef581f913117 // indirect google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/validation-service/go.sum b/validation-service/go.sum index 905cd49..1b38bb2 100644 --- a/validation-service/go.sum +++ b/validation-service/go.sum @@ -14,3 +14,6 @@ google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1 h1:F29+wU6Ee6qgu9TddPgooOda google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.5.1/go.mod h1:5KF+wpkbTSbGcR9zteSqZV6fqFOWBl4Yde8En8MryZA= google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/validation-service/internal/app/api/converter/converter.go b/validation-service/internal/app/api/converter/converter.go index f10ef43..3b63422 100644 --- a/validation-service/internal/app/api/converter/converter.go +++ b/validation-service/internal/app/api/converter/converter.go @@ -22,6 +22,6 @@ func ToUserRegisterDataFromDesc(data *desc.ValidateRegistrationRequest) *model.U func ToErrorsFromServ(data *model.ErrorResponse) *desc.ErrorMessage { return &desc.ErrorMessage{ Code: data.Code, - Error: data.Error, + Error: data.ErrorObj.Error(), } } diff --git a/validation-service/internal/app/api/validation/handler.go b/validation-service/internal/app/api/validation/handler.go index a0f9366..d36b1e9 100644 --- a/validation-service/internal/app/api/validation/handler.go +++ b/validation-service/internal/app/api/validation/handler.go @@ -13,11 +13,13 @@ type ValidationService interface { type Implementation struct { desc.UnimplementedValidationServer + ctx context.Context validationService ValidationService } -func NewImplementation(validationService ValidationService) *Implementation { +func NewImplementation(ctx context.Context, validationService ValidationService) *Implementation { return &Implementation{ + ctx: ctx, validationService: validationService, } } diff --git a/validation-service/internal/app/api/validation/validation.go b/validation-service/internal/app/api/validation/validation.go index a5aa54d..74c1f0b 100644 --- a/validation-service/internal/app/api/validation/validation.go +++ b/validation-service/internal/app/api/validation/validation.go @@ -8,7 +8,7 @@ import ( ) func (i *Implementation) ValidateRegistration(ctx context.Context, req *desc.ValidateRegistrationRequest) (*desc.ValidationResponse, error) { - validData := i.validationService.ValidateRegistration(ctx, converter.ToUserRegisterDataFromDesc(req)) + validData := i.validationService.ValidateRegistration(i.ctx, converter.ToUserRegisterDataFromDesc(req)) descErrors := make([]*desc.ErrorMessage, 0) for _, errData := range validData.Errors { descErrors = append(descErrors, converter.ToErrorsFromServ(&errData)) diff --git a/validation-service/internal/app/app.go b/validation-service/internal/app/app.go index 8f4d1f2..970ea5e 100644 --- a/validation-service/internal/app/app.go +++ b/validation-service/internal/app/app.go @@ -9,38 +9,39 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/reflection" + "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/config" validationAPI "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app/api/validation" validationService "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app/service/validation" desc "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/pb/validation" ) type App struct { - serverPort int validationService validationAPI.ValidationService } -func New(ctx context.Context, serverPort int) (*App, error) { - validationService := validationService.NewService() +func New() (*App, context.Context, error) { + ctx, err := config.CreateConfigContext() + if err != nil { + log.Fatal("Failed to read config: %v", err) + } return &App{ - serverPort: serverPort, - validationService: validationService, - }, nil + validationService: validationService.NewService(ctx), + }, ctx, nil } -func (a *App) Run() { - lis, err := net.Listen("tcp", fmt.Sprintf(":%d", a.serverPort)) +func (a *App) Run(ctx context.Context) { + cfg := config.GetConfigFromContext(ctx) + lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.Listener.Port)) if err != nil { log.Fatal("Failed to listen: %v", err) } - validationSrv := validationService.NewService() s := grpc.NewServer() reflection.Register(s) + desc.RegisterValidationServer(s, validationAPI.NewImplementation(ctx, a.validationService)) - desc.RegisterValidationServer(s, validationAPI.NewImplementation(validationSrv)) - - log.Printf("Server listening at %v", lis.Addr()) + log.Printf("Server listening at %v:%d", cfg.Listener.Address, cfg.Listener.Port) if err = s.Serve(lis); err != nil { log.Fatalf("failed to serve: %v", err) diff --git a/validation-service/internal/app/errors/errors.go b/validation-service/internal/app/errors/errors.go index 935af2b..ad02eb1 100644 --- a/validation-service/internal/app/errors/errors.go +++ b/validation-service/internal/app/errors/errors.go @@ -1,12 +1,14 @@ package errors +import "errors" + var ( ErrInvalidEmailCode = "invalid_email" - ErrInvalidEmailText = "email is incorrect" + ErrInvalidEmailText = errors.New("email is incorrect") ErrInvalidPasswordCode = "invalid_password" - ErrInvalidPasswordText = "password is too short. The minimal len is 8" + ErrInvalidPasswordText = errors.New("password is too short. The minimal len is 8") ErrInvalidSexCode = "invalid_sex" - ErrInvalidSexText = "only male or female allowed" + ErrInvalidSexText = errors.New("only male or female allowed") ErrInvalidBirthdateCode = "invalid_birthdate" - ErrInvalidBirthdateText = "bithdate should be before current time" + ErrInvalidBirthdateText = errors.New("bithdate should be before current time") ) diff --git a/validation-service/internal/app/model/validation.go b/validation-service/internal/app/model/validation.go index de4a40c..d21f637 100644 --- a/validation-service/internal/app/model/validation.go +++ b/validation-service/internal/app/model/validation.go @@ -4,13 +4,13 @@ type UserRegisterData struct { Email string Password string PasswordConfirm string - Sex string + Sex int32 Birthday int } type ErrorResponse struct { - Code string - Error string + Code string + ErrorObj error } type ValidationResponse struct { diff --git a/validation-service/internal/app/service/validation/helpers/user_helper.go b/validation-service/internal/app/service/validation/helpers/user_helper.go index a336732..eefb246 100644 --- a/validation-service/internal/app/service/validation/helpers/user_helper.go +++ b/validation-service/internal/app/service/validation/helpers/user_helper.go @@ -1,7 +1,6 @@ package helpers import ( - "fmt" "log" "regexp" "slices" @@ -11,10 +10,14 @@ import ( "google.golang.org/protobuf/types/known/timestamppb" ) +const PasswordLength = 8 +const Male = 0 +const Female = 1 +const Other = 2 + var ( - emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") - passwordLength = 8 - sexVals = []string{"male", "female"} + emailRegex = regexp.MustCompile("^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$") + sexVals = []int32{Male, Female, Other} ) func ValidatePassword(pass, passConf string) error { @@ -22,9 +25,9 @@ func ValidatePassword(pass, passConf string) error { log.Println("password confirm is missing, but now its OK") } - if len(pass) < passwordLength { - log.Println(errVals.ErrInvalidPasswordText) - return fmt.Errorf(errVals.ErrInvalidPasswordText) + if len(pass) < PasswordLength { + log.Println(errVals.ErrInvalidPasswordText.Error()) + return errVals.ErrInvalidPasswordText } return nil @@ -32,8 +35,8 @@ func ValidatePassword(pass, passConf string) error { func ValidateEmail(email string) error { if !emailRegex.MatchString(email) { - log.Println(errVals.ErrInvalidEmailText) - return fmt.Errorf(errVals.ErrInvalidEmailText) + log.Println(errVals.ErrInvalidEmailText.Error()) + return errVals.ErrInvalidEmailText } return nil @@ -42,17 +45,17 @@ func ValidateEmail(email string) error { func ValidateBirthdate(birthdate int) error { ts := timestamppb.New(time.Now()) if int(ts.Seconds) < birthdate { - log.Println(errVals.ErrInvalidBirthdateCode) - return fmt.Errorf(errVals.ErrInvalidBirthdateText) + log.Println(errVals.ErrInvalidBirthdateText.Error()) + return errVals.ErrInvalidBirthdateText } return nil } -func ValidateSex(sex string) error { +func ValidateSex(sex int32) error { if !slices.Contains(sexVals, sex) { - log.Println(errVals.ErrInvalidSexCode) - return fmt.Errorf(errVals.ErrInvalidSexText) + log.Println(errVals.ErrInvalidSexText.Error()) + return errVals.ErrInvalidSexText } return nil diff --git a/validation-service/internal/app/service/validation/validate_registartion.go b/validation-service/internal/app/service/validation/validate_registration.go similarity index 71% rename from validation-service/internal/app/service/validation/validate_registartion.go rename to validation-service/internal/app/service/validation/validate_registration.go index 7c0a9c9..9664c28 100644 --- a/validation-service/internal/app/service/validation/validate_registartion.go +++ b/validation-service/internal/app/service/validation/validate_registration.go @@ -13,19 +13,19 @@ func (s *serv) ValidateRegistration(ctx context.Context, userData *model.UserReg errors := make([]model.ErrorResponse, 0) if err := userHelper.ValidatePassword(userData.Password, userData.PasswordConfirm); err != nil { - success = AddError(errVals.ErrInvalidPasswordCode, err.Error(), &errors) + success = AddError(errVals.ErrInvalidPasswordCode, err, &errors) } if err := userHelper.ValidateEmail(userData.Email); err != nil { - success = AddError(errVals.ErrInvalidEmailCode, err.Error(), &errors) + success = AddError(errVals.ErrInvalidEmailCode, err, &errors) } if err := userHelper.ValidateBirthdate(userData.Birthday); err != nil { - success = AddError(errVals.ErrInvalidBirthdateCode, err.Error(), &errors) + success = AddError(errVals.ErrInvalidBirthdateCode, err, &errors) } if err := userHelper.ValidateSex(userData.Sex); err != nil { - success = AddError(errVals.ErrInvalidSexCode, err.Error(), &errors) + success = AddError(errVals.ErrInvalidSexCode, err, &errors) } return &model.ValidationResponse{ @@ -34,10 +34,10 @@ func (s *serv) ValidateRegistration(ctx context.Context, userData *model.UserReg } } -func AddError(code, err string, errors *[]model.ErrorResponse) bool { +func AddError(code string, err error, errors *[]model.ErrorResponse) bool { errStruct := model.ErrorResponse{ - Code: code, - Error: err, + Code: code, + ErrorObj: err, } *errors = append(*errors, errStruct) diff --git a/validation-service/internal/app/service/validation/validation.go b/validation-service/internal/app/service/validation/validation.go index 4eb09f3..c14cb33 100644 --- a/validation-service/internal/app/service/validation/validation.go +++ b/validation-service/internal/app/service/validation/validation.go @@ -1,13 +1,19 @@ package validation import ( + "context" + api "github.com/go-park-mail-ru/2024_2_GOATS/validation-service/internal/app/api/validation" ) var _ api.ValidationService = (*serv)(nil) -type serv struct{} +type serv struct{ + ctx context.Context +} -func NewService() *serv { - return &serv{} +func NewService(ctx context.Context) *serv { + return &serv{ + ctx: ctx, + } } diff --git a/validation-service/internal/config/config.yml b/validation-service/internal/config/config.yml new file mode 100644 index 0000000..f07d424 --- /dev/null +++ b/validation-service/internal/config/config.yml @@ -0,0 +1,3 @@ +listener: + address: localhost + port: 5050 diff --git a/validation-service/internal/pb/validation/validation.pb.go b/validation-service/internal/pb/validation/validation.pb.go index 6610310..145561e 100644 --- a/validation-service/internal/pb/validation/validation.pb.go +++ b/validation-service/internal/pb/validation/validation.pb.go @@ -29,7 +29,7 @@ type ValidateRegistrationRequest struct { Email string `protobuf:"bytes,1,opt,name=email,proto3" json:"email,omitempty"` Password string `protobuf:"bytes,2,opt,name=password,proto3" json:"password,omitempty"` PasswordConfirm string `protobuf:"bytes,3,opt,name=password_confirm,json=passwordConfirm,proto3" json:"password_confirm,omitempty"` - Sex string `protobuf:"bytes,4,opt,name=sex,proto3" json:"sex,omitempty"` + Sex int32 `protobuf:"varint,4,opt,name=sex,proto3" json:"sex,omitempty"` Bitrhdate *timestamppb.Timestamp `protobuf:"bytes,5,opt,name=bitrhdate,proto3" json:"bitrhdate,omitempty"` } @@ -86,11 +86,11 @@ func (x *ValidateRegistrationRequest) GetPasswordConfirm() string { return "" } -func (x *ValidateRegistrationRequest) GetSex() string { +func (x *ValidateRegistrationRequest) GetSex() int32 { if x != nil { return x.Sex } - return "" + return 0 } func (x *ValidateRegistrationRequest) GetBitrhdate() *timestamppb.Timestamp { @@ -225,7 +225,7 @@ var file_validation_proto_rawDesc = []byte{ 0x64, 0x12, 0x29, 0x0a, 0x10, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x5f, 0x63, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x18, 0x03, 0x20, 0x01, 0x28, 0x09, 0x52, 0x0f, 0x70, 0x61, 0x73, 0x73, 0x77, 0x6f, 0x72, 0x64, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x72, 0x6d, 0x12, 0x10, 0x0a, 0x03, - 0x73, 0x65, 0x78, 0x18, 0x04, 0x20, 0x01, 0x28, 0x09, 0x52, 0x03, 0x73, 0x65, 0x78, 0x12, 0x38, + 0x73, 0x65, 0x78, 0x18, 0x04, 0x20, 0x01, 0x28, 0x05, 0x52, 0x03, 0x73, 0x65, 0x78, 0x12, 0x38, 0x0a, 0x09, 0x62, 0x69, 0x74, 0x72, 0x68, 0x64, 0x61, 0x74, 0x65, 0x18, 0x05, 0x20, 0x01, 0x28, 0x0b, 0x32, 0x1a, 0x2e, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2e, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2e, 0x54, 0x69, 0x6d, 0x65, 0x73, 0x74, 0x61, 0x6d, 0x70, 0x52, 0x09, 0x62,