feat: persist player-scoped assignments

This commit is contained in:
Josh Creek
2026-08-31 23:19:23 +01:00
parent 7f7516d9a0
commit 3ae2daec88
5 changed files with 172 additions and 1 deletions
+1 -1
View File
@@ -1228,7 +1228,7 @@ the local/CI/community transport, not a silent production fallback.
|---|---|---|
| 8.39 `[D:8.3,8.14,8.17]` | **IN PROGRESS.** `MatchmakingState` now projects queue → proposal → allocation/process-ready/assignment-ready/connect/live plus terminal failure states; autoload `ControlPlaneClient` provides authenticated queue create/recovery/heartbeat/cancel and proposal response requests with idempotency/revision headers; `matchmaking.tscn`/`matchmaking.gd` expose the state and authoritative actions from the main menu; authenticated proposal recovery now reconciles missed proposal events and expires them at read time; the Go API publishes targeted authenticated revisioned queue/proposal/assignment events and the Godot client consumes state/proposal/assignment events, fetching the authoritative assignment after assignment readiness | `test_matchmaking_state.gd`, `test_control_plane_client.gd`, `test_matchmaking_ui.gd`, `TestProposalRecoveryIsParticipantScopedAndExpiresAtReadBoundary`, `TestAuthenticatedWebSocketDeliversOnlyTargetedRevisionedEvents` and `TestStateChangingAPIActionsPublishTargetedEvents` reject stale/gapped/conflicting updates, validate endpoint/token/payload normalization, preserve idempotent duplicates, and guarantee visible phase/terminal copy; wiring durable allocation events into the outbox, wait/latency explanations and Godot runtime verification remain |
| 8.40 `[D:8.3,8.14]` | **IN PROGRESS.** Pure Go revisioned replica reducer rejects gaps for REST resync, makes duplicate/out-of-order events idempotent, and resumes from the authoritative snapshot revision; authenticated queue-ticket recovery now has an owner-checked REST read; Godot client projection persists non-secret ticket/proposal state, forces authoritative recovery after restart, and can replay a lost queue-create response with the original ticket/idempotency key; the Go API now exposes an authenticated `/v1/events` WebSocket with bounded per-player queues, strict upgrade/vocabulary validation and REST-resync-safe slow-client failure; Godot `ControlPlaneClient` can connect to the stream, consume validated events, automatically reconnect with bounded backoff, and trigger REST recovery on projection gaps and stream return | `server/domain/sync.go`, `server/api/events.go`, `server/api/service.go`, `service_test.go`, `matchmaking_state.gd` and `control_plane_client.gd` cover gap, snapshot, replay, same-revision conflict, owner-only ticket recovery, expired-ticket terminal handling, malformed restart snapshots, API-level duplicate-create replay/conflict, authenticated handshake/key rejection, targeted event delivery, exactly-once slow-subscriber closure and invalid-event rejection; durable outbox fan-out and live Godot verification remain |
| 8.41 `[D:7.8,8.9,8.31,8.40]` | **IN PROGRESS.** Authenticated `GET /v1/assignments/{matchId}` now exposes only a validated, player-scoped assignment view; Godot `AssignmentState`/`ControlPlaneClient.fetch_assignment()` bind the response to the authenticated player, recheck expiry, preserve explicit transport/slot/join authorisation and do not connect before assignment-ready | `server/api/service.go`, `service_test.go`, `assignment_state.gd` and `test_assignment_state.gd` cover participant/identity/expiry/shape/transport boundaries and assignment recovery; signed manifest-to-player persistence, SDR relay-ticket installation, `hello` join-authorisation wiring, fencing integration and live Godot verification remain |
| 8.41 `[D:7.8,8.9,8.31,8.40]` | **IN PROGRESS.** Authenticated `GET /v1/assignments/{matchId}` now exposes only a validated, player-scoped assignment view; Godot `AssignmentState`/`ControlPlaneClient.fetch_assignment()` bind the response to the authenticated player, recheck expiry, preserve explicit transport/slot/join authorisation and do not connect before assignment-ready; migration 0002 and the Go store adapter now persist/recover the complete player-scoped assignment projection with conflict-safe identical replay | `server/api/service.go`, `service_test.go`, `assignment_state.gd`, `test_assignment_state.gd`, `server/migrations/0002_assignments.sql` and `server/store/assignment_sql.go` cover participant/identity/expiry/shape/transport boundaries, player-scoped schema keys, expiry-filtered reads and assignment upsert conflict handling; signed manifest-to-player persistence wiring, SDR relay-ticket installation, `hello` join-authorisation wiring, fencing integration and live Godot/PostgreSQL verification remain |
| 8.42 `[D:8.22,8.23,8.24,8.40]` | **IN PROGRESS.** `RankedProfileState` and `ControlPlaneClient.fetch_ranked_profile()` expose the backend-authoritative rating/RD/volatility/games/tier/provisional/season view; matchmaking UI displays provisional/tier status without client-side rating math | `test_control_plane_client.gd` validates profile shape, numeric safety and provisional display; ranked profile fetch/display, committed revision after reconnect, abandon status and season countdown remain dependent on live auth/backend events and Godot runtime verification |
| 8.43 `[D:8.39,8.40,8.41]` | **IN PROGRESS.** Matchmaking client now distinguishes expired queue recovery, session expiry, missing records and retryable control-plane outages; a 401 clears the in-memory token, emits `session_expired` and disables retry until a new session is configured; terminal messages remain visible and active searches are not falsely failed on transient errors | `MatchmakingState` and `ControlPlaneClient` tests cover explicit expiry and the existing terminal/retry-safe state paths; decline, version mismatch, regional outage retry UI, failed reconnect, duplicate-action recovery and live Godot verification remain |
+28
View File
@@ -0,0 +1,28 @@
-- Restart-safe player-scoped assignment projections. The signed manifest and
-- join authorisation are persisted only after the allocator/manifest gate has
-- succeeded; clients still receive them only through an authenticated owner
-- read.
CREATE TABLE assignments (
match_id TEXT NOT NULL,
player_id TEXT NOT NULL,
allocation_id TEXT NOT NULL,
server_id TEXT NOT NULL,
slot INTEGER NOT NULL CHECK (slot BETWEEN 0 AND 5),
region TEXT NOT NULL CHECK (region IN ('EU', 'NA')),
client_build TEXT NOT NULL,
protocol_version INTEGER NOT NULL CHECK (protocol_version > 0),
transport TEXT NOT NULL CHECK (transport IN ('enet', 'steam_sdr')),
endpoint TEXT NOT NULL,
join_authorisation TEXT NOT NULL,
manifest_digest BYTEA NOT NULL,
expires_at TIMESTAMPTZ NOT NULL,
revision BIGINT NOT NULL DEFAULT 0 CHECK (revision >= 0),
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
PRIMARY KEY (match_id, player_id),
FOREIGN KEY (match_id, player_id) REFERENCES match_participants(match_id, player_id),
UNIQUE (match_id, slot)
);
CREATE INDEX assignments_player_expiry
ON assignments (player_id, expires_at);
+10
View File
@@ -5,6 +5,7 @@ import unittest
SQL = (Path(__file__).parent / "0001_initial.sql").read_text()
ASSIGNMENTS_SQL = (Path(__file__).parent / "0002_assignments.sql").read_text()
class MigrationTest(unittest.TestCase):
@@ -43,6 +44,15 @@ class MigrationTest(unittest.TestCase):
self.assertIn("REFERENCES identities(player_id)", SQL)
self.assertIn("REFERENCES matches(match_id)", SQL)
def test_assignments_are_player_scoped_and_expiry_bound(self):
for fragment in (
"CREATE TABLE assignments", "PRIMARY KEY (match_id, player_id)",
"FOREIGN KEY (match_id, player_id)", "UNIQUE (match_id, slot)",
"join_authorisation TEXT NOT NULL", "expires_at TIMESTAMPTZ NOT NULL",
"assignments_player_expiry",
):
self.assertIn(fragment, ASSIGNMENTS_SQL)
if __name__ == "__main__":
unittest.main()
+102
View File
@@ -0,0 +1,102 @@
package store
import (
"context"
"database/sql"
"fmt"
"time"
)
// DurableAssignment is the persistence form of a verified assignment-ready
// projection. It deliberately keeps player ownership in the primary key and
// query predicate so another participant cannot recover its join material.
type DurableAssignment struct {
MatchID string
PlayerID string
AllocationID string
ServerID string
Slot int
Region string
ClientBuild string
ProtocolVersion int
Transport string
Endpoint string
JoinAuthorisation string
ManifestDigest []byte
ExpiresAt time.Time
Revision uint64
}
const AssignmentUpsertSQL = `INSERT INTO assignments
(match_id, player_id, allocation_id, server_id, slot, region, client_build,
protocol_version, transport, endpoint, join_authorisation, manifest_digest,
expires_at, revision)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (match_id, player_id) DO UPDATE SET
allocation_id = EXCLUDED.allocation_id, server_id = EXCLUDED.server_id,
slot = EXCLUDED.slot, region = EXCLUDED.region, client_build = EXCLUDED.client_build,
protocol_version = EXCLUDED.protocol_version, transport = EXCLUDED.transport,
endpoint = EXCLUDED.endpoint, join_authorisation = EXCLUDED.join_authorisation,
manifest_digest = EXCLUDED.manifest_digest, expires_at = EXCLUDED.expires_at,
revision = EXCLUDED.revision
WHERE assignments.allocation_id = EXCLUDED.allocation_id
AND assignments.server_id = EXCLUDED.server_id
AND assignments.slot = EXCLUDED.slot
AND assignments.region = EXCLUDED.region
AND assignments.client_build = EXCLUDED.client_build
AND assignments.protocol_version = EXCLUDED.protocol_version
AND assignments.transport = EXCLUDED.transport
AND assignments.endpoint = EXCLUDED.endpoint
AND assignments.join_authorisation = EXCLUDED.join_authorisation
AND assignments.manifest_digest = EXCLUDED.manifest_digest
AND assignments.expires_at = EXCLUDED.expires_at
AND assignments.revision = EXCLUDED.revision`
const AssignmentSelectSQL = `SELECT match_id, player_id, allocation_id, server_id,
slot, region, client_build, protocol_version, transport, endpoint,
join_authorisation, manifest_digest, expires_at, revision
FROM assignments
WHERE match_id = $1 AND player_id = $2 AND expires_at > $3`
func validateDurableAssignment(assignment DurableAssignment) error {
if assignment.MatchID == "" || assignment.PlayerID == "" || assignment.AllocationID == "" || assignment.ServerID == "" || assignment.Slot < 0 || assignment.Slot > 5 || (assignment.Region != "EU" && assignment.Region != "NA") || assignment.ClientBuild == "" || assignment.ProtocolVersion < 1 || (assignment.Transport != "enet" && assignment.Transport != "steam_sdr") || assignment.Endpoint == "" || assignment.JoinAuthorisation == "" || len(assignment.ManifestDigest) == 0 || assignment.ExpiresAt.IsZero() || assignment.Revision < 0 {
return fmt.Errorf("invalid durable assignment")
}
return nil
}
func SaveAssignment(ctx context.Context, db *sql.DB, assignment DurableAssignment) error {
if db == nil {
return fmt.Errorf("invalid assignment database")
}
if err := validateDurableAssignment(assignment); err != nil {
return err
}
result, err := db.ExecContext(ctx, AssignmentUpsertSQL, assignment.MatchID, assignment.PlayerID, assignment.AllocationID, assignment.ServerID, assignment.Slot, assignment.Region, assignment.ClientBuild, assignment.ProtocolVersion, assignment.Transport, assignment.Endpoint, assignment.JoinAuthorisation, assignment.ManifestDigest, assignment.ExpiresAt, assignment.Revision)
if err != nil {
return err
}
changed, err := result.RowsAffected()
if err != nil {
return err
}
if changed != 1 {
return fmt.Errorf("assignment persistence conflict")
}
return nil
}
func GetAssignment(ctx context.Context, db *sql.DB, playerID, matchID string, now time.Time) (DurableAssignment, error) {
if db == nil || playerID == "" || matchID == "" || now.IsZero() {
return DurableAssignment{}, fmt.Errorf("invalid assignment recovery arguments")
}
var assignment DurableAssignment
err := db.QueryRowContext(ctx, AssignmentSelectSQL, matchID, playerID, now).Scan(&assignment.MatchID, &assignment.PlayerID, &assignment.AllocationID, &assignment.ServerID, &assignment.Slot, &assignment.Region, &assignment.ClientBuild, &assignment.ProtocolVersion, &assignment.Transport, &assignment.Endpoint, &assignment.JoinAuthorisation, &assignment.ManifestDigest, &assignment.ExpiresAt, &assignment.Revision)
if err != nil {
return DurableAssignment{}, err
}
if err := validateDurableAssignment(assignment); err != nil {
return DurableAssignment{}, err
}
return assignment, nil
}
+31
View File
@@ -0,0 +1,31 @@
package store
import (
"testing"
"time"
)
func TestAssignmentSQLBindsPlayerAndPreservesIdenticalReplay(t *testing.T) {
for query, fragments := range map[string][]string{
AssignmentUpsertSQL: {"ON CONFLICT (match_id, player_id)", "WHERE assignments.allocation_id = EXCLUDED.allocation_id", "join_authorisation", "manifest_digest"},
AssignmentSelectSQL: {"match_id = $1", "player_id = $2", "expires_at > $3"},
} {
for _, fragment := range fragments {
if !contains(query, fragment) {
t.Fatalf("query %q missing %q", query, fragment)
}
}
}
}
func TestAssignmentStoreRejectsInvalidRecoveryAndManifestInputs(t *testing.T) {
if _, err := GetAssignment(nil, nil, "player-1", "match-1", time.Unix(1000, 0)); err == nil {
t.Fatal("nil database accepted")
}
if err := SaveAssignment(nil, nil, DurableAssignment{MatchID: "match-1", PlayerID: "player-1", ExpiresAt: time.Unix(1000, 0)}); err == nil {
t.Fatal("incomplete assignment accepted")
}
if err := validateDurableAssignment(DurableAssignment{MatchID: "match-1", PlayerID: "player-1", AllocationID: "allocation-1", ServerID: "server-1", Slot: 6, Region: "EU", ClientBuild: "build-1", ProtocolVersion: 1, Transport: "enet", Endpoint: "127.0.0.1:1", JoinAuthorisation: "join", ManifestDigest: []byte("digest"), ExpiresAt: time.Unix(1001, 0)}); err == nil {
t.Fatal("out-of-range slot accepted")
}
}