diff --git a/multiplayer-todo.md b/multiplayer-todo.md index 509b7542..672394df 100644 --- a/multiplayer-todo.md +++ b/multiplayer-todo.md @@ -1194,7 +1194,7 @@ the local/CI/community transport, not a silent production fallback. | 8.14 `[D:8.4,8.5,8.8]` | **IN PROGRESS.** Pure Go queue domain enforces one active ticket per verified player, 10 s heartbeat/30 s expiry, retry-safe create/heartbeat/cancel and deterministic candidate projection | `server/domain/queue.go` has adversarial ownership/expiry/idempotency tests; PostgreSQL transaction adapter, Redis candidate index and cache-loss repair remain | | 8.15 `[D:7.8,8.3]` | **IN PROGRESS.** Pure Go probe validation treats Steam location as opaque, requires nonce/freshness/region and server-computed RTT, and implements discrepancy quarantine/release | `server/domain/probes.go` and adversarial fixtures cover stale/wrong/forged evidence, the 25 ms/30% threshold, three-sample quarantine and five-clean release; Steam coordinator and regional probe adapters remain | | 8.16 `[D:8.14,8.15]` | **IN PROGRESS.** Pure Go candidate/team selection implements the <=100 ms ceiling, pairwise widening tolerance, anchor inclusion, deterministic set/region scoring and balanced team partitioning | `server/domain/matcher.go`, `teams.go` and adversarial fixtures cover no-common-region, tolerance boundaries, lexical ties, mean-rating balance and input-order independence; queue-backed candidate loading and full population fixtures remain | -| 8.17 `[D:8.14,8.16]` | Ten-second proposal to **every selected human**: ranked 6; casual largest compatible 6→2 after 60 s with disclosed teams/bots; apply exact decline/timeout/no-show cooldown and queue-precedence rules | Allocation starts only after selected humans accept; 2–5-human casual is reachable; accepter timestamps restore exactly; ranked pre-match no-show has cooldown but no rating loss | +| 8.17 `[D:8.14,8.16]` | **IN PROGRESS.** Pure Go proposal policy sends a 10-second response window to every selected human, requires unanimous acceptance, applies exact decline/timeout cooldowns and ranked escalation | `server/domain/proposal.go` and adversarial fixtures cover partial/unanimous response, expiry, replay/conflict and ranked six-player/cooldown rules; casual 6→2 composition, queue precedence and allocation integration remain | | 8.18 `[D:8.5,8.14,8.17]` | Horizontally replicated matcher: Redis candidates, then PostgreSQL serializable proposal/participant fence, then cache cleanup/repair | Forced loss of the last acknowledged Redis write, retries, worker death and failover cannot claim a player into two proposals/matches | | 8.19 `[D:8.18]` | Casual policy: proposal composition above; >=1 human/team, exhaustive rating-balanced teams, bots after 60 s, opt-in kickoff-only backfill, 30 s reconnect and defined backfill/casual penalties | Every 2–6-human shape is tested; no mid-play replacement; declined/backfill participant gets no excluded rating/cooldown; original leaver gets only documented outcome/cooldown | | 8.20 `[D:8.18]` | Ranked policy: exactly six verified solo humans, no bots/backfill, only `ArenaRegistry.random`; define initial no-show, proposal timeout and reconnect/abandon transitions | Ranked rejects parties/bots/backfill/elevated arenas; every pre-live failure returns five innocent players with original precedence and applies no rating | diff --git a/server/domain/proposal.go b/server/domain/proposal.go new file mode 100644 index 00000000..0a992567 --- /dev/null +++ b/server/domain/proposal.go @@ -0,0 +1,130 @@ +package domain + +import ( + "crypto/sha256" + "errors" + "fmt" + "sort" + "time" +) + +const ProposalWindow = 10 * time.Second + +var ( + ErrProposalClosed = errors.New("proposal is no longer open") + ErrNotParticipant = errors.New("player is not a proposal participant") +) + +type Playlist string + +const ( + Casual Playlist = "casual" + Ranked Playlist = "ranked" +) + +type Response string + +const ( + Pending Response = "PENDING" + AcceptedResponse Response = "ACCEPTED" + DeclinedResponse Response = "DECLINED" + TimedOutResponse Response = "TIMED_OUT" +) + +type ProposalParticipant struct { + PlayerID string + Response Response +} + +type Proposal struct { + ProposalID string + Playlist Playlist + Participants []ProposalParticipant + State State + Revision uint64 + ExpiresAt time.Time + idempotent map[string]proposalMutation +} + +type proposalMutation struct { + digest [32]byte + proposal Proposal +} + +func NewProposal(id string, playlist Playlist, playerIDs []string, now time.Time) (Proposal, error) { + if id == "" || (playlist != Casual && playlist != Ranked) { return Proposal{}, fmt.Errorf("%w: invalid proposal", ErrConflict) } + if playlist == Ranked && len(playerIDs) != 6 { return Proposal{}, fmt.Errorf("%w: ranked requires exactly six players", ErrConflict) } + if len(playerIDs) < 2 || len(playerIDs) > 6 { return Proposal{}, fmt.Errorf("%w: proposal requires 2 through 6 players", ErrConflict) } + seen := make(map[string]bool, len(playerIDs)) + participants := make([]ProposalParticipant, 0, len(playerIDs)) + for _, playerID := range playerIDs { + if playerID == "" || seen[playerID] { return Proposal{}, fmt.Errorf("%w: duplicate or empty player", ErrConflict) } + seen[playerID] = true + participants = append(participants, ProposalParticipant{PlayerID: playerID, Response: Pending}) + } + sort.Slice(participants, func(i, j int) bool { return participants[i].PlayerID < participants[j].PlayerID }) + return Proposal{ProposalID: id, Playlist: playlist, Participants: participants, State: Open, ExpiresAt: now.Add(ProposalWindow), idempotent: make(map[string]proposalMutation)}, nil +} + +func (p *Proposal) Respond(playerID, idempotencyKey string, accept bool, expectedRevision uint64, now time.Time) (Proposal, error) { + digest := sha256.Sum256([]byte(fmt.Sprintf("%s:%t:%d", playerID, accept, expectedRevision))) + if prior, ok := p.idempotent[idempotencyKey]; ok { + if prior.digest != digest { return Proposal{}, fmt.Errorf("%w: proposal response payload changed", ErrConflict) } + return prior.proposal, nil + } + if idempotencyKey == "" { return Proposal{}, fmt.Errorf("%w: empty proposal response key", ErrConflict) } + if p.State != Open || !now.Before(p.ExpiresAt) { return Proposal{}, ErrProposalClosed } + if p.Revision != expectedRevision { return Proposal{}, ErrStaleRevision } + index := p.participantIndex(playerID) + if index < 0 { return Proposal{}, ErrNotParticipant } + if p.Participants[index].Response != Pending { return Proposal{}, fmt.Errorf("%w: participant already responded", ErrConflict) } + if accept { p.Participants[index].Response = AcceptedResponse } else { p.Participants[index].Response = DeclinedResponse; p.State = Declined } + if accept && p.allAccepted() { p.State = Accepted } + p.Revision++ + p.idempotent[idempotencyKey] = proposalMutation{digest: digest, proposal: p.copy()} + return p.copy(), nil +} + +func (p *Proposal) Expire(now time.Time) bool { + if p.State != Open || now.Before(p.ExpiresAt) { return false } + for i := range p.Participants { if p.Participants[i].Response == Pending { p.Participants[i].Response = TimedOutResponse } } + p.State = Expired + p.Revision++ + return true +} + +func (p *Proposal) participantIndex(playerID string) int { + for i, participant := range p.Participants { if participant.PlayerID == playerID { return i } } + return -1 +} + +func (p *Proposal) allAccepted() bool { + for _, participant := range p.Participants { if participant.Response != AcceptedResponse { return false } } + return true +} + +func (p *Proposal) copy() Proposal { + clone := *p + clone.Participants = append([]ProposalParticipant(nil), p.Participants...) + clone.idempotent = nil + return clone +} + +type CooldownEvent struct { At time.Time; Playlist Playlist; Kind Response } + +func CooldownUntil(events []CooldownEvent, playlist Playlist, now time.Time) time.Time { + window := 30 * time.Minute + cutoff := now.Add(-window) + filtered := make([]CooldownEvent, 0, len(events)) + for _, event := range events { if event.Playlist == playlist && !event.At.Before(cutoff) { filtered = append(filtered, event) } } + sort.Slice(filtered, func(i, j int) bool { return filtered[i].At.Before(filtered[j].At) }) + var duration time.Duration + if len(filtered) > 0 { + if playlist == Casual { if filtered[len(filtered)-1].Kind == DeclinedResponse { duration = 30 * time.Second } else { duration = 60 * time.Second } } else { + if filtered[len(filtered)-1].Kind == DeclinedResponse { duration = 2 * time.Minute } else { duration = 5 * time.Minute } + if len(filtered) >= 3 { duration = 15 * time.Minute } + } + } + if duration == 0 { return time.Time{} } + return filtered[len(filtered)-1].At.Add(duration) +} diff --git a/server/domain/proposal_test.go b/server/domain/proposal_test.go new file mode 100644 index 00000000..c4394b91 --- /dev/null +++ b/server/domain/proposal_test.go @@ -0,0 +1,45 @@ +package domain + +import ( + "errors" + "testing" + "time" +) + +func TestProposalRequiresUnanimousAcceptance(t *testing.T) { + now := time.Unix(1000, 0) + p, err := NewProposal("proposal-123456789", Casual, []string{"b", "a"}, now) + if err != nil { t.Fatal(err) } + if _, err = p.Respond("a", "response-a-123456", true, 0, now); err != nil { t.Fatal(err) } + if p.State != Open || p.Revision != 1 { t.Fatalf("partial acceptance closed proposal: %+v", p) } + if _, err = p.Respond("b", "response-b-123456", true, 1, now); err != nil { t.Fatal(err) } + if p.State != Accepted || p.Revision != 2 { t.Fatalf("unanimous acceptance not committed: %+v", p) } +} + +func TestProposalResponseReplayIsStableAndPayloadReuseConflicts(t *testing.T) { + now := time.Unix(1000, 0) + p, err := NewProposal("proposal-123456789", Casual, []string{"a", "b"}, now) + if err != nil { t.Fatal(err) } + first, err := p.Respond("a", "response-a-123456", true, 0, now) + if err != nil { t.Fatal(err) } + replay, err := p.Respond("a", "response-a-123456", true, 0, now.Add(20*time.Second)) + if err != nil || replay.Revision != first.Revision { t.Fatalf("replay = %+v, %v", replay, err) } + if _, err = p.Respond("a", "response-a-123456", false, 1, now); !errors.Is(err, ErrConflict) { t.Fatalf("payload reuse error = %v", err) } +} + +func TestProposalExpiryTimesOutPendingParticipantsAndClosesRace(t *testing.T) { + now := time.Unix(1000, 0) + p, err := NewProposal("proposal-123456789", Ranked, []string{"a", "b", "c", "d", "e", "f"}, now) + if err != nil { t.Fatal(err) } + if !p.Expire(now.Add(ProposalWindow)) || p.State != Expired || p.Revision != 1 { t.Fatalf("expiry failed: %+v", p) } + for _, participant := range p.Participants { if participant.Response != TimedOutResponse { t.Fatalf("pending participant not timed out: %+v", participant) } } + if _, err = p.Respond("a", "late-response-123", true, 1, now.Add(ProposalWindow)); !errors.Is(err, ErrProposalClosed) { t.Fatalf("late response error = %v", err) } +} + +func TestRankedProposalAndCooldownEscalation(t *testing.T) { + now := time.Unix(1000, 0) + if _, err := NewProposal("proposal-123456789", Ranked, []string{"a", "b"}, now); err == nil { t.Fatal("ranked proposal accepted fewer than six") } + if got := CooldownUntil([]CooldownEvent{{At: now, Playlist: Ranked, Kind: DeclinedResponse}}, Ranked, now); !got.Equal(now.Add(2*time.Minute)) { t.Fatalf("ranked decline cooldown = %v", got) } + events := []CooldownEvent{{At: now, Playlist: Ranked, Kind: TimedOutResponse}, {At: now.Add(time.Minute), Playlist: Ranked, Kind: DeclinedResponse}, {At: now.Add(2*time.Minute), Playlist: Ranked, Kind: TimedOutResponse}} + if got := CooldownUntil(events, Ranked, now.Add(2*time.Minute)); !got.Equal(now.Add(17*time.Minute)) { t.Fatalf("ranked escalation cooldown = %v", got) } +}