feat: connect Godot matchmaking event stream

This commit is contained in:
Josh Creek
2026-08-31 23:06:44 +01:00
parent d258f17852
commit a16db39884
3 changed files with 101 additions and 2 deletions
+94
View File
@@ -8,6 +8,8 @@ signal request_succeeded(operation: String, payload: Dictionary)
signal request_failed(operation: String, http_code: int, detail: String)
signal session_expired()
signal session_changed(player_id: String)
signal websocket_event(event: Dictionary)
signal websocket_status_changed(status: String)
const DEFAULT_BASE_URL := "http://127.0.0.1:8080"
const PERSIST_PATH := "user://matchmaking_state.cfg"
@@ -24,6 +26,8 @@ var assignment: AssignmentState
var _request: HTTPRequest
var _operation := ""
var _last_queue_create: Dictionary = {}
var _websocket: WebSocketPeer
var _websocket_status := "DISCONNECTED"
func _ready() -> void:
@@ -36,6 +40,23 @@ func _ready() -> void:
_request.timeout = 10.0
add_child(_request)
_request.request_completed.connect(_on_request_completed)
state.resync_required.connect(_on_resync_required)
_websocket = WebSocketPeer.new()
func _process(_delta: float) -> void:
if _websocket == null:
return
_websocket.poll()
var ready_state := _websocket.get_ready_state()
if ready_state == WebSocketPeer.STATE_OPEN:
_set_websocket_status("CONNECTED")
while _websocket.get_available_packet_count() > 0:
_handle_websocket_packet(_websocket.get_packet())
elif ready_state == WebSocketPeer.STATE_CONNECTING:
_set_websocket_status("CONNECTING")
elif ready_state == WebSocketPeer.STATE_CLOSED:
_set_websocket_status("DISCONNECTED")
func configure(url: String, token: String) -> bool:
@@ -49,6 +70,33 @@ func configure(url: String, token: String) -> bool:
return true
func connect_event_stream() -> Error:
if not is_valid_access_token(access_token) or auth_expired or not is_valid_base_url(base_url):
return ERR_UNAUTHORIZED
var socket_url := websocket_url(base_url) + "/v1/events"
_websocket = WebSocketPeer.new()
var err := _websocket.connect_to_url(socket_url, PackedStringArray(["Authorization: Bearer " + access_token]))
if err != OK:
_set_websocket_status("DISCONNECTED")
return err
_set_websocket_status("CONNECTING")
return OK
func disconnect_event_stream() -> void:
if _websocket != null:
_websocket.close()
_set_websocket_status("DISCONNECTED")
static func websocket_url(url: String) -> String:
if url.begins_with("https://"):
return "wss://" + url.trim_prefix("https://")
if url.begins_with("http://"):
return "ws://" + url.trim_prefix("http://")
return ""
func queue_create(ticket_id: String, playlist: String, client_build: String, protocol_version: int) -> Error:
if ticket_id.is_empty() or (playlist != "casual" and playlist != "ranked") or client_build.is_empty() or protocol_version < 1:
return ERR_INVALID_PARAMETER
@@ -242,6 +290,52 @@ func _on_request_completed(result: HTTPRequest.Result, response_code: int, _head
request_succeeded.emit(operation, payload)
func _handle_websocket_packet(packet: PackedByteArray) -> void:
var parsed = JSON.parse_string(packet.get_string_from_utf8())
if not parsed is Dictionary or not _valid_websocket_event(parsed):
websocket_status_changed.emit("INVALID_EVENT")
return
var event: Dictionary = parsed
websocket_event.emit(event)
var event_name := String(event["event"])
if event_name == "state_changed":
var update := event.duplicate(true)
update["ticket_id"] = String(event["resource_id"])
if not state.apply_ticket_update(update):
return
elif event_name == "proposal_changed":
var proposal_update := event.duplicate(true)
proposal_update["proposal_id"] = String(event["resource_id"])
state.apply_proposal_update(proposal_update)
func _valid_websocket_event(event: Dictionary) -> bool:
if not event.has("event") or not event["event"] is String or String(event["event"]).is_empty():
return false
if not event.has("revision") or not (event["revision"] is int or event["revision"] is float):
return false
if int(event["revision"]) < 0 or not event.has("resource_id") or not event["resource_id"] is String or String(event["resource_id"]).is_empty():
return false
if not event.has("occurred_at") or not event["occurred_at"] is String or String(event["occurred_at"]).is_empty():
return false
var event_name := String(event["event"])
return event_name in ["state_changed", "proposal_changed", "assignment_changed", "error"]
func _on_resync_required(resource_id: String) -> void:
if resource_id == state.ticket_id and not state.ticket_id.is_empty():
recover_queue(state.ticket_id)
elif resource_id == state.proposal_id and not state.proposal_id.is_empty():
recover_proposal(state.proposal_id)
func _set_websocket_status(status: String) -> void:
if _websocket_status == status:
return
_websocket_status = status
websocket_status_changed.emit(status)
func _idempotency_key(prefix: String) -> String:
return "%s-%s-%s" % [prefix, str(Time.get_ticks_usec()), str(randi())]
@@ -22,6 +22,11 @@ func test_base_url_validation_rejects_ambiguous_or_insecure_values() -> void:
assert_true(ControlPlaneClient.is_valid_access_token("session-id:opaque-token"), "opaque session format is accepted")
assert_true(not ControlPlaneClient.is_valid_access_token(":opaque-token"), "missing session identifier is rejected")
assert_true(not ControlPlaneClient.is_valid_access_token("session-id:token\nforged"), "session header injection is rejected")
assert_eq(ControlPlaneClient.websocket_url("https://match.example"), "wss://match.example", "TLS control plane uses secure WebSocket")
assert_eq(ControlPlaneClient.websocket_url("http://127.0.0.1:8080"), "ws://127.0.0.1:8080", "local control plane uses WebSocket")
assert_eq(ControlPlaneClient.websocket_url("match.example"), "", "unscoped URL cannot become a WebSocket URL")
var unconfigured := ControlPlaneClient.new()
assert_eq(unconfigured.connect_event_stream(), ERR_UNAUTHORIZED, "event stream requires an authenticated session")
func test_ticket_normalization_preserves_payload_and_derives_expiry() -> void:
+2 -2
View File
@@ -1226,8 +1226,8 @@ the local/CI/community transport, not a silent production fallback.
| # | Task | Acceptance |
|---|---|---|
| 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 now provides targeted authenticated revisioned event publication | `test_matchmaking_state.gd`, `test_control_plane_client.gd`, `test_matchmaking_ui.gd`, `TestProposalRecoveryIsParticipantScopedAndExpiresAtReadBoundary` and `TestAuthenticatedWebSocketDeliversOnlyTargetedRevisionedEvents` 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 validation and REST-resync-safe slow-client failure | `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 and targeted event delivery; Godot WebSocket client wiring, durable outbox fan-out, reconnect/resync orchestration and live Godot verification remain |
| 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 now provides targeted authenticated revisioned event publication and the Godot client consumes state/proposal events | `test_matchmaking_state.gd`, `test_control_plane_client.gd`, `test_matchmaking_ui.gd`, `TestProposalRecoveryIsParticipantScopedAndExpiresAtReadBoundary` and `TestAuthenticatedWebSocketDeliversOnlyTargetedRevisionedEvents` 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 validation and REST-resync-safe slow-client failure; Godot `ControlPlaneClient` can connect to the stream, consume validated events, and trigger REST recovery on projection gaps | `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 and targeted event delivery; durable outbox fan-out, reconnect/resync orchestration 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.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 |