feat(multiplayer): add server process/assignment-ready registration API

Add POST /v1/servers/{id}/register (and its /api/v1 contract alias),
authenticated by the same workload binding as the result route. A
game server reports its protocol version and image digest and asks
to advance ALLOCATING -> PROCESS_READY -> ASSIGNMENT_READY; the store
boundary (AdvanceServerRegistration) does this as one idempotent
SERIALIZABLE transaction that also advances every participant's queue
ticket, and gates the final transition on every participant having a
live, unexpired assignment.

Adversarial review of the surrounding routing turned up a pre-existing
bug: contractServerMutation rejected any path containing '/', so the
already-documented /api/v1/servers/{id}/result route (and this new
/register route) 404'd for every real caller despite being declared
in the OpenAPI contract. Fix it to delegate shape validation to
serverMutation, matching how contractQueueMutation handles its own
two-segment paths, and add a regression test covering both contract
routes end to end.
This commit is contained in:
Josh Creek
2026-09-01 12:35:30 +01:00
parent 4fb7ddfecf
commit d937cb153c
6 changed files with 217 additions and 4 deletions
+51 -4
View File
@@ -33,6 +33,9 @@ type WorkloadVerifier func(string, time.Time) (domain.WorkloadBinding, error)
type ResultSubmitter interface {
SubmitResult(context.Context, string, domain.MatchResult, domain.WorkloadBinding, []byte, time.Time) error
}
type ServerRegistrar interface {
RegisterServer(context.Context, domain.WorkloadBinding, int, bool, string, time.Time) error
}
type QueueBackend interface {
Create(context.Context, string, string, string, domain.QueueSpec, time.Time) (domain.QueueTicket, error)
@@ -104,6 +107,7 @@ type Service struct {
ProbeRecorder ProbeRecorder
WorkloadVerify WorkloadVerifier
ResultSubmitter ResultSubmitter
ServerRegistrar ServerRegistrar
Assignment AssignmentProvider
Now func() time.Time
Proposals map[string]*domain.Proposal
@@ -369,8 +373,12 @@ func (s *Service) contractAssignment(w http.ResponseWriter, r *http.Request) {
}
func (s *Service) contractServerMutation(w http.ResponseWriter, r *http.Request) {
// Unlike contractAssignment, the documented shape here is two segments
// (/servers/{serverId}/result, /servers/{serverId}/register) — rejecting
// any "/" would 404 every real call. Delegate shape validation to
// serverMutation, which already enforces exactly {id}/{result|register}.
path := strings.TrimPrefix(r.URL.Path, "/api/v1/servers/")
if path == "" || strings.Contains(path, "/") {
if path == "" {
writeError(w, http.StatusNotFound, "not_found")
return
}
@@ -389,18 +397,25 @@ type resultRequest struct {
IntegrityState domain.IntegrityState `json:"integrity_state"`
}
type serverRegistrationRequest struct {
MatchID string `json:"match_id"`
ProtocolVersion int `json:"protocol_version"`
ImageDigest string `json:"image_digest"`
AssignmentReady bool `json:"assignment_ready"`
}
func (s *Service) serverMutation(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed")
return
}
parts := strings.Split(strings.TrimPrefix(r.URL.Path, "/v1/servers/"), "/")
if len(parts) != 2 || parts[0] == "" || parts[1] != "result" {
if len(parts) != 2 || parts[0] == "" || (parts[1] != "result" && parts[1] != "register") {
writeError(w, http.StatusNotFound, "not_found")
return
}
if s.WorkloadVerify == nil || s.ResultSubmitter == nil {
writeError(w, http.StatusServiceUnavailable, "result_unavailable")
if s.WorkloadVerify == nil || (parts[1] == "result" && s.ResultSubmitter == nil) || (parts[1] == "register" && s.ServerRegistrar == nil) {
writeError(w, http.StatusServiceUnavailable, "server_unavailable")
return
}
key := r.Header.Get("Idempotency-Key")
@@ -419,6 +434,26 @@ func (s *Service) serverMutation(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusUnauthorized, "unauthorized")
return
}
if parts[1] == "register" {
var input serverRegistrationRequest
if !decodeBody(w, r, &input) {
return
}
if input.MatchID == "" || input.MatchID != binding.MatchID || input.ProtocolVersion < 1 || !validImageDigest(input.ImageDigest) {
writeError(w, http.StatusUnprocessableEntity, "invalid_request")
return
}
if err := s.ServerRegistrar.RegisterServer(r.Context(), binding, input.ProtocolVersion, input.AssignmentReady, key, now); err != nil {
if errors.Is(err, domain.ErrConflict) {
writeError(w, http.StatusConflict, "conflict")
} else {
writeError(w, http.StatusUnprocessableEntity, "invalid_request")
}
return
}
w.WriteHeader(http.StatusNoContent)
return
}
var input resultRequest
if !decodeBody(w, r, &input) {
return
@@ -444,6 +479,18 @@ func (s *Service) serverMutation(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusAccepted)
}
func validImageDigest(value string) bool {
if len(value) != len("sha256:")+64 || !strings.HasPrefix(value, "sha256:") {
return false
}
for _, ch := range value[len("sha256:"):] {
if !(ch >= '0' && ch <= '9') && !(ch >= 'a' && ch <= 'f') {
return false
}
}
return true
}
func (s *Service) queueMutation(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost && r.Method != http.MethodGet && r.Method != http.MethodDelete {
writeError(w, http.StatusMethodNotAllowed, "method_not_allowed")
+81
View File
@@ -41,6 +41,20 @@ type resultSubmitterSpy struct {
result domain.MatchResult
}
type serverRegistrarSpy struct {
calls int
binding domain.WorkloadBinding
protocol int
assignmentReady bool
err error
}
func (s *serverRegistrarSpy) RegisterServer(_ context.Context, binding domain.WorkloadBinding, protocol int, assignmentReady bool, _ string, _ time.Time) error {
s.calls++
s.binding, s.protocol, s.assignmentReady = binding, protocol, assignmentReady
return s.err
}
type proposalPromoterSpy struct {
calls int
proposal domain.Proposal
@@ -1018,6 +1032,73 @@ func TestServerResultAPIRequiresBoundWorkloadAndDelegatesDurableSubmission(t *te
response.Body.Close()
}
func TestContractServerRoutesAdaptTwoSegmentPaths(t *testing.T) {
now := time.Unix(1000, 0).UTC()
binding := domain.WorkloadBinding{AllocationID: "allocation-1", MatchID: "match-1", ServerID: "server-1"}
submitter := &resultSubmitterSpy{}
registrar := &serverRegistrarSpy{}
service := &Service{Now: func() time.Time { return now }, WorkloadVerify: func(token string, _ time.Time) (domain.WorkloadBinding, error) {
if token != "workload-token" {
return domain.WorkloadBinding{}, errors.New("bad token")
}
return binding, nil
}, ResultSubmitter: submitter, ServerRegistrar: registrar}
server := httptest.NewServer(service.Handler())
defer server.Close()
registerBody := `{"match_id":"match-1","protocol_version":1,"image_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","assignment_ready":false}`
req, _ := http.NewRequest(http.MethodPost, server.URL+"/api/v1/servers/server-1/register", strings.NewReader(registerBody))
req.Header.Set("Authorization", "Bearer workload-token")
req.Header.Set("Idempotency-Key", "contract-register-key-1")
response, err := http.DefaultClient.Do(req)
if err != nil || response.StatusCode != http.StatusNoContent || registrar.calls != 1 {
t.Fatalf("register status=%v err=%v calls=%d", response.StatusCode, err, registrar.calls)
}
response.Body.Close()
resultBody := `{"match_id":"match-1","result_nonce":"nonce-1234567890","score":{"team_0":3,"team_1":2},"integrity_state":"CERTIFIED"}`
req, _ = http.NewRequest(http.MethodPost, server.URL+"/api/v1/servers/server-1/result", strings.NewReader(resultBody))
req.Header.Set("Authorization", "Bearer workload-token")
req.Header.Set("Idempotency-Key", "contract-result-key-123")
response, err = http.DefaultClient.Do(req)
if err != nil || response.StatusCode != http.StatusAccepted || submitter.calls != 1 {
t.Fatalf("result status=%v err=%v calls=%d", response.StatusCode, err, submitter.calls)
}
response.Body.Close()
}
func TestServerRegistrationAPIRequiresBoundWorkloadAndValidDigest(t *testing.T) {
now := time.Unix(1000, 0).UTC()
binding := domain.WorkloadBinding{AllocationID: "allocation-1", MatchID: "match-1", ServerID: "server-1"}
registrar := &serverRegistrarSpy{}
service := &Service{Now: func() time.Time { return now }, WorkloadVerify: func(token string, _ time.Time) (domain.WorkloadBinding, error) {
if token != "workload-token" {
return domain.WorkloadBinding{}, errors.New("bad token")
}
return binding, nil
}, ServerRegistrar: registrar}
server := httptest.NewServer(service.Handler())
defer server.Close()
body := `{"match_id":"match-1","protocol_version":1,"image_digest":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","assignment_ready":false}`
req, _ := http.NewRequest(http.MethodPost, server.URL+"/v1/servers/server-1/register", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer workload-token")
req.Header.Set("Idempotency-Key", "register-key-123456")
response, err := http.DefaultClient.Do(req)
if err != nil || response.StatusCode != http.StatusNoContent || registrar.calls != 1 || registrar.binding != binding || registrar.protocol != 1 || registrar.assignmentReady {
t.Fatalf("status=%v err=%v registrar=%+v", response.StatusCode, err, registrar)
}
response.Body.Close()
body = `{"match_id":"match-1","protocol_version":1,"image_digest":"bad","assignment_ready":false}`
req, _ = http.NewRequest(http.MethodPost, server.URL+"/v1/servers/server-1/register", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer workload-token")
req.Header.Set("Idempotency-Key", "register-key-123456")
response, err = http.DefaultClient.Do(req)
if err != nil || response.StatusCode != http.StatusUnprocessableEntity || registrar.calls != 1 {
t.Fatalf("invalid registration status=%v err=%v calls=%d", response.StatusCode, err, registrar.calls)
}
response.Body.Close()
}
func TestProbeAPIUsesServerEvidenceAndRejectsClientRTTField(t *testing.T) {
now := time.Unix(1000, 0).UTC()
sessions := domain.NewSessionStore()
+13
View File
@@ -58,3 +58,16 @@ func ProposalPromoterFromStore(db *sql.DB) ProposalPromoter {
return store.PromoteStoredAcceptedProposal(ctx, db, proposal.ProposalID, now)
})
}
type postgresServerRegistrar struct{ db *sql.DB }
func (p postgresServerRegistrar) RegisterServer(ctx context.Context, binding domain.WorkloadBinding, protocol int, assignmentReady bool, idempotencyKey string, now time.Time) error {
return store.AdvanceServerRegistration(ctx, p.db, binding, protocol, assignmentReady, idempotencyKey, now)
}
func ServerRegistrarFromStore(db *sql.DB) ServerRegistrar {
if db == nil {
return nil
}
return postgresServerRegistrar{db: db}
}