feat: add durable matcher worker orchestration

This commit is contained in:
Josh Creek
2026-09-01 09:30:28 +01:00
parent 18538e833b
commit bdc89303b4
4 changed files with 169 additions and 2 deletions
+88
View File
@@ -0,0 +1,88 @@
// Package matcher contains the provider-neutral orchestration around the
// durable proposal claim transaction.
package matcher
import (
"context"
"fmt"
"time"
"github.com/cosmic-clash/cosmic-clash/server/domain"
)
type CandidateSource func(context.Context, time.Time, int) ([]domain.Candidate, error)
type ProposalCreator interface {
CreateProposal(context.Context, domain.Proposal, map[string]string, time.Time) error
}
type ProposalCreatorFunc func(context.Context, domain.Proposal, map[string]string, time.Time) error
func (f ProposalCreatorFunc) CreateProposal(ctx context.Context, proposal domain.Proposal, ticketIDs map[string]string, now time.Time) error {
return f(ctx, proposal, ticketIDs, now)
}
type PrepareFunc func(string, domain.Playlist, domain.MatchFormation, time.Time) (domain.PreparedProposal, error)
type Worker struct {
Source CandidateSource
Creator ProposalCreator
Playlist domain.Playlist
Size int
Now func() time.Time
NextID func() string
Prepare PrepareFunc
}
// RunOnce performs one bounded matchmaking attempt. The source may be Redis
// backed, but the creator must be the durable transaction that claims tickets;
// a stale cache therefore fails safely and can be retried on the next pass.
func (w Worker) RunOnce(ctx context.Context) (bool, error) {
if w.Source == nil || w.Creator == nil || w.Now == nil || w.NextID == nil || w.Prepare == nil {
return false, fmt.Errorf("matcher worker is not configured")
}
if w.Playlist != domain.Casual && w.Playlist != domain.Ranked {
return false, fmt.Errorf("unsupported matcher playlist")
}
if w.Size < 2 || w.Size > 6 {
return false, fmt.Errorf("invalid matcher size")
}
now := w.Now()
candidates, err := w.Source(ctx, now, w.Size)
if err != nil {
return false, err
}
if len(candidates) < w.Size {
return false, nil
}
queue := domain.NewQueue()
for _, candidate := range candidates {
if _, err := queue.Create(candidate.PlayerID, candidate.TicketID, "matcher-"+candidate.TicketID, candidate, now); err != nil {
return false, err
}
}
formation, err := domain.FormFromQueue(queue, w.Size, now)
if err != nil {
return false, err
}
prepared, err := w.Prepare(w.NextID(), w.Playlist, formation, now)
if err != nil {
return false, err
}
ticketIDs := make(map[string]string, len(prepared.Proposal.Participants))
for _, participant := range prepared.Proposal.Participants {
for _, candidate := range formation.Selection.Players {
if candidate.PlayerID == participant.PlayerID {
ticketIDs[participant.PlayerID] = candidate.TicketID
break
}
}
}
if len(ticketIDs) != len(prepared.Proposal.Participants) {
return false, fmt.Errorf("proposal participant is not in formed selection")
}
if err := w.Creator.CreateProposal(ctx, prepared.Proposal, ticketIDs, now); err != nil {
return false, err
}
return true, nil
}
+77
View File
@@ -0,0 +1,77 @@
package matcher
import (
"context"
"errors"
"testing"
"time"
"github.com/cosmic-clash/cosmic-clash/server/domain"
)
type creatorSpy struct {
calls int
err error
last domain.Proposal
ids map[string]string
}
func (c *creatorSpy) CreateProposal(_ context.Context, proposal domain.Proposal, ids map[string]string, _ time.Time) error {
c.calls++
c.last = proposal
c.ids = ids
return c.err
}
func candidates() []domain.Candidate {
now := time.Unix(1000, 0).UTC()
result := make([]domain.Candidate, 4)
for i := range result {
result[i] = domain.Candidate{TicketID: "ticket-" + string(rune('1'+i)), PlayerID: "player-" + string(rune('1'+i)), Playlist: domain.Casual, EnqueuedAt: now.Add(time.Duration(i) * time.Second), PredictedRTT: map[string]float64{"EU": 20}}
}
return result
}
func workerFor(source CandidateSource, creator ProposalCreator) Worker {
return Worker{Source: source, Creator: creator, Playlist: domain.Casual, Size: 4, Now: func() time.Time { return time.Unix(1000, 0).UTC() }, NextID: func() string { return "proposal-1234567890123456" }, Prepare: func(id string, playlist domain.Playlist, formation domain.MatchFormation, now time.Time) (domain.PreparedProposal, error) {
return domain.PrepareProposal(id, playlist, formation, nil, domain.RankedArena{}, now)
}}
}
func TestRunOnceDelegatesFinalClaimAndBindsTickets(t *testing.T) {
creator := &creatorSpy{}
worker := workerFor(func(context.Context, time.Time, int) ([]domain.Candidate, error) { return candidates(), nil }, creator)
formed, err := worker.RunOnce(context.Background())
if err != nil || !formed || creator.calls != 1 {
t.Fatalf("formed=%v err=%v calls=%d", formed, err, creator.calls)
}
if len(creator.ids) != 4 || creator.ids["player-1"] != "ticket-1" {
t.Fatalf("ticket bindings=%v", creator.ids)
}
}
func TestRunOnceFailsClosedOnSourceOrDurableClaimFailure(t *testing.T) {
creator := &creatorSpy{err: errors.New("serialization conflict")}
worker := workerFor(func(context.Context, time.Time, int) ([]domain.Candidate, error) {
return nil, errors.New("redis unavailable")
}, creator)
if _, err := worker.RunOnce(context.Background()); err == nil {
t.Fatal("source failure was swallowed")
}
worker.Source = func(context.Context, time.Time, int) ([]domain.Candidate, error) { return candidates(), nil }
if _, err := worker.RunOnce(context.Background()); err == nil {
t.Fatal("durable claim failure was swallowed")
}
if creator.calls != 1 {
t.Fatalf("creator calls=%d", creator.calls)
}
}
func TestRunOnceDoesNotClaimAnIncompleteBatch(t *testing.T) {
creator := &creatorSpy{}
worker := workerFor(func(context.Context, time.Time, int) ([]domain.Candidate, error) { return candidates()[:3], nil }, creator)
formed, err := worker.RunOnce(context.Background())
if err != nil || formed || creator.calls != 0 {
t.Fatalf("formed=%v err=%v calls=%d", formed, err, creator.calls)
}
}