mirror of
https://github.com/jcreek/CosmicClash.git
synced 2026-09-10 16:04:04 +00:00
801fca7cb0
domain.validCandidate hard-requires a non-empty PredictedRTT map, but
CreateQueueTicket persisted an empty one and the only endpoint that
could fill it returned 503 in every real binary, because Service.Probe
was assigned nowhere outside api tests. No client-created ticket could
ever be selected by the matcher. The Godot client had no probe method at
all, so even a wired backend was unreachable from the game.
Four distinct defects had to be fixed for this path to work:
Nothing issued the nonce ProbeProvider was meant to compare against, so
the contract could not be satisfied even in principle. Add
POST /v1/probes/{region}/challenge, backed by a durable single-use
challenge -- durable because any replica may serve the answer for a
challenge another replica issued. RTT is the interval between issuing
and receiving, so no client-reported latency reaches placement.
CreateQueueTicket marshalled a nil map to JSON `null`, a JSONB scalar
rather than an object, and jsonb_set rejects that with "cannot set path
in scalar". RecordProbe would have failed at runtime even once wired.
Persist an object, and normalise non-object values in the update for
rows already written.
A nil ProbeRecorder made the handler report success while persisting
nothing, which silently leaves the ticket unmatchable. That is a
misconfiguration, not a successful probe; it now returns 503.
A successful probe updated PostgreSQL only. The candidate inserted at
enqueue time carries an empty RTT map, and the Redis keyspace has its
TTL continually refreshed, so the stale entry need never repair itself.
Refresh that player's projection after the probe commits.
Client side: add the challenge/answer round trip and have the
matchmaking screen collect evidence before creating a ticket, since
queueing first produces a search that can never match. Probing every
region fully is not required -- placement uses whichever regions
answered -- but queueing with none is refused rather than silently
stalling.
New integration test drives the real enqueue and probe paths and then
asks the actual matcher predicate, rather than hand-building a candidate
the way the unit tests do -- which is exactly why they missed this.
Also make the integration schema reset drop the whole public schema: the
enumerated table list silently broke with each new migration.
103 lines
5.1 KiB
Python
103 lines
5.1 KiB
Python
"""Dependency-free structural checks for the versioned control-plane contract."""
|
|
|
|
import json
|
|
from pathlib import Path
|
|
import unittest
|
|
|
|
|
|
ROOT = Path(__file__).parent
|
|
|
|
|
|
class ContractTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.openapi = json.loads((ROOT / "openapi.json").read_text())
|
|
cls.events = json.loads((ROOT / "websocket-events.json").read_text())
|
|
cls.transitions = json.loads((ROOT / "state-transitions.json").read_text())
|
|
|
|
def test_openapi_is_versioned_and_has_core_surfaces(self):
|
|
self.assertEqual(self.openapi["openapi"], "3.1.0")
|
|
operations = {
|
|
operation["operationId"]
|
|
for path in self.openapi["paths"].values()
|
|
for operation in path.values()
|
|
if isinstance(operation, dict) and "operationId" in operation
|
|
}
|
|
# These are the operation IDs generated clients bind to, so a rename
|
|
# here is a breaking change for every consumer. Assert the difference
|
|
# rather than a bare subset check: a plain assertTrue reports only
|
|
# "False is not true" and hides which operation went missing.
|
|
required = {
|
|
"createSteamSession", "getProfile", "createQueueTicket",
|
|
"heartbeatQueueTicket", "cancelQueueTicket", "acceptProposal",
|
|
"declineProposal", "getAssignment", "registerServer",
|
|
"claimPlayerConnection", "submitMatchResult", "getRankedProfile",
|
|
}
|
|
self.assertEqual(set(), required - operations)
|
|
|
|
def test_ranked_profile_contract_is_authoritative_and_optional_season_metadata(self):
|
|
schema = self.openapi["components"]["schemas"]["RankedProfile"]
|
|
self.assertEqual(schema["required"], ["rating", "rd", "volatility", "ranked_games", "tier", "provisional"])
|
|
self.assertFalse(schema["additionalProperties"])
|
|
self.assertEqual(schema["properties"]["season_ends_at"]["format"], "date-time")
|
|
self.assertNotIn("access_token", json.dumps(schema).lower())
|
|
|
|
def test_mutations_require_idempotency_and_revision(self):
|
|
parameters = self.openapi["components"]["parameters"]
|
|
self.assertEqual(parameters["IdempotencyKey"]["name"], "Idempotency-Key")
|
|
self.assertTrue(parameters["IdempotencyKey"]["required"])
|
|
self.assertEqual(parameters["ExpectedRevision"]["name"], "If-Match-Revision")
|
|
for path, methods in self.openapi["paths"].items():
|
|
for method, operation in methods.items():
|
|
if method not in {"post", "delete", "put", "patch"} or "operationId" not in operation:
|
|
continue
|
|
# Exempt: these establish or consume a single-use credential
|
|
# rather than mutating a revisioned resource. A probe challenge
|
|
# is deliberately new on every call, and its answer is made
|
|
# single-use by consuming the nonce, so an idempotency key
|
|
# would be meaningless rather than protective.
|
|
if operation["operationId"] in {"createSteamSession", "createProbeChallenge", "submitProbeAnswer"}:
|
|
continue
|
|
refs = {item.get("$ref") for item in operation.get("parameters", [])}
|
|
self.assertIn("#/components/parameters/IdempotencyKey", refs, path)
|
|
|
|
def test_state_vocabulary_is_shared(self):
|
|
queue_states = self.openapi["components"]["schemas"]["QueueState"]["enum"]
|
|
websocket_states = self.events["$defs"]["stateChanged"]["allOf"][1]["properties"]["state"]["enum"]
|
|
self.assertEqual(queue_states, websocket_states)
|
|
self.assertIn("ASSIGNMENT_READY", queue_states)
|
|
self.assertIn("RESULT_PENDING", queue_states)
|
|
|
|
def test_events_have_revisioned_envelopes_and_no_credentials(self):
|
|
envelope = self.events["$defs"]["envelope"]
|
|
self.assertEqual(envelope["required"], ["event", "revision", "resource_id", "occurred_at"])
|
|
serialized = json.dumps(self.events).lower()
|
|
self.assertNotIn("access_token", serialized)
|
|
self.assertNotIn("web_api_ticket", serialized)
|
|
self.assertNotIn("relay_ticket", serialized)
|
|
|
|
def test_state_machine_has_explicit_recovery_and_terminal_edges(self):
|
|
for resource, states in self.transitions["resource_states"].items():
|
|
graph = self.transitions["transitions"][resource]
|
|
self.assertEqual(set(states), set(graph))
|
|
for state, targets in graph.items():
|
|
self.assertTrue(set(targets) <= set(states))
|
|
if state in {"COMPLETED", "CANCELLED", "EXPIRED", "FAILED"}:
|
|
self.assertEqual(targets, [], state)
|
|
|
|
queue = self.transitions["transitions"]["queue_ticket"]
|
|
self.assertIn("QUEUED", queue["PROPOSED"])
|
|
self.assertIn("QUEUED", queue["ACCEPTED"])
|
|
self.assertEqual(
|
|
self.transitions["mutation_rules"]["same_key_same_payload"],
|
|
"return_original_result_without_new_revision",
|
|
)
|
|
self.assertEqual(
|
|
self.transitions["mutation_rules"]["same_key_different_payload"],
|
|
"reject_conflict_without_state_change",
|
|
)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|