diff --git a/backend/internal/social/handler.go b/backend/internal/social/handler.go index 817e2e1..1edce96 100644 --- a/backend/internal/social/handler.go +++ b/backend/internal/social/handler.go @@ -1,6 +1,7 @@ package social import ( + "errors" "feedsystem_video_go/internal/account" "feedsystem_video_go/internal/apierror" "feedsystem_video_go/internal/middleware/jwt" @@ -9,6 +10,14 @@ import ( "github.com/gin-gonic/gin" ) +// classifySocialError 只补一条本地语义:自关注是客户端错误,不是数据库故障。 +func classifySocialError(err error) int { + if errors.Is(err, ErrCannotFollowSelf) { + return http.StatusBadRequest + } + return apierror.ClassifyHTTPStatus(err) +} + type SocialHandler struct { service *SocialService } @@ -36,11 +45,12 @@ func (h *SocialHandler) Follow(c *gin.Context) { FollowerID: FollowerID, VloggerID: req.VloggerID, } - if err := h.service.Follow(c.Request.Context(), social); err != nil { - c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()}) + created, err := h.service.Follow(c.Request.Context(), social) + if err != nil { + c.JSON(classifySocialError(err), gin.H{"error": err.Error()}) return } - c.JSON(http.StatusOK, gin.H{"message": "followed"}) + c.JSON(http.StatusOK, gin.H{"message": "followed", "created": created}) } func (h *SocialHandler) Unfollow(c *gin.Context) { @@ -62,11 +72,12 @@ func (h *SocialHandler) Unfollow(c *gin.Context) { FollowerID: FollowerID, VloggerID: req.VloggerID, } - if err := h.service.Unfollow(c.Request.Context(), social); err != nil { - c.JSON(apierror.ClassifyHTTPStatus(err), gin.H{"error": err.Error()}) + deleted, err := h.service.Unfollow(c.Request.Context(), social) + if err != nil { + c.JSON(classifySocialError(err), gin.H{"error": err.Error()}) return } - c.JSON(http.StatusOK, gin.H{"message": "unfollowed"}) + c.JSON(http.StatusOK, gin.H{"message": "unfollowed", "deleted": deleted}) } func (h *SocialHandler) GetAllFollowers(c *gin.Context) { diff --git a/backend/internal/social/handler_test.go b/backend/internal/social/handler_test.go new file mode 100644 index 0000000..e65d902 --- /dev/null +++ b/backend/internal/social/handler_test.go @@ -0,0 +1,85 @@ +package social + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func newTestHandler(t *testing.T) (*SocialHandler, *fakeStore) { + t.Helper() + gin.SetMode(gin.TestMode) + store := newFakeStore() + notifier := &fakeNotifier{} + return NewSocialHandler(newTestService(store, fakeAccounts{}, notifier)), store +} + +func postSocial(t *testing.T, h *SocialHandler, accountID uint, action, body string) *httptest.ResponseRecorder { + t.Helper() + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest(http.MethodPost, "/social/"+action, strings.NewReader(body)) + c.Request.Header.Set("Content-Type", "application/json") + c.Set("accountID", accountID) + if action == "follow" { + h.Follow(c) + } else { + h.Unfollow(c) + } + return w +} + +func TestSocialHandler_Follow_SelfReturnsBadRequest(t *testing.T) { + h, _ := newTestHandler(t) + + w := postSocial(t, h, 1, "follow", `{"vlogger_id":1}`) + if w.Code != http.StatusBadRequest { + t.Fatalf("自关注状态码 = %d,想要 %d", w.Code, http.StatusBadRequest) + } + if !strings.Contains(w.Body.String(), "can not follow self") { + t.Fatalf("响应体 = %s,想要包含 can not follow self", w.Body.String()) + } +} + +func TestSocialHandler_Follow_DuplicateReturnsOK(t *testing.T) { + h, store := newTestHandler(t) + store.rows[[2]uint{1, 2}] = true + + w := postSocial(t, h, 1, "follow", `{"vlogger_id":2}`) + if w.Code != http.StatusOK { + t.Fatalf("重复关注状态码 = %d,想要 %d", w.Code, http.StatusOK) + } + var resp struct { + Message string `json:"message"` + Created bool `json:"created"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("解析响应体失败: %v", err) + } + if resp.Message != "followed" || resp.Created { + t.Fatalf("重复关注响应 = %+v,想要 message=followed created=false", resp) + } +} + +func TestSocialHandler_Unfollow_DuplicateReturnsOK(t *testing.T) { + h, _ := newTestHandler(t) + + w := postSocial(t, h, 1, "unfollow", `{"vlogger_id":2}`) + if w.Code != http.StatusOK { + t.Fatalf("重复取关状态码 = %d,想要 %d", w.Code, http.StatusOK) + } + var resp struct { + Message string `json:"message"` + Deleted bool `json:"deleted"` + } + if err := json.Unmarshal(w.Body.Bytes(), &resp); err != nil { + t.Fatalf("解析响应体失败: %v", err) + } + if resp.Message != "unfollowed" || resp.Deleted { + t.Fatalf("重复取关响应 = %+v,想要 message=unfollowed deleted=false", resp) + } +} diff --git a/backend/internal/social/repo.go b/backend/internal/social/repo.go index d599f5a..9c7e09f 100644 --- a/backend/internal/social/repo.go +++ b/backend/internal/social/repo.go @@ -5,6 +5,7 @@ import ( "feedsystem_video_go/internal/account" "gorm.io/gorm" + "gorm.io/gorm/clause" ) type SocialRepository struct { @@ -15,14 +16,27 @@ func NewSocialRepository(db *gorm.DB) *SocialRepository { return &SocialRepository{db: db} } -func (r *SocialRepository) Follow(ctx context.Context, social *Social) error { - return r.db.WithContext(ctx).Create(social).Error +// Follow 返回本次是否真的插入关系:重复关注是幂等成功,不是错误。 +// 判重交给唯一索引 idx_social_follower_vlogger,OnConflict 把冲突变成一次不报错的 SQL。 +func (r *SocialRepository) Follow(ctx context.Context, social *Social) (bool, error) { + res := r.db.WithContext(ctx). + Clauses(clause.OnConflict{DoNothing: true}). + Create(social) + if res.Error != nil { + return false, res.Error + } + return res.RowsAffected > 0, nil } -func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) error { - return r.db.WithContext(ctx). +// Unfollow 用影响行数回答"这次是否真的删掉":第二次取关是空操作。 +func (r *SocialRepository) Unfollow(ctx context.Context, social *Social) (bool, error) { + res := r.db.WithContext(ctx). Where("follower_id = ? AND vlogger_id = ?", social.FollowerID, social.VloggerID). - Delete(&Social{}).Error + Delete(&Social{}) + if res.Error != nil { + return false, res.Error + } + return res.RowsAffected > 0, nil } func (r *SocialRepository) GetAllFollowers(ctx context.Context, VloggerID uint) ([]*account.Account, error) { diff --git a/backend/internal/social/repo_integration_test.go b/backend/internal/social/repo_integration_test.go new file mode 100644 index 0000000..b45d9bf --- /dev/null +++ b/backend/internal/social/repo_integration_test.go @@ -0,0 +1,87 @@ +//go:build integration + +package social + +import ( + "context" + "os" + "strings" + "testing" + + "gorm.io/driver/mysql" + "gorm.io/gorm" + "gorm.io/gorm/logger" +) + +// 判重由唯一索引 idx_social_follower_vlogger 裁决,"这次有没有真的写入"只能对着 +// 真实 MySQL 验证:没有数据库就没有被测对象。 +// +// MYSQL_TEST_DSN='root:123456@tcp(127.0.0.1:3306)/feedsystem_test?charset=utf8mb4&parseTime=True&loc=Local' \ +// go test -tags integration -count=1 ./internal/social/ + +func newSocialTestDB(t *testing.T) *gorm.DB { + t.Helper() + dsn := os.Getenv("MYSQL_TEST_DSN") + if dsn == "" { + t.Skip("MYSQL_TEST_DSN 未设置:需要真实 MySQL(见本文件顶部注释)") + } + if strings.Contains(dsn, "clientFoundRows") { + t.Fatalf("测试 DSN 不能带 clientFoundRows:它会让 RowsAffected 判重失效") + } + db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{ + Logger: logger.Default.LogMode(logger.Silent), + }) + if err != nil { + t.Fatalf("connect mysql: %v", err) + } + if err := db.Migrator().DropTable(&Social{}); err != nil { + t.Fatalf("drop table: %v", err) + } + if err := db.AutoMigrate(&Social{}); err != nil { + t.Fatalf("migrate: %v", err) + } + return db +} + +func TestSocialRepository_Follow_DuplicateReportsNotCreated(t *testing.T) { + db := newSocialTestDB(t) + repo := NewSocialRepository(db) + ctx := context.Background() + + created, err := repo.Follow(ctx, &Social{FollowerID: 1, VloggerID: 2}) + if err != nil || !created { + t.Fatalf("首次关注 = (%v, %v),想要 (true, nil)", created, err) + } + + created, err = repo.Follow(ctx, &Social{FollowerID: 1, VloggerID: 2}) + if err != nil || created { + t.Fatalf("重复关注 = (%v, %v),想要 (false, nil)", created, err) + } + + var count int64 + if err := db.Model(&Social{}).Count(&count).Error; err != nil { + t.Fatalf("count: %v", err) + } + if count != 1 { + t.Fatalf("socials 行数 = %d,想要 1", count) + } +} + +func TestSocialRepository_Unfollow_SecondCallReportsNotDeleted(t *testing.T) { + db := newSocialTestDB(t) + repo := NewSocialRepository(db) + ctx := context.Background() + if _, err := repo.Follow(ctx, &Social{FollowerID: 3, VloggerID: 4}); err != nil { + t.Fatalf("准备关注失败: %v", err) + } + + deleted, err := repo.Unfollow(ctx, &Social{FollowerID: 3, VloggerID: 4}) + if err != nil || !deleted { + t.Fatalf("首次取关 = (%v, %v),想要 (true, nil)", deleted, err) + } + + deleted, err = repo.Unfollow(ctx, &Social{FollowerID: 3, VloggerID: 4}) + if err != nil || deleted { + t.Fatalf("重复取关 = (%v, %v),想要 (false, nil)", deleted, err) + } +} diff --git a/backend/internal/social/service.go b/backend/internal/social/service.go index b084644..942aa26 100644 --- a/backend/internal/social/service.go +++ b/backend/internal/social/service.go @@ -4,91 +4,92 @@ import ( "context" "errors" "feedsystem_video_go/internal/account" - "feedsystem_video_go/internal/middleware/rabbitmq" rediscache "feedsystem_video_go/internal/middleware/redis" "log" ) +// ErrCannotFollowSelf 是客户端错误:自关注不写库,也不发消息。 +var ErrCannotFollowSelf = errors.New("can not follow self") + +// socialStore 只声明 SocialService 用到的方法,测试里用 fake 驱动。 +type socialStore interface { + Follow(ctx context.Context, social *Social) (bool, error) + Unfollow(ctx context.Context, social *Social) (bool, error) + IsFollowed(ctx context.Context, social *Social) (bool, error) + GetAllFollowers(ctx context.Context, vloggerID uint) ([]*account.Account, error) + GetAllVloggers(ctx context.Context, followerID uint) ([]*account.Account, error) + CountFollowers(ctx context.Context, vloggerID uint) (int64, error) + CountVloggers(ctx context.Context, followerID uint) (int64, error) +} + +type accountFinder interface { + FindByID(ctx context.Context, id uint) (*account.Account, error) +} + +// followNotifier 只暴露关注通知。真实实现 *rabbitmq.SocialMQ 在 nil 接收者上返回 error, +// 所以 MQ 未启用时这里只会多一条日志。 +type followNotifier interface { + Follow(ctx context.Context, followerID, vloggerID uint) error +} + type SocialService struct { - repo *SocialRepository - accountrepo *account.AccountRepository - socialMQ *rabbitmq.SocialMQ + repo socialStore + accountrepo accountFinder + socialMQ followNotifier cache *rediscache.Client } -func NewSocialService(repo *SocialRepository, accountrepo *account.AccountRepository, socialMQ *rabbitmq.SocialMQ, cache *rediscache.Client) *SocialService { +func NewSocialService(repo socialStore, accountrepo accountFinder, socialMQ followNotifier, cache *rediscache.Client) *SocialService { return &SocialService{repo: repo, accountrepo: accountrepo, socialMQ: socialMQ, cache: cache} } -func (s *SocialService) Follow(ctx context.Context, social *Social) error { - _, err := s.accountrepo.FindByID(ctx, social.FollowerID) - if err != nil { - return err - } - _, err = s.accountrepo.FindByID(ctx, social.VloggerID) - if err != nil { - return err - } +// Follow 返回本次是否真的插入关系:重复关注返回 (false, nil)。 +func (s *SocialService) Follow(ctx context.Context, social *Social) (bool, error) { if social.FollowerID == social.VloggerID { - return errors.New("can not follow self") + return false, ErrCannotFollowSelf } - isFollowed, err := s.repo.IsFollowed(ctx, social) + if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil { + return false, err + } + if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil { + return false, err + } + + created, err := s.repo.Follow(ctx, social) if err != nil { - return err + return false, err } - if isFollowed { - return errors.New("already followed") + if !created { + // 关系已在,缓存和通知都已经是“已关注”状态。 + return false, nil } - // 先写 DB,确保数据持久化 - if err := s.repo.Follow(ctx, social); err != nil { - return err - } - - // DB 成功后,失效该用户的关注列表缓存 s.invalidateFollowingFeedCache(context.Background(), social.FollowerID) - - // 最后发 MQ(用于通知),失败只记日志不影响业务 - if s.socialMQ != nil { - if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil { - log.Printf("social MQ Follow 发布失败: %v", err) - } + if err := s.socialMQ.Follow(ctx, social.FollowerID, social.VloggerID); err != nil { + log.Printf("social MQ Follow 发布失败: %v", err) } - return nil + return true, nil } -func (s *SocialService) Unfollow(ctx context.Context, social *Social) error { - _, err := s.accountrepo.FindByID(ctx, social.FollowerID) - if err != nil { - return err +// Unfollow 返回本次是否真的删掉关系:重复取关返回 (false, nil)。 +func (s *SocialService) Unfollow(ctx context.Context, social *Social) (bool, error) { + if _, err := s.accountrepo.FindByID(ctx, social.FollowerID); err != nil { + return false, err } - _, err = s.accountrepo.FindByID(ctx, social.VloggerID) - if err != nil { - return err - } - isFollowed, err := s.repo.IsFollowed(ctx, social) - if err != nil { - return err - } - if !isFollowed { - return errors.New("not followed") + if _, err := s.accountrepo.FindByID(ctx, social.VloggerID); err != nil { + return false, err } - // 先写 DB - if err := s.repo.Unfollow(ctx, social); err != nil { - return err + deleted, err := s.repo.Unfollow(ctx, social) + if err != nil { + return false, err + } + if !deleted { + return false, nil } - // 失效缓存 s.invalidateFollowingFeedCache(context.Background(), social.FollowerID) - - // 最后发 MQ - if s.socialMQ != nil { - if err := s.socialMQ.UnFollow(ctx, social.FollowerID, social.VloggerID); err != nil { - log.Printf("social MQ UnFollow 发布失败: %v", err) - } - } - return nil + return true, nil } // 失效关注列表缓存,确保下次查询时能获取到最新的关注列表 diff --git a/backend/internal/social/service_test.go b/backend/internal/social/service_test.go new file mode 100644 index 0000000..58c6c12 --- /dev/null +++ b/backend/internal/social/service_test.go @@ -0,0 +1,193 @@ +package social + +import ( + "context" + "errors" + "testing" + + "feedsystem_video_go/internal/account" +) + +// fakeStore 用内存行模拟 socials 表:返回值就是"这张表这次有没有变"。 +type fakeStore struct { + rows map[[2]uint]bool + err error +} + +func newFakeStore() *fakeStore { + return &fakeStore{rows: map[[2]uint]bool{}} +} + +func (f *fakeStore) Follow(ctx context.Context, social *Social) (bool, error) { + if f.err != nil { + return false, f.err + } + key := [2]uint{social.FollowerID, social.VloggerID} + if f.rows[key] { + return false, nil + } + f.rows[key] = true + return true, nil +} + +func (f *fakeStore) Unfollow(ctx context.Context, social *Social) (bool, error) { + if f.err != nil { + return false, f.err + } + key := [2]uint{social.FollowerID, social.VloggerID} + if !f.rows[key] { + return false, nil + } + delete(f.rows, key) + return true, nil +} + +func (f *fakeStore) IsFollowed(ctx context.Context, social *Social) (bool, error) { + return f.rows[[2]uint{social.FollowerID, social.VloggerID}], nil +} + +func (f *fakeStore) GetAllFollowers(ctx context.Context, vloggerID uint) ([]*account.Account, error) { + return nil, nil +} + +func (f *fakeStore) GetAllVloggers(ctx context.Context, followerID uint) ([]*account.Account, error) { + return nil, nil +} + +func (f *fakeStore) CountFollowers(ctx context.Context, vloggerID uint) (int64, error) { + return 0, nil +} + +func (f *fakeStore) CountVloggers(ctx context.Context, followerID uint) (int64, error) { + return 0, nil +} + +type fakeAccounts struct { + err error +} + +func (f fakeAccounts) FindByID(ctx context.Context, id uint) (*account.Account, error) { + if f.err != nil { + return nil, f.err + } + return &account.Account{ID: id}, nil +} + +// fakeNotifier 记录真正发出去的通知事件,而不是调用次数。 +type fakeNotifier struct { + published [][2]uint + err error +} + +func (f *fakeNotifier) Follow(ctx context.Context, followerID, vloggerID uint) error { + f.published = append(f.published, [2]uint{followerID, vloggerID}) + return f.err +} + +func newTestService(store socialStore, accounts accountFinder, notifier followNotifier) *SocialService { + return NewSocialService(store, accounts, notifier, nil) +} + +func TestSocialService_Follow_SecondCallIsNoop(t *testing.T) { + store := newFakeStore() + notifier := &fakeNotifier{} + svc := newTestService(store, fakeAccounts{}, notifier) + rel := &Social{ID: 1, FollowerID: 7, VloggerID: 9} + + created, err := svc.Follow(context.Background(), rel) + if err != nil || !created { + t.Fatalf("首次关注 = (%v, %v),想要 (true, nil)", created, err) + } + + created, err = svc.Follow(context.Background(), &Social{FollowerID: 7, VloggerID: 9}) + if err != nil || created { + t.Fatalf("重复关注 = (%v, %v),想要 (false, nil)", created, err) + } + if len(store.rows) != 1 { + t.Fatalf("socials 行数 = %d,想要 1", len(store.rows)) + } + // 重复点击不该产生第二条通知。 + if len(notifier.published) != 1 { + t.Fatalf("通知事件数 = %d,想要 1", len(notifier.published)) + } +} + +func TestSocialService_Follow_SelfIsRejected(t *testing.T) { + store := newFakeStore() + notifier := &fakeNotifier{} + svc := newTestService(store, fakeAccounts{}, notifier) + + created, err := svc.Follow(context.Background(), &Social{FollowerID: 3, VloggerID: 3}) + if created || !errors.Is(err, ErrCannotFollowSelf) { + t.Fatalf("自关注 = (%v, %v),想要 (false, ErrCannotFollowSelf)", created, err) + } + if len(store.rows) != 0 { + t.Fatalf("自关注写入了 %d 行,想要 0", len(store.rows)) + } + if len(notifier.published) != 0 { + t.Fatalf("自关注发出了 %d 条通知,想要 0", len(notifier.published)) + } +} + +func TestSocialService_Follow_RepoErrorPropagates(t *testing.T) { + repoErr := errors.New("db is down") + store := newFakeStore() + store.err = repoErr + notifier := &fakeNotifier{} + svc := newTestService(store, fakeAccounts{}, notifier) + + created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2}) + if created || !errors.Is(err, repoErr) { + t.Fatalf("仓储报错 = (%v, %v),想要 (false, db is down)", created, err) + } + if len(notifier.published) != 0 { + t.Fatalf("仓储报错仍发出了 %d 条通知,想要 0", len(notifier.published)) + } +} + +func TestSocialService_Follow_NotifyFailureKeepsSuccess(t *testing.T) { + store := newFakeStore() + notifier := &fakeNotifier{err: errors.New("mq is down")} + svc := newTestService(store, fakeAccounts{}, notifier) + + created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2}) + if !created || err != nil { + t.Fatalf("通知失败时 Follow = (%v, %v),想要 (true, nil)", created, err) + } +} + +func TestSocialService_Follow_AccountLookupErrorPropagates(t *testing.T) { + lookupErr := errors.New("account not found") + store := newFakeStore() + svc := newTestService(store, fakeAccounts{err: lookupErr}, &fakeNotifier{}) + + created, err := svc.Follow(context.Background(), &Social{FollowerID: 1, VloggerID: 2}) + if created || !errors.Is(err, lookupErr) { + t.Fatalf("账号校验失败 = (%v, %v),想要 (false, account not found)", created, err) + } + if len(store.rows) != 0 { + t.Fatalf("账号校验失败仍写入了 %d 行,想要 0", len(store.rows)) + } +} + +func TestSocialService_Unfollow_SecondCallIsNoop(t *testing.T) { + store := newFakeStore() + notifier := &fakeNotifier{} + svc := newTestService(store, fakeAccounts{}, notifier) + if _, err := svc.Follow(context.Background(), &Social{FollowerID: 7, VloggerID: 9}); err != nil { + t.Fatalf("准备关注失败: %v", err) + } + + deleted, err := svc.Unfollow(context.Background(), &Social{FollowerID: 7, VloggerID: 9}) + if err != nil || !deleted { + t.Fatalf("首次取关 = (%v, %v),想要 (true, nil)", deleted, err) + } + + deleted, err = svc.Unfollow(context.Background(), &Social{FollowerID: 7, VloggerID: 9}) + if err != nil || deleted { + t.Fatalf("重复取关 = (%v, %v),想要 (false, nil)", deleted, err) + } + if len(store.rows) != 0 { + t.Fatalf("取关后还有 %d 行,想要 0", len(store.rows)) + } +} diff --git a/backend/internal/worker/socialworker.go b/backend/internal/worker/socialworker.go index b8e8adc..a02f6ee 100644 --- a/backend/internal/worker/socialworker.go +++ b/backend/internal/worker/socialworker.go @@ -45,7 +45,7 @@ func (w *SocialWorker) process(ctx context.Context, d amqp.Delivery) error { switch evt.Action { case "follow": - err := w.repo.Follow(ctx, &social.Social{ + _, err := w.repo.Follow(ctx, &social.Social{ FollowerID: evt.FollowerID, VloggerID: evt.VloggerID, }) @@ -59,10 +59,11 @@ func (w *SocialWorker) process(ctx context.Context, d amqp.Delivery) error { } return err case "unfollow": - return w.repo.Unfollow(ctx, &social.Social{ + _, err := w.repo.Unfollow(ctx, &social.Social{ FollowerID: evt.FollowerID, VloggerID: evt.VloggerID, }) + return err default: return rabbitmq.Permanent(fmt.Errorf("social worker: unknown action %q", evt.Action)) }