Files
CosmicClash/server/domain/proposal.go
T
2026-08-31 20:23:17 +01:00

131 lines
5.0 KiB
Go

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)
}