Stage 17 round 5 — backend/correctness bug fixes
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 9s
CI / integration (pull_request) Failing after 12s
CI / ui (pull_request) Successful in 30s
CI / gate (pull_request) Failing after 1s
CI / deploy (pull_request) Has been skipped
CI / changes (pull_request) Successful in 2s
CI / unit (pull_request) Successful in 9s
CI / integration (pull_request) Failing after 12s
CI / ui (pull_request) Successful in 30s
CI / gate (pull_request) Failing after 1s
CI / deploy (pull_request) Has been skipped
- Resign on the opponent's turn: engine ResignSeat(seat) resigns a specific seat (not just toMove); game.Resign bypasses the turn check and forfeits the actor's seat. - Quick-match cancel was a UI no-op (only stopped polling): add the full path (REST /lobby/cancel -> gateway lobby.cancel -> client) and clear the matchmaker's pending result on Cancel, so a cancelled search is dequeued (no 'already queued', no later robot-substituted game). NewGame dequeues on cancel and on abandon. - Lobby win/loss: result.ts ranked by score, so a 0-0 resignation read as a win. The winner now takes rank 1 and the viewer is placed from rank 2 — matching the game-detail screen. - Friend request to a robot: robots no longer block requests; the request stays pending and expires (friendRequestTTL), mirroring a human who ignores it. - Nudge cooldown: ErrNudgeTooSoon now maps to a distinct nudge_too_soon code with a correct message; the chat nudge button disables during the hourly cooldown; the nudge note reads 'Waiting for your move!' (button keeps the Nudge action label). Tests: engine/service off-turn resign, matchmaker cancel-clears-result, friend-to-robot inttest, result.ts 0-0 resignation, nudge_too_soon mapping.
This commit is contained in:
@@ -112,17 +112,19 @@ func (s *Store) ProvisionByIdentity(ctx context.Context, kind, externalID string
|
||||
}
|
||||
|
||||
// ProvisionRobot provisions (or finds) the durable account backing a robot pool
|
||||
// member: a KindRobot identity carrying displayName, with chat and friend requests
|
||||
// blocked so the robot never engages socially. Robot names are system-generated, not
|
||||
// player-edited, so they bypass the editable display-name validation and may carry
|
||||
// forms the editor rejects (an abbreviated surname like "Peter J."). It is idempotent:
|
||||
// repeated calls converge the display name and both block flags.
|
||||
// member: a KindRobot identity carrying displayName, with chat blocked but friend
|
||||
// requests NOT blocked — a request to a robot is accepted as pending and, since the
|
||||
// robot never responds, simply expires (friendRequestTTL), exactly mirroring a human
|
||||
// who ignores the request. Robot names are system-generated, not player-edited, so they
|
||||
// bypass the editable display-name validation and may carry forms the editor rejects (an
|
||||
// abbreviated surname like "Peter J."). It is idempotent: repeated calls converge the
|
||||
// display name and both block flags.
|
||||
func (s *Store) ProvisionRobot(ctx context.Context, externalID, displayName string) (Account, error) {
|
||||
acc, err := s.provision(ctx, KindRobot, externalID, provisionSeed{displayName: displayName})
|
||||
if err != nil {
|
||||
return Account{}, err
|
||||
}
|
||||
if acc.DisplayName == displayName && acc.BlockChat && acc.BlockFriendRequests {
|
||||
if acc.DisplayName == displayName && acc.BlockChat && !acc.BlockFriendRequests {
|
||||
return acc, nil
|
||||
}
|
||||
stmt := table.Accounts.UPDATE(
|
||||
@@ -130,7 +132,7 @@ func (s *Store) ProvisionRobot(ctx context.Context, externalID, displayName stri
|
||||
table.Accounts.BlockFriendRequests, table.Accounts.UpdatedAt,
|
||||
).SET(
|
||||
postgres.String(displayName), postgres.Bool(true),
|
||||
postgres.Bool(true), postgres.TimestampzT(time.Now().UTC()),
|
||||
postgres.Bool(false), postgres.TimestampzT(time.Now().UTC()),
|
||||
).WHERE(table.Accounts.AccountID.EQ(postgres.UUID(acc.ID))).
|
||||
RETURNING(table.Accounts.AllColumns)
|
||||
|
||||
|
||||
@@ -248,17 +248,29 @@ func (g *Game) Exchange(tiles []byte) (MoveRecord, error) {
|
||||
// winning regardless of score. A missed-turn timeout reuses Resign in the game
|
||||
// domain, so it inherits this win/loss.
|
||||
func (g *Game) Resign() (MoveRecord, error) {
|
||||
return g.ResignSeat(g.toMove)
|
||||
}
|
||||
|
||||
// ResignSeat resigns a specific seat regardless of whose turn it is, so a player
|
||||
// may forfeit on the opponent's turn. The resigning seat always loses (winner()
|
||||
// skips resigned seats). The turn cursor only advances when the seat that resigned
|
||||
// was the one to move; resigning an off-turn seat leaves the current player's turn
|
||||
// intact. It returns ErrGameOver on a finished game or for an out-of-range or
|
||||
// already-resigned seat.
|
||||
func (g *Game) ResignSeat(seat int) (MoveRecord, error) {
|
||||
if g.over {
|
||||
return MoveRecord{}, ErrGameOver
|
||||
}
|
||||
player := g.toMove
|
||||
g.resigned[player] = true
|
||||
g.disposeHand(player)
|
||||
rec := MoveRecord{Player: player, Action: ActionResign, Total: g.scores[player]}
|
||||
if seat < 0 || seat >= len(g.hands) || g.resigned[seat] {
|
||||
return MoveRecord{}, ErrGameOver
|
||||
}
|
||||
g.resigned[seat] = true
|
||||
g.disposeHand(seat)
|
||||
rec := MoveRecord{Player: seat, Action: ActionResign, Total: g.scores[seat]}
|
||||
g.log = append(g.log, rec)
|
||||
if g.activeCount() <= 1 {
|
||||
g.finish(EndResign)
|
||||
} else {
|
||||
} else if seat == g.toMove {
|
||||
g.advance()
|
||||
}
|
||||
return rec, nil
|
||||
|
||||
@@ -69,6 +69,39 @@ func TestResignTrailingPlayerLoses(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestResignSeatOffTurn covers a forfeit on the opponent's turn: after player 0
|
||||
// moves it is player 1's turn, yet player 0 resigns its own seat — the resigner
|
||||
// loses, the opponent wins, and the game ends.
|
||||
func TestResignSeatOffTurn(t *testing.T) {
|
||||
g := openingGame(t)
|
||||
|
||||
hint, ok := g.HintView()
|
||||
if !ok {
|
||||
t.Fatal("opening game has no hint")
|
||||
}
|
||||
if _, err := g.SubmitPlay(hint.Dir, hint.Tiles); err != nil { // player 0 moves
|
||||
t.Fatalf("player 0 play: %v", err)
|
||||
}
|
||||
if g.ToMove() != 1 {
|
||||
t.Fatalf("after player 0's move, toMove = %d, want 1", g.ToMove())
|
||||
}
|
||||
|
||||
// Player 0 resigns although it is player 1's turn.
|
||||
rec, err := g.ResignSeat(0)
|
||||
if err != nil {
|
||||
t.Fatalf("player 0 off-turn resign: %v", err)
|
||||
}
|
||||
if rec.Player != 0 || rec.Action != ActionResign {
|
||||
t.Errorf("resign record = seat %d action %v, want seat 0 resign", rec.Player, rec.Action)
|
||||
}
|
||||
if !g.Over() || g.Reason() != EndResign {
|
||||
t.Fatalf("game over=%v reason=%v, want over with resign", g.Over(), g.Reason())
|
||||
}
|
||||
if res := g.Result(); res.Winner != 1 {
|
||||
t.Errorf("winner = %d, want 1 (the non-resigner)", res.Winner)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResignOnFinishedGame rejects a second transition.
|
||||
func TestResignOnFinishedGame(t *testing.T) {
|
||||
g := newEnglishGame(t, 1)
|
||||
|
||||
@@ -171,11 +171,46 @@ func (svc *Service) Exchange(ctx context.Context, gameID, accountID uuid.UUID, t
|
||||
}
|
||||
|
||||
// Resign ends the game on the player's turn; the remaining player wins.
|
||||
// Resign forfeits the game for the acting account. Unlike a play/exchange/pass it is
|
||||
// allowed on the opponent's turn (a resignation is not a turn-scoped move), so it does
|
||||
// not go through transition's turn check: it resigns the actor's own seat, whoever is to
|
||||
// move. The resigning seat always loses (docs/ARCHITECTURE.md §7).
|
||||
func (svc *Service) Resign(ctx context.Context, gameID, accountID uuid.UUID) (MoveResult, error) {
|
||||
return svc.transition(ctx, gameID, accountID, func(g *engine.Game) (engine.MoveRecord, []string, error) {
|
||||
rec, err := g.Resign()
|
||||
return rec, nil, err
|
||||
})
|
||||
pre, err := svc.store.GetGame(ctx, gameID)
|
||||
if err != nil {
|
||||
return MoveResult{}, err
|
||||
}
|
||||
seat, ok := pre.seatOf(accountID)
|
||||
if !ok {
|
||||
return MoveResult{}, ErrNotAPlayer
|
||||
}
|
||||
if pre.Status != StatusActive {
|
||||
return MoveResult{}, ErrFinished
|
||||
}
|
||||
|
||||
unlock := svc.locks.lock(gameID)
|
||||
defer unlock()
|
||||
|
||||
g, err := svc.liveGame(ctx, pre)
|
||||
if err != nil {
|
||||
return MoveResult{}, err
|
||||
}
|
||||
if g.Over() {
|
||||
return MoveResult{}, ErrFinished
|
||||
}
|
||||
|
||||
rackBefore := g.Hand(seat)
|
||||
rec, err := g.ResignSeat(seat)
|
||||
if err != nil {
|
||||
return MoveResult{}, err
|
||||
}
|
||||
post, err := svc.commit(ctx, gameID, g, rec, rec.Action.String(), rackBefore, nil, pre.Seats)
|
||||
if err != nil {
|
||||
return MoveResult{}, err
|
||||
}
|
||||
// A resignation carries no think time (it can happen on the opponent's turn), so it
|
||||
// is intentionally excluded from the move-duration metric.
|
||||
return MoveResult{Move: rec, Game: post}, nil
|
||||
}
|
||||
|
||||
// GameVariant returns just a game's variant. The edge layer uses it to map wire alphabet
|
||||
|
||||
@@ -299,6 +299,42 @@ func TestResignWinnerAndStats(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestResignOnOpponentTurn checks the Stage 17 fix: a player can forfeit on the
|
||||
// opponent's turn. Seat 0 plays (so it is seat 1's turn), then seat 0 resigns its own
|
||||
// seat while it is not its turn — no ErrNotYourTurn, the game ends, and seat 0 loses
|
||||
// despite leading on score.
|
||||
func TestResignOnOpponentTurn(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newGameService()
|
||||
seats := []uuid.UUID{provisionAccount(t), provisionAccount(t)}
|
||||
seed := openingSeed(t)
|
||||
g, err := svc.Create(ctx, game.CreateParams{
|
||||
Variant: engine.VariantEnglish, Seats: seats, TurnTimeout: 24 * time.Hour, Seed: seed,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("create: %v", err)
|
||||
}
|
||||
|
||||
hint, ok := newMirror(t, seed, 2).HintView()
|
||||
if !ok {
|
||||
t.Fatal("no opening move")
|
||||
}
|
||||
if _, err := svc.SubmitPlay(ctx, g.ID, seats[0], hint.Dir, hint.Tiles); err != nil { // p0 scores, now p1's turn
|
||||
t.Fatalf("p0 play: %v", err)
|
||||
}
|
||||
|
||||
res, err := svc.Resign(ctx, g.ID, seats[0]) // p0 resigns OFF turn
|
||||
if err != nil {
|
||||
t.Fatalf("off-turn resign = %v, want nil", err)
|
||||
}
|
||||
if res.Game.Status != game.StatusFinished || res.Game.EndReason != "resign" {
|
||||
t.Fatalf("after off-turn resign: %+v", res.Game)
|
||||
}
|
||||
if res.Game.Seats[0].IsWinner || !res.Game.Seats[1].IsWinner {
|
||||
t.Errorf("winner flags wrong (resigner must lose): %+v", res.Game.Seats)
|
||||
}
|
||||
}
|
||||
|
||||
// TestTimeoutSweep auto-resigns an overdue game and records it as a timeout.
|
||||
func TestTimeoutSweep(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
@@ -40,6 +40,38 @@ func newGameWithSeats(t *testing.T, n int) (uuid.UUID, []uuid.UUID) {
|
||||
return g.ID, seats
|
||||
}
|
||||
|
||||
// TestFriendRequestToRobotStaysPending checks a friend request to a robot is accepted as
|
||||
// pending rather than blocked: robots no longer block friend requests, so the request
|
||||
// just sits unanswered and later expires — mirroring a human who ignores it (Stage 17).
|
||||
func TestFriendRequestToRobotStaysPending(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newSocialService()
|
||||
accs := account.NewStore(testDB)
|
||||
|
||||
human := provisionAccount(t)
|
||||
robot, err := accs.ProvisionRobot(ctx, "robot-friend-"+uuid.NewString(), "Robbie")
|
||||
if err != nil {
|
||||
t.Fatalf("provision robot: %v", err)
|
||||
}
|
||||
if robot.BlockFriendRequests {
|
||||
t.Fatal("robot must not block friend requests")
|
||||
}
|
||||
// A request is only allowed between players who share a game.
|
||||
if _, err := newGameService().Create(ctx, game.CreateParams{
|
||||
Variant: engine.VariantEnglish, Seats: []uuid.UUID{human, robot.ID},
|
||||
TurnTimeout: 24 * time.Hour, Seed: openingSeed(t),
|
||||
}); err != nil {
|
||||
t.Fatalf("create game: %v", err)
|
||||
}
|
||||
|
||||
if err := svc.SendFriendRequest(ctx, human, robot.ID); err != nil {
|
||||
t.Fatalf("request to robot = %v, want nil (accepted as pending)", err)
|
||||
}
|
||||
if got, _ := svc.ListIncomingRequests(ctx, robot.ID); len(got) != 1 || got[0] != human {
|
||||
t.Fatalf("robot incoming = %v, want [human]", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFriendRequestLifecycle(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
svc := newSocialService()
|
||||
|
||||
@@ -142,11 +142,14 @@ func (m *Matchmaker) Poll(_ context.Context, accountID uuid.UUID) (EnqueueResult
|
||||
return EnqueueResult{}, nil
|
||||
}
|
||||
|
||||
// Cancel removes accountID from whatever pool it waits in, reporting whether it
|
||||
// was queued.
|
||||
// Cancel removes accountID from whatever pool it waits in and drops any pending
|
||||
// matched result, reporting whether it was queued. Clearing the result closes the
|
||||
// race where the reaper substituted a robot just before the player cancelled: the
|
||||
// stale game must not later surface through Poll as a game the player did not want.
|
||||
func (m *Matchmaker) Cancel(_ context.Context, accountID uuid.UUID) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
delete(m.results, accountID)
|
||||
variant, ok := m.queued[accountID]
|
||||
if !ok {
|
||||
return false
|
||||
|
||||
@@ -240,6 +240,27 @@ func TestMatchmakerReaperSkipsCancelled(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestMatchmakerCancelClearsPendingResult covers the race where the reaper substitutes a
|
||||
// robot just before the player cancels: Cancel must drop the pending result so the
|
||||
// abandoned game never surfaces through Poll (Stage 17).
|
||||
func TestMatchmakerCancelClearsPendingResult(t *testing.T) {
|
||||
creator := &fakeCreator{}
|
||||
mm := newTestMatchmaker(creator, uuid.New())
|
||||
base := time.Now()
|
||||
mm.clock = func() time.Time { return base }
|
||||
ctx := context.Background()
|
||||
a := uuid.New()
|
||||
|
||||
if _, err := mm.Enqueue(ctx, a, engine.VariantEnglish); err != nil {
|
||||
t.Fatalf("enqueue: %v", err)
|
||||
}
|
||||
mm.Reap(ctx, base.Add(testWaitDelay+time.Second)) // substitution stores a pending result
|
||||
mm.Cancel(ctx, a) // ... then the player cancels
|
||||
if got, _ := mm.Poll(ctx, a); got.Matched {
|
||||
t.Error("cancel must drop the pending substituted game; Poll still matched")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchmakerReaperDefersWithoutRobot(t *testing.T) {
|
||||
creator := &fakeCreator{}
|
||||
mm := NewMatchmaker(creator, &fakeRobots{err: errors.New("empty pool")}, testWaitDelay, zap.NewNop())
|
||||
|
||||
@@ -47,6 +47,7 @@ func TestStatusForError(t *testing.T) {
|
||||
"not a player": {game.ErrNotAPlayer, http.StatusForbidden, "not_a_player"},
|
||||
"not your turn": {game.ErrNotYourTurn, http.StatusConflict, "not_your_turn"},
|
||||
"nudge own turn": {social.ErrNudgeOnOwnTurn, http.StatusConflict, "nudge_own_turn"},
|
||||
"nudge too soon": {social.ErrNudgeTooSoon, http.StatusConflict, "nudge_too_soon"},
|
||||
"illegal play": {engine.ErrIllegalPlay, http.StatusUnprocessableEntity, "illegal_play"},
|
||||
"email taken": {account.ErrEmailTaken, http.StatusConflict, "email_taken"},
|
||||
"code mismatch": {account.ErrCodeMismatch, http.StatusUnauthorized, "code_invalid"},
|
||||
|
||||
@@ -69,6 +69,7 @@ func (s *Server) registerRoutes() {
|
||||
}
|
||||
if s.matchmaker != nil {
|
||||
u.POST("/lobby/enqueue", s.handleEnqueue)
|
||||
u.POST("/lobby/cancel", s.handleCancel)
|
||||
u.GET("/lobby/poll", s.handlePoll)
|
||||
}
|
||||
if s.invitations != nil {
|
||||
@@ -200,9 +201,12 @@ func statusForError(err error) (int, string) {
|
||||
case errors.Is(err, session.ErrNotFound):
|
||||
return http.StatusUnauthorized, "session_invalid"
|
||||
case errors.Is(err, social.ErrChatBlocked), errors.Is(err, social.ErrMessageTooLong),
|
||||
errors.Is(err, social.ErrEmptyMessage), errors.Is(err, social.ErrForbiddenContent),
|
||||
errors.Is(err, social.ErrNudgeTooSoon):
|
||||
errors.Is(err, social.ErrEmptyMessage), errors.Is(err, social.ErrForbiddenContent):
|
||||
return http.StatusUnprocessableEntity, "chat_rejected"
|
||||
case errors.Is(err, social.ErrNudgeTooSoon):
|
||||
// A too-frequent nudge is a distinct, non-content rejection — the UI must say
|
||||
// "don't rush the player so often", not the chat content-rejection message.
|
||||
return http.StatusConflict, "nudge_too_soon"
|
||||
case errors.Is(err, social.ErrSelfRelation):
|
||||
return http.StatusBadRequest, "self_relation"
|
||||
case errors.Is(err, social.ErrRequestExists):
|
||||
|
||||
@@ -153,6 +153,20 @@ func (s *Server) handleEnqueue(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, dto)
|
||||
}
|
||||
|
||||
// handleCancel removes the caller from the auto-match pool (and drops any pending
|
||||
// matched result), so a cancelled quick-match neither blocks a re-queue nor later
|
||||
// surfaces a robot-substituted game the player abandoned. It is idempotent: cancelling
|
||||
// when not queued is a no-op success.
|
||||
func (s *Server) handleCancel(c *gin.Context) {
|
||||
uid, ok := userID(c)
|
||||
if !ok {
|
||||
abortBadRequest(c, "missing identity")
|
||||
return
|
||||
}
|
||||
s.matchmaker.Cancel(c.Request.Context(), uid)
|
||||
c.Status(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// handlePoll reports whether the caller has been paired since queueing.
|
||||
func (s *Server) handlePoll(c *gin.Context) {
|
||||
uid, ok := userID(c)
|
||||
|
||||
Reference in New Issue
Block a user