neon-sprawl/client/scripts/player_combat_health_client.gd

90 lines
2.6 KiB
GDScript

extends Node
## NEO-97: prototype HTTP client for [code]GET /game/players/{id}/combat-health[/code] (NEO-95).
signal health_received(snapshot: Dictionary)
signal health_sync_failed(reason: String)
const SCHEMA_VERSION := 1
@export var base_url: String = "http://127.0.0.1:5253"
@export var dev_player_id: String = "dev-local-1"
@export var injected_http: Node = null
var _http: Node
var _busy: bool = false
func _ready() -> void:
if injected_http != null:
_http = injected_http
else:
_http = HTTPRequest.new()
add_child(_http)
if _http is HTTPRequest:
(_http as HTTPRequest).timeout = 30.0
@warning_ignore("unsafe_method_access")
_http.request_completed.connect(_on_request_completed)
func request_sync_from_server() -> void:
if _busy:
return
_busy = true
var url := "%s/game/players/%s/combat-health" % [_base_root(), _player_path_segment()]
var err: Error = _http.request(url)
if err != OK:
var reason := "GET failed to start (%s)" % err
push_warning("PlayerCombatHealthClient: %s" % reason)
_busy = false
health_sync_failed.emit(reason)
static func parse_combat_health_json(text: String) -> Variant:
var parsed: Variant = JSON.parse_string(text)
if not parsed is Dictionary:
return null
var root: Dictionary = parsed
if int(root.get("schemaVersion", -1)) != SCHEMA_VERSION:
return null
if not root.has("currentHp") or not root.has("maxHp"):
return null
return root
func _base_root() -> String:
return base_url.strip_edges().rstrip("/")
func _player_path_segment() -> String:
return dev_player_id.strip_edges()
func _on_request_completed(
result: int, response_code: int, _headers: PackedStringArray, body: PackedByteArray
) -> void:
_busy = false
if result != HTTPRequest.RESULT_SUCCESS:
var reason := "HTTP failed (result=%s)" % result
push_warning("PlayerCombatHealthClient: %s" % reason)
health_sync_failed.emit(reason)
return
if response_code == 404:
var reason_404 := "HTTP 404 (player unknown)"
push_warning("PlayerCombatHealthClient: %s" % reason_404)
health_sync_failed.emit(reason_404)
return
if response_code < 200 or response_code >= 300:
var reason_code := "HTTP %s" % response_code
push_warning("PlayerCombatHealthClient: %s" % reason_code)
health_sync_failed.emit(reason_code)
return
var text := body.get_string_from_utf8()
var snapshot: Variant = parse_combat_health_json(text)
if snapshot == null:
var reason_json := "non-JSON body or schemaVersion mismatch"
push_warning("PlayerCombatHealthClient: %s" % reason_json)
health_sync_failed.emit(reason_json)
return
health_received.emit(snapshot as Dictionary)