feat: add matchmaking proposal policy

This commit is contained in:
Josh Creek
2026-08-31 20:23:17 +01:00
parent cf212d94f9
commit 7643dbc439
3 changed files with 176 additions and 1 deletions
+130
View File
@@ -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)
}
+45
View File
@@ -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) }
}