diff --git a/internal/apps/bots/init.go b/internal/apps/bots/init.go index 19c8528..66ded5e 100644 --- a/internal/apps/bots/init.go +++ b/internal/apps/bots/init.go @@ -18,6 +18,7 @@ import ( "github.com/goriiin/kotyari-bots_backend/internal/delivery_grpc/profiles_validator" delivery "github.com/goriiin/kotyari-bots_backend/internal/delivery_http/bots" gen "github.com/goriiin/kotyari-bots_backend/internal/gen/bots" + "github.com/goriiin/kotyari-bots_backend/internal/logger" repo "github.com/goriiin/kotyari-bots_backend/internal/repo/bots" usecase "github.com/goriiin/kotyari-bots_backend/internal/usecase/bots" "github.com/goriiin/kotyari-bots_backend/pkg/cors" @@ -41,6 +42,8 @@ func (b *App) Run() error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() + l := logger.NewLogger("bots-app", &b.config.ConfigBase) + pool, err := postgres.GetPool(ctx, b.config.Database) if err != nil { return fmt.Errorf("postgres.GetPool: %w", err) @@ -63,7 +66,7 @@ func (b *App) Run() error { profileValidator := profiles_validator.NewGrpcValidator(profilesClient) profileGateway := profiles_getter.NewProfileGateway(profilesClient) botsUsecase := usecase.NewService(botsRepo, profileValidator, profileGateway) - botsHandler := delivery.NewHandler(botsUsecase) + botsHandler := delivery.NewHandler(botsUsecase, l) svr, err := gen.NewServer(botsHandler) if err != nil { @@ -90,7 +93,7 @@ func (b *App) Run() error { return fmt.Errorf("failed to listen for grpc: %w", err) } grpcServer := grpc.NewServer() - botGrpcServer := bots.NewServer(botsUsecase) + botGrpcServer := bots.NewServer(botsUsecase, l) botgrpc.RegisterBotServiceServer(grpcServer, botGrpcServer) go func() { diff --git a/internal/apps/posts_command_producer/init.go b/internal/apps/posts_command_producer/init.go index 70a9a28..72a7cca 100644 --- a/internal/apps/posts_command_producer/init.go +++ b/internal/apps/posts_command_producer/init.go @@ -39,8 +39,7 @@ func NewPostsCommandProducerApp(config *PostsCommandProducerConfig) (*PostsComma return nil, err } - // TODO: ??? - log := logger.NewLogger("xdd", &config.ConfigBase) + log := logger.NewLogger("posts-command-producer", &config.ConfigBase) reader := consumer.NewKafkaConsumer(log, &config.KafkaCons) @@ -52,7 +51,7 @@ func NewPostsCommandProducerApp(config *PostsCommandProducerConfig) (*PostsComma return nil, err } - handler := posts_command_producer.NewPostsHandler(grpc, p) + handler := posts_command_producer.NewPostsHandler(grpc, p, log) return &PostsCommandProducerApp{ handler: handler, diff --git a/internal/apps/posts_query/init.go b/internal/apps/posts_query/init.go index 6d6be6d..c199fa3 100644 --- a/internal/apps/posts_query/init.go +++ b/internal/apps/posts_query/init.go @@ -6,6 +6,7 @@ import ( "github.com/go-faster/errors" postsQueryHandler "github.com/goriiin/kotyari-bots_backend/internal/delivery_http/posts/posts_query" gen "github.com/goriiin/kotyari-bots_backend/internal/gen/posts/posts_query" + "github.com/goriiin/kotyari-bots_backend/internal/logger" postsQueryRepo "github.com/goriiin/kotyari-bots_backend/internal/repo/posts/posts_query" "github.com/goriiin/kotyari-bots_backend/pkg/postgres" ) @@ -23,6 +24,8 @@ type PostsQueryApp struct { } func NewPostsQueryApp(config *PostsQueryConfig) (*PostsQueryApp, error) { + log := logger.NewLogger("posts-query", &config.ConfigBase) + pool, err := postgres.GetPool(context.Background(), config.Database) if err != nil { @@ -31,7 +34,7 @@ func NewPostsQueryApp(config *PostsQueryConfig) (*PostsQueryApp, error) { repo := postsQueryRepo.NewPostsQueryRepo(pool) - handler := postsQueryHandler.NewPostsQueryHandler(repo) + handler := postsQueryHandler.NewPostsQueryHandler(repo, log) return &PostsQueryApp{ handler: handler, diff --git a/internal/apps/profiles/init.go b/internal/apps/profiles/init.go index aefbfea..dec97f0 100644 --- a/internal/apps/profiles/init.go +++ b/internal/apps/profiles/init.go @@ -15,6 +15,7 @@ import ( deliverygrpc "github.com/goriiin/kotyari-bots_backend/internal/delivery_grpc/profiles" deliveryhttp "github.com/goriiin/kotyari-bots_backend/internal/delivery_http/profiles" gen "github.com/goriiin/kotyari-bots_backend/internal/gen/profiles" + "github.com/goriiin/kotyari-bots_backend/internal/logger" repo "github.com/goriiin/kotyari-bots_backend/internal/repo/profiles" usecase "github.com/goriiin/kotyari-bots_backend/internal/usecase/profiles" "github.com/goriiin/kotyari-bots_backend/pkg/cors" @@ -37,6 +38,8 @@ func (p *ProfilesApp) Run() error { ctx, cancel := context.WithCancel(context.Background()) defer cancel() + l := logger.NewLogger("profiles-app", &p.config.ConfigBase) + pool, err := postgres.GetPool(ctx, p.config.Database) if err != nil { return fmt.Errorf("postgres.GetPool: %w", err) @@ -46,8 +49,8 @@ func (p *ProfilesApp) Run() error { profilesRepo := repo.NewRepository(pool) profilesUsecase := usecase.NewService(profilesRepo) - grpcHandler := deliverygrpc.NewGRPCHandler(profilesUsecase) - httpHandler := deliveryhttp.NewHTTPHandler(profilesUsecase) + grpcHandler := deliverygrpc.NewGRPCHandler(profilesUsecase, l) + httpHandler := deliveryhttp.NewHTTPHandler(profilesUsecase, l) g, gCtx := errgroup.WithContext(ctx) diff --git a/internal/delivery_grpc/bots/get.go b/internal/delivery_grpc/bots/get.go index 7c32aff..4f64c59 100644 --- a/internal/delivery_grpc/bots/get.go +++ b/internal/delivery_grpc/bots/get.go @@ -12,11 +12,13 @@ import ( func (s *Server) GetBot(ctx context.Context, req *botgrpc.GetBotRequest) (*botgrpc.Bot, error) { id, err := uuid.Parse(req.GetId()) if err != nil { + s.log.Error(err, true, "GetBot: parse id") return nil, ierrors.DomainToGRPCError(constants.ErrInvalid) } botModel, err := s.usecase.Get(ctx, id) if err != nil { + s.log.Error(err, true, "GetBot: get bot") return nil, ierrors.DomainToGRPCError(err) } diff --git a/internal/delivery_grpc/bots/init.go b/internal/delivery_grpc/bots/init.go index 452e4b1..88dea9a 100644 --- a/internal/delivery_grpc/bots/init.go +++ b/internal/delivery_grpc/bots/init.go @@ -5,6 +5,7 @@ import ( "github.com/google/uuid" bot_grpc "github.com/goriiin/kotyari-bots_backend/api/protos/bots/gen" + "github.com/goriiin/kotyari-bots_backend/internal/logger" "github.com/goriiin/kotyari-bots_backend/internal/model" ) @@ -15,10 +16,12 @@ type Usecase interface { type Server struct { bot_grpc.UnimplementedBotServiceServer usecase Usecase + log *logger.Logger } -func NewServer(usecase Usecase) *Server { +func NewServer(usecase Usecase, log *logger.Logger) *Server { return &Server{ usecase: usecase, + log: log, } } diff --git a/internal/delivery_grpc/profiles/exist.go b/internal/delivery_grpc/profiles/exist.go index c5e42d5..1b8fb32 100644 --- a/internal/delivery_grpc/profiles/exist.go +++ b/internal/delivery_grpc/profiles/exist.go @@ -13,7 +13,8 @@ func (h *GRPCHandler) ProfilesExist(ctx context.Context, req *profiles.ProfilesE for _, idStr := range req.ProfileIds { id, err := uuid.Parse(idStr) if err != nil { - continue // пропускаем невалидные UUID + h.log.Warn("ProfilesExist: parse id", err) + continue } profileUUIDs = append(profileUUIDs, id) } @@ -24,6 +25,7 @@ func (h *GRPCHandler) ProfilesExist(ctx context.Context, req *profiles.ProfilesE existenceMap, err := h.u.Exist(ctx, profileUUIDs) if err != nil { + h.log.Error(err, true, "ProfilesExist: exist") return nil, ierrors.DomainToGRPCError(err) } diff --git a/internal/delivery_grpc/profiles/get.go b/internal/delivery_grpc/profiles/get.go index d170497..04b0ac7 100644 --- a/internal/delivery_grpc/profiles/get.go +++ b/internal/delivery_grpc/profiles/get.go @@ -12,7 +12,8 @@ func (h *GRPCHandler) GetProfiles(ctx context.Context, req *profiles.GetProfiles for _, idStr := range req.ProfileIds { id, err := uuid.Parse(idStr) if err != nil { - continue // Игнорируем невалидные UUID + h.log.Warn("GetProfiles: parse id", err) + continue } profileUUIDs = append(profileUUIDs, id) } @@ -23,6 +24,7 @@ func (h *GRPCHandler) GetProfiles(ctx context.Context, req *profiles.GetProfiles profileModels, err := h.u.GetByIDs(ctx, profileUUIDs) if err != nil { + h.log.Error(err, true, "GetProfiles: get by ids") return nil, err } diff --git a/internal/delivery_grpc/profiles/init.go b/internal/delivery_grpc/profiles/init.go index f25c101..2be50ac 100644 --- a/internal/delivery_grpc/profiles/init.go +++ b/internal/delivery_grpc/profiles/init.go @@ -5,6 +5,7 @@ import ( "github.com/google/uuid" profiles "github.com/goriiin/kotyari-bots_backend/api/protos/bot_profile/gen" + "github.com/goriiin/kotyari-bots_backend/internal/logger" "github.com/goriiin/kotyari-bots_backend/internal/model" ) @@ -15,9 +16,13 @@ type usecase interface { type GRPCHandler struct { profiles.UnimplementedProfilesServiceServer - u usecase + u usecase + log *logger.Logger } -func NewGRPCHandler(u usecase) *GRPCHandler { - return &GRPCHandler{u: u} +func NewGRPCHandler(u usecase, log *logger.Logger) *GRPCHandler { + return &GRPCHandler{ + u: u, + log: log, + } } diff --git a/internal/delivery_http/bots/create.go b/internal/delivery_http/bots/create.go index 5ffda17..c18b284 100644 --- a/internal/delivery_http/bots/create.go +++ b/internal/delivery_http/bots/create.go @@ -31,11 +31,13 @@ func (h *Handler) CreateBot(ctx context.Context, req *gen.BotInput) (gen.CreateB ProfileIDs: profiles, }) if err != nil { + h.log.Error(err, true, "CreateBot: create bot") return nil, err } bot, profs, err := h.u.GetWithProfiles(ctx, created.ID) if err != nil { + h.log.Error(err, true, "CreateBot: get with profiles") return nil, err } return modelToDTO(&bot, profs), nil diff --git a/internal/delivery_http/bots/delete.go b/internal/delivery_http/bots/delete.go index 8df7377..4566357 100644 --- a/internal/delivery_http/bots/delete.go +++ b/internal/delivery_http/bots/delete.go @@ -2,15 +2,14 @@ package bots import ( "context" - "log" gen "github.com/goriiin/kotyari-bots_backend/internal/gen/bots" ) func (h *Handler) DeleteBotById(ctx context.Context, params gen.DeleteBotByIdParams) (gen.DeleteBotByIdRes, error) { - log.Println("delete:", params.BotId) err := h.u.Delete(ctx, params.BotId) if err != nil { + h.log.Error(err, true, "DeleteBotById: delete") return nil, err } diff --git a/internal/delivery_http/bots/get.go b/internal/delivery_http/bots/get.go index 2c70f52..fef41a3 100644 --- a/internal/delivery_http/bots/get.go +++ b/internal/delivery_http/bots/get.go @@ -18,11 +18,13 @@ func (h *Handler) GetBotById(ctx context.Context, params gen.GetBotByIdParams) ( }, nil } if errors.Is(err, constants.ErrServiceUnavailable) { + h.log.Error(err, true, "GetBotById: service unavailable") return &gen.GetBotByIdInternalServerError{ ErrorCode: constants.ServiceUnavailableMsg, Message: err.Error(), }, nil } + h.log.Error(err, true, "GetBotById: get with profiles") return nil, err } diff --git a/internal/delivery_http/bots/init.go b/internal/delivery_http/bots/init.go index 0d63a8f..54823c7 100644 --- a/internal/delivery_http/bots/init.go +++ b/internal/delivery_http/bots/init.go @@ -4,6 +4,7 @@ import ( "context" "github.com/google/uuid" + "github.com/goriiin/kotyari-bots_backend/internal/logger" "github.com/goriiin/kotyari-bots_backend/internal/model" ) @@ -20,9 +21,13 @@ type usecase interface { } type Handler struct { - u usecase + u usecase + log *logger.Logger } -func NewHandler(usecase usecase) *Handler { - return &Handler{u: usecase} +func NewHandler(usecase usecase, log *logger.Logger) *Handler { + return &Handler{ + u: usecase, + log: log, + } } diff --git a/internal/delivery_http/bots/list.go b/internal/delivery_http/bots/list.go index 8e982cb..3ac7ccc 100644 --- a/internal/delivery_http/bots/list.go +++ b/internal/delivery_http/bots/list.go @@ -2,27 +2,22 @@ package bots import ( "context" - "log" gen "github.com/goriiin/kotyari-bots_backend/internal/gen/bots" ) func (h *Handler) ListBots(ctx context.Context) (gen.ListBotsRes, error) { - log.Println("ListBots") bots, err := h.u.List(ctx) if err != nil { - log.Println(err) + h.log.Error(err, true, "ListBots: list") return nil, err } - log.Println("ListBots", bots) genBots := make([]gen.Bot, len(bots)) for i, b := range bots { genBots[i] = *modelToDTO(&b.Bot, b.Profiles) } - log.Println("bots list:", len(bots), genBots) - return &gen.BotList{ Data: genBots, NextCursor: gen.OptNilString{}, diff --git a/internal/delivery_http/bots/profiles.go b/internal/delivery_http/bots/profiles.go index d0bd1bf..baa3f51 100644 --- a/internal/delivery_http/bots/profiles.go +++ b/internal/delivery_http/bots/profiles.go @@ -16,6 +16,7 @@ func (h Handler) AddProfileToBot(ctx context.Context, params gen.AddProfileToBot Message: "bot or profile not found", }, nil } + h.log.Error(err, true, "AddProfileToBot: add profile") return &gen.AddProfileToBotInternalServerError{ ErrorCode: constants.InternalMsg, Message: err.Error(), @@ -32,6 +33,7 @@ func (h Handler) RemoveProfileFromBot(ctx context.Context, params gen.RemoveProf Message: "bot not found", }, nil } + h.log.Error(err, true, "RemoveProfileFromBot: remove profile") return &gen.RemoveProfileFromBotInternalServerError{ ErrorCode: constants.InternalMsg, Message: err.Error(), @@ -49,6 +51,7 @@ func (h Handler) GetBotProfiles(ctx context.Context, params gen.GetBotProfilesPa Message: "bot not found", }, nil } + h.log.Error(err, true, "GetBotProfiles: get with profiles") return &gen.GetBotProfilesInternalServerError{ ErrorCode: constants.InternalMsg, Message: err.Error(), diff --git a/internal/delivery_http/bots/search.go b/internal/delivery_http/bots/search.go index d0d2643..f7c63ca 100644 --- a/internal/delivery_http/bots/search.go +++ b/internal/delivery_http/bots/search.go @@ -10,6 +10,7 @@ import ( func (h *Handler) SearchBots(ctx context.Context, params bots.SearchBotsParams) (bots.SearchBotsRes, error) { foundBots, err := h.u.Search(ctx, params.Q) if err != nil { + h.log.Error(err, true, "SearchBots: search") return &bots.SearchBotsInternalServerError{ ErrorCode: constants.InternalMsg, Message: err.Error(), diff --git a/internal/delivery_http/bots/summary.go b/internal/delivery_http/bots/summary.go index e00f993..9edab95 100644 --- a/internal/delivery_http/bots/summary.go +++ b/internal/delivery_http/bots/summary.go @@ -10,6 +10,7 @@ import ( func (h *Handler) SummaryBots(ctx context.Context) (bots.SummaryBotsRes, error) { summary, err := h.u.GetSummary(ctx) if err != nil { + h.log.Error(err, true, "SummaryBots: get summary") return &bots.Error{ ErrorCode: constants.InternalMsg, Message: err.Error(), diff --git a/internal/delivery_http/bots/update.go b/internal/delivery_http/bots/update.go index 67dd8dc..80b9c69 100644 --- a/internal/delivery_http/bots/update.go +++ b/internal/delivery_http/bots/update.go @@ -11,6 +11,7 @@ import ( func (h *Handler) UpdateBotById(ctx context.Context, req *gen.BotInput, params gen.UpdateBotByIdParams) (gen.UpdateBotByIdRes, error) { _, err := h.u.Update(ctx, dtoToModel(req, params.BotId)) if err != nil { + h.log.Error(err, true, "UpdateBotById: update") return nil, err } @@ -22,6 +23,7 @@ func (h *Handler) UpdateBotById(ctx context.Context, req *gen.BotInput, params g Message: err.Error(), }, nil } + h.log.Error(err, true, "UpdateBotById: get with profiles") return nil, err } diff --git a/internal/delivery_http/posts/posts_command_consumer/create_post.go b/internal/delivery_http/posts/posts_command_consumer/create_post.go index 2c72f0e..13f2030 100644 --- a/internal/delivery_http/posts/posts_command_consumer/create_post.go +++ b/internal/delivery_http/posts/posts_command_consumer/create_post.go @@ -3,7 +3,6 @@ package posts_command_consumer import ( "context" "fmt" - "log" "sync" "github.com/go-faster/errors" @@ -40,6 +39,7 @@ func (p *PostsCommandConsumer) CreatePost(ctx context.Context, postsMap map[uuid err := p.repo.UpdatePostsBatch(ctx, finalPosts) if err != nil { + p.log.Error(err, true, "CreatePost: update posts batch") return errors.Wrap(err, "failed to create posts") } @@ -56,7 +56,7 @@ func (p *PostsCommandConsumer) processProfile(ctx context.Context, req posts.Kaf bestPostCandidate, err := p.judge.SelectBest(ctx, req.UserPrompt, profile.ProfilePrompt, req.BotPrompt, posts.PostsToCandidates(profilesPosts)) if err != nil { - fmt.Println("error getting best post ", err) + p.log.Error(err, true, "processProfile: select best") return nil } @@ -74,7 +74,7 @@ func (p *PostsCommandConsumer) processProfile(ctx context.Context, req posts.Kaf func (p *PostsCommandConsumer) generatePostsForProfile(ctx context.Context, req posts.KafkaCreatePostRequest, profile posts.CreatePostProfiles, postsMap map[uuid.UUID]model.Post) []model.Post { rewritten, err := p.rewriter.Rewrite(ctx, req.UserPrompt, profile.ProfilePrompt, req.BotPrompt) if err != nil { - fmt.Println("error rewriting prompts", err) + p.log.Error(err, true, "generatePostsForProfile: rewrite") return nil } @@ -92,7 +92,7 @@ func (p *PostsCommandConsumer) generatePostsForProfile(ctx context.Context, req generatedPostContent, err := p.getter.GetPost(ctx, rewrittenPrompt, profile.ProfilePrompt, req.BotPrompt) if err != nil { - fmt.Println("error getting post", err) + p.log.Error(err, true, "generatePostsForProfile: get post") return } @@ -137,17 +137,17 @@ func (p *PostsCommandConsumer) publishToOtvet(ctx context.Context, req posts.Kaf // Respect bot-level moderation flag: if moderation required, do not publish directly if req.ModerationRequired { // Create post in DB but skip publish since moderation is required - fmt.Printf("bot requires moderation, skipping direct publish for post %s\n", post.ID.String()) + p.log.Info(fmt.Sprintf("publishToOtvet: bot requires moderation, skipping direct publish for post %s", post.ID.String())) return } otvetResp, err := p.otvetClient.CreatePostSimple(ctx, candidate.Title, candidate.Text, topicType, spaces) if err != nil { - fmt.Printf("error publishing post to otvet: %v\n", err) + p.log.Error(err, true, "publishToOtvet: create post simple") return } - log.Printf("INFO: published post to otvet: %v\n", otvetResp) + p.log.Info(fmt.Sprintf("publishToOtvet: published post to otvet: %v", otvetResp)) if otvetResp != nil && otvetResp.Result != nil { post.OtvetiID = uint64(otvetResp.Result.ID) @@ -161,7 +161,7 @@ func (p *PostsCommandConsumer) getSpacesForPost(ctx context.Context, candidate m predictResp, err := p.otvetClient.PredictTagsSpaces(ctx, combinedText) if err != nil { - fmt.Printf("error predicting spaces: %v, using default spaces\n", err) + p.log.Error(err, true, "getSpacesForPost: predict tags spaces") return spaces } diff --git a/internal/delivery_http/posts/posts_command_consumer/handler.go b/internal/delivery_http/posts/posts_command_consumer/handler.go index e34f990..7899fb1 100644 --- a/internal/delivery_http/posts/posts_command_consumer/handler.go +++ b/internal/delivery_http/posts/posts_command_consumer/handler.go @@ -40,7 +40,7 @@ func (p *PostsCommandConsumer) HandleCommands() error { } if err != nil { - p.log.Error(err, false, fmt.Sprintf("failed to handle command '%s'", env.Command)) + p.log.Error(err, false, fmt.Sprintf("HandleCommands: failed to handle command '%s'", env.Command)) } } @@ -50,16 +50,19 @@ func (p *PostsCommandConsumer) HandleCommands() error { func (p *PostsCommandConsumer) handleSeenCommand(ctx context.Context, message kafkaConfig.CommittableMessage, payload []byte) error { err := p.SeenPosts(ctx, payload) if err != nil { + p.log.Error(err, true, "handleSeenCommand: seen posts") return sendErrReply(ctx, message, err) } resp := posts.KafkaResponse{} rawResp, err := jsoniter.Marshal(resp) if err != nil { + p.log.Error(err, true, "handleSeenCommand: marshal") return errors.Wrap(err, constants.MarshalMsg) } if err := message.Reply(ctx, rawResp, true); err != nil { + p.log.Error(err, true, "handleSeenCommand: reply") return errors.Wrap(err, failedToSendReplyMsg) } @@ -69,6 +72,7 @@ func (p *PostsCommandConsumer) handleSeenCommand(ctx context.Context, message ka func (p *PostsCommandConsumer) handleUpdateCommand(ctx context.Context, message kafkaConfig.CommittableMessage, payload []byte) error { post, err := p.UpdatePost(ctx, payload) if err != nil { + p.log.Error(err, true, "handleUpdateCommand: update post") return sendErrReply(ctx, message, err) } @@ -78,10 +82,12 @@ func (p *PostsCommandConsumer) handleUpdateCommand(ctx context.Context, message rawResp, err := jsoniter.Marshal(resp) if err != nil { + p.log.Error(err, true, "handleUpdateCommand: marshal") return errors.Wrap(err, constants.MarshalMsg) } if err := message.Reply(ctx, rawResp, true); err != nil { + p.log.Error(err, true, "handleUpdateCommand: reply") return errors.Wrap(err, failedToSendReplyMsg) } @@ -90,15 +96,18 @@ func (p *PostsCommandConsumer) handleUpdateCommand(ctx context.Context, message func (p *PostsCommandConsumer) handleDeleteCommand(ctx context.Context, message kafkaConfig.CommittableMessage, payload []byte) error { if err := p.DeletePost(ctx, payload); err != nil { + p.log.Error(err, true, "handleDeleteCommand: delete post") return sendErrReply(ctx, message, err) } resp, err := jsoniter.Marshal(posts.KafkaResponse{}) if err != nil { + p.log.Error(err, true, "handleDeleteCommand: marshal") return errors.Wrap(err, constants.MarshalMsg) } if err := message.Reply(ctx, resp, true); err != nil { + p.log.Error(err, true, "handleDeleteCommand: reply") return errors.Wrap(err, failedToSendReplyMsg) } @@ -108,15 +117,18 @@ func (p *PostsCommandConsumer) handleDeleteCommand(ctx context.Context, message func (p *PostsCommandConsumer) handleCreateCommand(ctx context.Context, message kafkaConfig.CommittableMessage, payload []byte) error { postsMapping, req, err := p.CreateInitialPosts(ctx, payload) if err != nil { + p.log.Error(err, true, "handleCreateCommand: create initial posts") return sendErrReply(ctx, message, err) } err = sendOkReply(ctx, message) if err != nil { + p.log.Error(err, true, "handleCreateCommand: send ok reply") return errors.Wrap(err, "failed to ACK posts creation") } if err = message.Ack(ctx); err != nil { + p.log.Error(err, true, "handleCreateCommand: ack") return errors.Wrap(err, "failed to commit offset") } @@ -124,9 +136,9 @@ func (p *PostsCommandConsumer) handleCreateCommand(ctx context.Context, message go func() { bgCtx := context.Background() if err := p.CreatePost(bgCtx, postsMapping, req); err != nil { - p.log.Error(err, false, fmt.Sprintf("Async post generation failed for GroupID %s", req.GroupID)) + p.log.Error(err, false, fmt.Sprintf("handleCreateCommand: Async post generation failed for GroupID %s", req.GroupID)) } else { - p.log.Info(fmt.Sprintf("Async post generation finished for GroupID %s", req.GroupID)) + p.log.Info(fmt.Sprintf("handleCreateCommand: Async post generation finished for GroupID %s", req.GroupID)) } }() @@ -137,24 +149,30 @@ func (p *PostsCommandConsumer) handlePublishCommand(ctx context.Context, message var req posts.KafkaPublishPostRequest err := jsoniter.Unmarshal(payload, &req) if err != nil { + p.log.Error(err, true, "handlePublishCommand: unmarshal") return sendErrReply(ctx, message, errors.Wrap(err, "failed to unmarshal")) } if p.queue == nil { - return sendErrReply(ctx, message, errors.New("queue not available")) + err := errors.New("queue not available") + p.log.Error(err, true, "handlePublishCommand: check queue") + return sendErrReply(ctx, message, err) } err = p.queue.ApprovePost(req.PostID) if err != nil { + p.log.Error(err, true, "handlePublishCommand: approve post") return sendErrReply(ctx, message, errors.Wrap(err, "failed to approve post")) } resp, err := jsoniter.Marshal(posts.KafkaResponse{}) if err != nil { + p.log.Error(err, true, "handlePublishCommand: marshal") return errors.Wrap(err, constants.MarshalMsg) } if err := message.Reply(ctx, resp, true); err != nil { + p.log.Error(err, true, "handlePublishCommand: reply") return errors.Wrap(err, failedToSendReplyMsg) } diff --git a/internal/delivery_http/posts/posts_command_producer/create_post.go b/internal/delivery_http/posts/posts_command_producer/create_post.go index d7ca0bc..712bf3b 100644 --- a/internal/delivery_http/posts/posts_command_producer/create_post.go +++ b/internal/delivery_http/posts/posts_command_producer/create_post.go @@ -6,6 +6,7 @@ import ( "net/http" "time" + "github.com/go-faster/errors" "github.com/google/uuid" "github.com/goriiin/kotyari-bots_backend/internal/delivery_http/posts" gen "github.com/goriiin/kotyari-bots_backend/internal/gen/posts/posts_command" @@ -17,7 +18,7 @@ import ( func (p *PostsCommandHandler) CreatePost(ctx context.Context, req *gen.PostInput) (gen.CreatePostRes, error) { bot, err := p.fetcher.GetBot(ctx, req.BotId.String()) if err != nil { - fmt.Println("bots") + p.log.Error(err, true, "CreatePost: get bot") return &gen.CreatePostInternalServerError{ErrorCode: http.StatusInternalServerError, Message: ierrors.GRPCToDomainError(err).Error()}, nil } @@ -26,15 +27,12 @@ func (p *PostsCommandHandler) CreatePost(ctx context.Context, req *gen.PostInput idsString = append(idsString, id.String()) } - fmt.Printf("ids string: %+v\n", idsString) profilesBatch, err := p.fetcher.GetProfiles(ctx, idsString) if err != nil { - fmt.Println("profiles") + p.log.Error(err, true, "CreatePost: get profiles") return &gen.CreatePostInternalServerError{ErrorCode: http.StatusInternalServerError, Message: ierrors.GRPCToDomainError(err).Error()}, nil } - fmt.Printf("profiles batch: %+v\n", idsString) - postProfiles := make([]posts.CreatePostProfiles, 0, len(idsString)) for _, profile := range profilesBatch.Profiles { profileID, _ := uuid.Parse(profile.Id) @@ -48,23 +46,21 @@ func (p *PostsCommandHandler) CreatePost(ctx context.Context, req *gen.PostInput groupID := uuid.New() botID, _ := uuid.Parse(bot.Id) createPostRequest := posts.KafkaCreatePostRequest{ - PostID: uuid.New(), - GroupID: groupID, - BotID: botID, - BotName: bot.BotName, - BotPrompt: bot.BotPrompt, - UserPrompt: req.TaskText, - Profiles: postProfiles, - Platform: model.PlatformType(req.Platform), - PostType: model.PostType(req.PostType.Value), - // pass moderation flag from bot + PostID: uuid.New(), + GroupID: groupID, + BotID: botID, + BotName: bot.BotName, + BotPrompt: bot.BotPrompt, + UserPrompt: req.TaskText, + Profiles: postProfiles, + Platform: model.PlatformType(req.Platform), + PostType: model.PostType(req.PostType.Value), ModerationRequired: bot.ModerationRequired, } - fmt.Printf("%+v\n", createPostRequest) - rawReq, err := jsoniter.Marshal(createPostRequest) if err != nil { + p.log.Error(err, true, "CreatePost: marshal") return &gen.CreatePostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -73,6 +69,7 @@ func (p *PostsCommandHandler) CreatePost(ctx context.Context, req *gen.PostInput rawResp, err := p.producer.Request(ctx, posts.PayloadToEnvelope(posts.CmdCreate, createPostRequest.GroupID.String(), rawReq), 30*time.Second) if err != nil { + p.log.Error(err, true, "CreatePost: request") return &gen.CreatePostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -82,6 +79,7 @@ func (p *PostsCommandHandler) CreatePost(ctx context.Context, req *gen.PostInput var resp posts.KafkaResponse err = jsoniter.Unmarshal(rawResp, &resp) if err != nil { + p.log.Error(err, true, "CreatePost: unmarshal response") return &gen.CreatePostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -89,6 +87,7 @@ func (p *PostsCommandHandler) CreatePost(ctx context.Context, req *gen.PostInput } if resp.Error != "" { + p.log.Warn("CreatePost: response error", errors.New(resp.Error)) return &gen.CreatePostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: fmt.Sprintf("Failed to create post, %s", resp.Error), diff --git a/internal/delivery_http/posts/posts_command_producer/delete_post.go b/internal/delivery_http/posts/posts_command_producer/delete_post.go index 32efb9c..487b7b7 100644 --- a/internal/delivery_http/posts/posts_command_producer/delete_post.go +++ b/internal/delivery_http/posts/posts_command_producer/delete_post.go @@ -17,6 +17,7 @@ func (p *PostsCommandHandler) DeletePostById(ctx context.Context, params gen.Del rawReq, err := jsoniter.Marshal(req) if err != nil { + p.log.Error(err, true, "DeletePostById: marshal") return &gen.DeletePostByIdInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -26,7 +27,7 @@ func (p *PostsCommandHandler) DeletePostById(ctx context.Context, params gen.Del env := posts.PayloadToEnvelope(posts.CmdDelete, params.PostId.String(), rawReq) rawResp, err := p.producer.Request(ctx, env, 5*time.Second) if err != nil { - // TODO: TIMEOUT / PUBLISH ERR + p.log.Error(err, true, "DeletePostById: request") return &gen.DeletePostByIdInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -36,6 +37,7 @@ func (p *PostsCommandHandler) DeletePostById(ctx context.Context, params gen.Del var resp posts.KafkaResponse err = jsoniter.Unmarshal(rawResp, &resp) if err != nil { + p.log.Error(err, true, "DeletePostById: unmarshal response") return &gen.DeletePostByIdInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), diff --git a/internal/delivery_http/posts/posts_command_producer/init.go b/internal/delivery_http/posts/posts_command_producer/init.go index 6d668f6..c11d298 100644 --- a/internal/delivery_http/posts/posts_command_producer/init.go +++ b/internal/delivery_http/posts/posts_command_producer/init.go @@ -7,6 +7,7 @@ import ( profilesgen "github.com/goriiin/kotyari-bots_backend/api/protos/bot_profile/gen" botsgen "github.com/goriiin/kotyari-bots_backend/api/protos/bots/gen" kafkaConfig "github.com/goriiin/kotyari-bots_backend/internal/kafka" + "github.com/goriiin/kotyari-bots_backend/internal/logger" "google.golang.org/grpc" ) @@ -31,11 +32,13 @@ type botsAndProfilesFetcher interface { type PostsCommandHandler struct { fetcher botsAndProfilesFetcher producer producer + log *logger.Logger } -func NewPostsHandler(fetcher botsAndProfilesFetcher, producer producer) *PostsCommandHandler { +func NewPostsHandler(fetcher botsAndProfilesFetcher, producer producer, log *logger.Logger) *PostsCommandHandler { return &PostsCommandHandler{ fetcher: fetcher, producer: producer, + log: log, } } diff --git a/internal/delivery_http/posts/posts_command_producer/publish_post.go b/internal/delivery_http/posts/posts_command_producer/publish_post.go index 39cc509..4fffb95 100644 --- a/internal/delivery_http/posts/posts_command_producer/publish_post.go +++ b/internal/delivery_http/posts/posts_command_producer/publish_post.go @@ -5,6 +5,7 @@ import ( "net/http" "time" + "github.com/go-faster/errors" "github.com/goriiin/kotyari-bots_backend/internal/delivery_http/posts" gen "github.com/goriiin/kotyari-bots_backend/internal/gen/posts/posts_command" jsoniter "github.com/json-iterator/go" @@ -25,6 +26,7 @@ func (p *PostsCommandHandler) PublishPost(ctx context.Context, req *gen.PublishP rawReq, err := jsoniter.Marshal(publishRequest) if err != nil { + p.log.Error(err, true, "PublishPost: marshal") return &gen.PublishPostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -33,6 +35,7 @@ func (p *PostsCommandHandler) PublishPost(ctx context.Context, req *gen.PublishP rawResp, err := p.producer.Request(ctx, posts.PayloadToEnvelope(posts.CmdPublish, params.PostId.String(), rawReq), 5*time.Second) if err != nil { + p.log.Error(err, true, "PublishPost: request") return &gen.PublishPostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -42,6 +45,7 @@ func (p *PostsCommandHandler) PublishPost(ctx context.Context, req *gen.PublishP var resp posts.KafkaResponse err = jsoniter.Unmarshal(rawResp, &resp) if err != nil { + p.log.Error(err, true, "PublishPost: unmarshal response") return &gen.PublishPostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -49,6 +53,7 @@ func (p *PostsCommandHandler) PublishPost(ctx context.Context, req *gen.PublishP } if resp.Error != "" { + p.log.Warn("PublishPost: response error", errors.New(resp.Error)) return &gen.PublishPostInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: resp.Error, diff --git a/internal/delivery_http/posts/posts_command_producer/seen_posts.go b/internal/delivery_http/posts/posts_command_producer/seen_posts.go index 7bab01e..5722749 100644 --- a/internal/delivery_http/posts/posts_command_producer/seen_posts.go +++ b/internal/delivery_http/posts/posts_command_producer/seen_posts.go @@ -20,6 +20,7 @@ func (p *PostsCommandHandler) SeenPosts(ctx context.Context, req *gen.PostsSeenR rawReq, err := jsoniter.Marshal(seenPostsRequest) if err != nil { + p.log.Error(err, true, "SeenPosts: marshal") return &gen.SeenPostsInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -28,6 +29,7 @@ func (p *PostsCommandHandler) SeenPosts(ctx context.Context, req *gen.PostsSeenR rawResp, err := p.producer.Request(ctx, posts.PayloadToEnvelope(posts.CmdSeen, uuid.New().String(), rawReq), 10*time.Second) if err != nil { + p.log.Error(err, true, "SeenPosts: request") return &gen.SeenPostsInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -37,6 +39,7 @@ func (p *PostsCommandHandler) SeenPosts(ctx context.Context, req *gen.PostsSeenR var resp posts.KafkaResponse err = jsoniter.Unmarshal(rawResp, &resp) if err != nil { + p.log.Error(err, true, "SeenPosts: unmarshal response") return &gen.SeenPostsInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), diff --git a/internal/delivery_http/posts/posts_command_producer/update_post.go b/internal/delivery_http/posts/posts_command_producer/update_post.go index afa281a..bcf8b38 100644 --- a/internal/delivery_http/posts/posts_command_producer/update_post.go +++ b/internal/delivery_http/posts/posts_command_producer/update_post.go @@ -21,6 +21,7 @@ func (p *PostsCommandHandler) UpdatePostById(ctx context.Context, req *gen.PostU rawReq, err := jsoniter.Marshal(updatePostRequest) if err != nil { + p.log.Error(err, true, "UpdatePostById: marshal") return &gen.UpdatePostByIdInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -29,7 +30,7 @@ func (p *PostsCommandHandler) UpdatePostById(ctx context.Context, req *gen.PostU rawResp, err := p.producer.Request(ctx, posts.PayloadToEnvelope(posts.CmdUpdate, params.PostId.String(), rawReq), 5*time.Second) if err != nil { - // TODO: TIMEOUT OR PUBLISH ERROR - 500 + p.log.Error(err, true, "UpdatePostById: request") return &gen.UpdatePostByIdInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), @@ -39,6 +40,7 @@ func (p *PostsCommandHandler) UpdatePostById(ctx context.Context, req *gen.PostU var resp posts.KafkaResponse err = jsoniter.Unmarshal(rawResp, &resp) if err != nil { + p.log.Error(err, true, "UpdatePostById: unmarshal response") return &gen.UpdatePostByIdInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), diff --git a/internal/delivery_http/posts/posts_query/check_group_id.go b/internal/delivery_http/posts/posts_query/check_group_id.go index 5f49253..f4c8f87 100644 --- a/internal/delivery_http/posts/posts_query/check_group_id.go +++ b/internal/delivery_http/posts/posts_query/check_group_id.go @@ -21,6 +21,7 @@ func (p *PostsQueryHandler) CheckGroupId(ctx context.Context, params gen.CheckGr }, nil case strings.Contains(err.Error(), constants.InternalMsg): + p.log.Error(err, true, "CheckGroupId: get by group id") return &gen.CheckGroupIdInternalServerError{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), diff --git a/internal/delivery_http/posts/posts_query/check_group_ids.go b/internal/delivery_http/posts/posts_query/check_group_ids.go index 8830cef..1ba7a7c 100644 --- a/internal/delivery_http/posts/posts_query/check_group_ids.go +++ b/internal/delivery_http/posts/posts_query/check_group_ids.go @@ -22,6 +22,7 @@ func (p *PostsQueryHandler) CheckGroupIds(ctx context.Context) (gen.CheckGroupId }, nil case strings.Contains(err.Error(), constants.InternalMsg): + p.log.Error(err, true, "CheckGroupIds: check group ids") return &gen.CheckGroupIdsNotFound{ ErrorCode: http.StatusInternalServerError, Message: err.Error(), diff --git a/internal/delivery_http/posts/posts_query/init.go b/internal/delivery_http/posts/posts_query/init.go index 165f680..bb380ee 100644 --- a/internal/delivery_http/posts/posts_query/init.go +++ b/internal/delivery_http/posts/posts_query/init.go @@ -4,6 +4,7 @@ import ( "context" "github.com/google/uuid" + "github.com/goriiin/kotyari-bots_backend/internal/logger" "github.com/goriiin/kotyari-bots_backend/internal/model" ) @@ -17,10 +18,12 @@ type postsQueryRepository interface { type PostsQueryHandler struct { repo postsQueryRepository + log *logger.Logger } -func NewPostsQueryHandler(repo postsQueryRepository) *PostsQueryHandler { +func NewPostsQueryHandler(repo postsQueryRepository, log *logger.Logger) *PostsQueryHandler { return &PostsQueryHandler{ repo: repo, + log: log, } } diff --git a/internal/delivery_http/posts/posts_query/list_posts.go b/internal/delivery_http/posts/posts_query/list_posts.go index 2a259d6..5786b9b 100644 --- a/internal/delivery_http/posts/posts_query/list_posts.go +++ b/internal/delivery_http/posts/posts_query/list_posts.go @@ -11,6 +11,7 @@ import ( func (p *PostsQueryHandler) ListPosts(ctx context.Context) (gen.ListPostsRes, error) { postsModels, err := p.repo.ListPosts(ctx) if err != nil { + p.log.Error(err, true, "ListPosts: list posts") return &gen.ListPostsInternalServerError{ErrorCode: http.StatusInternalServerError, Message: err.Error()}, nil } diff --git a/internal/delivery_http/profiles/create.go b/internal/delivery_http/profiles/create.go index d1a49d3..1c7a8df 100644 --- a/internal/delivery_http/profiles/create.go +++ b/internal/delivery_http/profiles/create.go @@ -15,6 +15,7 @@ func (h *HTTPHandler) CreateMyProfile(ctx context.Context, req *gen.ProfileInput if errors.Is(err, constants.ErrValidation) { return &gen.CreateMyProfileBadRequest{ErrorCode: constants.ErrValidationMsg, Message: err.Error()}, nil } + h.log.Error(err, true, "CreateMyProfile: create") return &gen.CreateMyProfileInternalServerError{ErrorCode: constants.ErrInternalMsg, Message: err.Error()}, nil } return modelToHttpDTO(&created), nil diff --git a/internal/delivery_http/profiles/delete.go b/internal/delivery_http/profiles/delete.go index 9d52c37..5a048c6 100644 --- a/internal/delivery_http/profiles/delete.go +++ b/internal/delivery_http/profiles/delete.go @@ -14,6 +14,7 @@ func (h *HTTPHandler) DeleteProfileById(ctx context.Context, params gen.DeletePr if errors.Is(err, constants.ErrNotFound) { return &gen.DeleteProfileByIdNotFound{ErrorCode: constants.ErrNotFoundMsg, Message: "profile not found"}, nil } + h.log.Error(err, true, "DeleteProfileById: delete") return &gen.DeleteProfileByIdInternalServerError{ErrorCode: constants.ErrInternalMsg, Message: err.Error()}, nil } return &gen.NoContent{}, nil diff --git a/internal/delivery_http/profiles/get.go b/internal/delivery_http/profiles/get.go index c5f27d5..e8b81b3 100644 --- a/internal/delivery_http/profiles/get.go +++ b/internal/delivery_http/profiles/get.go @@ -14,6 +14,7 @@ func (h *HTTPHandler) GetProfileById(ctx context.Context, params gen.GetProfileB if errors.Is(err, constants.ErrNotFound) { return &gen.GetProfileByIdNotFound{ErrorCode: constants.ErrNotFoundMsg, Message: "profile not found"}, nil } + h.log.Error(err, true, "GetProfileById: get") return &gen.GetProfileByIdInternalServerError{ErrorCode: constants.ErrInternalMsg, Message: err.Error()}, nil } return modelToHttpDTO(&p), nil diff --git a/internal/delivery_http/profiles/init.go b/internal/delivery_http/profiles/init.go index 112566f..701d878 100644 --- a/internal/delivery_http/profiles/init.go +++ b/internal/delivery_http/profiles/init.go @@ -4,6 +4,7 @@ import ( "context" "github.com/google/uuid" + "github.com/goriiin/kotyari-bots_backend/internal/logger" "github.com/goriiin/kotyari-bots_backend/internal/model" ) @@ -17,9 +18,13 @@ type usecase interface { } type HTTPHandler struct { - u usecase + u usecase + log *logger.Logger } -func NewHTTPHandler(u usecase) *HTTPHandler { - return &HTTPHandler{u: u} +func NewHTTPHandler(u usecase, log *logger.Logger) *HTTPHandler { + return &HTTPHandler{ + u: u, + log: log, + } } diff --git a/internal/delivery_http/profiles/list.go b/internal/delivery_http/profiles/list.go index 523b14a..2a1f578 100644 --- a/internal/delivery_http/profiles/list.go +++ b/internal/delivery_http/profiles/list.go @@ -10,6 +10,7 @@ import ( func (h *HTTPHandler) ListMyProfiles(ctx context.Context) (gen.ListMyProfilesRes, error) { profiles, err := h.u.List(ctx) if err != nil { + h.log.Error(err, true, "ListMyProfiles: list") return &gen.ListMyProfilesInternalServerError{ErrorCode: constants.ErrInternalMsg, Message: err.Error()}, nil } diff --git a/internal/delivery_http/profiles/update.go b/internal/delivery_http/profiles/update.go index 56b246c..8ef3a13 100644 --- a/internal/delivery_http/profiles/update.go +++ b/internal/delivery_http/profiles/update.go @@ -17,6 +17,7 @@ func (h *HTTPHandler) UpdateProfileById(ctx context.Context, req *gen.ProfileInp if errors.Is(err, constants.ErrValidation) { return &gen.UpdateProfileByIdBadRequest{ErrorCode: constants.ErrValidationMsg, Message: err.Error()}, nil } + h.log.Error(err, true, "UpdateProfileById: update") return &gen.UpdateProfileByIdInternalServerError{ErrorCode: constants.ErrInternalMsg, Message: err.Error()}, nil } return modelToHttpDTO(&updated), nil