Files
sor/Client/origin-client/autoloads/Network.gd
T

307 lines
12 KiB
GDScript

extends Node
## Singleton WebSocket connection manager.
##
## Handles connection lifecycle, reconnection with exponential backoff,
## request/reply correlation via sequence numbers, and application-level
## keepalive (sends a network.ping every 30 s of idle; expects any reply
## within 30 s or forces a reconnect).
##
## Usage:
## Network.request("chat.send", payload, on_reply_callable, on_error_callable)
## Network.send("game.move", payload)
## Network.debug_log_packets = true # dump all sent/received JSON
# ── Configuration ─────────────────────────────────────────────────────────────
const SERVER_URL := "wss://hub.aeternalisgames.com/ws"
## Print every sent/received packet as JSON to stdout.
@export var debug_log_packets: bool = false
const KEEPALIVE_INTERVAL_SEC := 30.0 ## Idle seconds before sending an app-level ping.
const KEEPALIVE_TIMEOUT_SEC := 30.0 ## Seconds with no reply before forcing a reconnect.
const MAX_RECONNECT_DELAY := 30.0 ## Cap on exponential backoff (seconds).
# ── Signals ───────────────────────────────────────────────────────────────────
## Emitted once the WebSocket handshake completes. Auth will send its
## first message (auth.hello / auth.login / auth.register) in response.
signal connected
## Emitted when the connection is lost. Reconnect loop starts automatically.
signal disconnected
## Emitted for server-pushed messages that don't match a pending request.
signal message_received(type: String, payload: Variant)
# ── State machine ─────────────────────────────────────────────────────────────
enum _State { DISCONNECTED, CONNECTING, CONNECTED, RECONNECTING }
var _state: _State = _State.DISCONNECTED
var _ws: WebSocketPeer
var _seq: int = 0
var _pending: Dictionary = {} ## int(seq) → { on_reply: Callable, on_error: Callable }
var _ping_seq: int = -1 ## seq of the in-flight keepalive ping, or -1
var _reconnect_delay: float = 1.0
var _reconnect_timer: float = 0.0
var _last_rx_time: float = 0.0 ## Epoch-seconds of last received packet.
var _ping_sent_at: float = -1.0 ## Epoch-seconds when keepalive ping was sent, or -1.
# ── Lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
_connect_now()
func _process(delta: float) -> void:
# ── DISCONNECTED: nothing to do ────────────────────────────────────────────
if _state == _State.DISCONNECTED:
return
# ── RECONNECTING: count down and retry ────────────────────────────────────
if _state == _State.RECONNECTING:
_reconnect_timer -= delta
if _reconnect_timer <= 0.0:
_connect_now()
return
# ── CONNECTING / CONNECTED: drive the WebSocket ───────────────────────────
_ws.poll()
var ws_ready := _ws.get_ready_state()
match ws_ready:
WebSocketPeer.STATE_OPEN:
if _state == _State.CONNECTING:
_on_ws_opened()
# Fall through to packet/keepalive processing below.
WebSocketPeer.STATE_CLOSED:
if _state == _State.CONNECTED:
# Drain any packets the server sent just before closing (e.g. an
# auth error response followed immediately by the close frame).
# Without this, both arrive in the same poll() and we return early
# here, so _poll_packets() is skipped and _on_ws_closed() fires
# DISCONNECTED for all pending requests before the real error is
# dispatched — causing auth.hello failures to look like reconnect
# drops and keeping the session token alive indefinitely.
_poll_packets()
_on_ws_closed()
else: # STATE_CONNECTING → connection attempt failed
_schedule_reconnect()
return
WebSocketPeer.STATE_CLOSING:
return # Wait for STATE_CLOSED on the next poll.
# Only run packet/keepalive while fully connected.
if _state == _State.CONNECTED:
_poll_packets()
_tick_keepalive()
# ── Public API ────────────────────────────────────────────────────────────────
## Send [param type] with [param payload] and register callbacks.
## [param on_reply] is called as (type: String, payload: Variant).
## [param on_error] is called as (error_code: String, message: String).
## Returns the sequence number used (useful for cancellation).
func request(
type: String,
payload: Variant,
on_reply: Callable,
on_error: Callable = Callable()) -> int:
_seq += 1
var seq := _seq
if _state != _State.CONNECTED:
# Fail immediately rather than dropping the send silently and leaving a
# dangling pending entry that never gets a response.
if on_error.is_valid():
on_error.call("DISCONNECTED", "Not connected.")
return seq
_pending[seq] = { &"on_reply": on_reply, &"on_error": on_error }
_send_raw({ "type": type, "seq": seq, "payload": payload })
return seq
## Fire-and-forget send. No reply tracking.
func send(type: String, payload: Variant = {}) -> void:
_seq += 1
_send_raw({ "type": type, "seq": _seq, "payload": payload })
## True when the WebSocket is fully open.
func is_online() -> bool:
return _state == _State.CONNECTED
## Force-close the current connection and schedule a reconnect.
## Call on logout so the next auth.login / auth.register arrives on a fresh
## connection — the server only accepts those as the very first message.
func force_reconnect() -> void:
if _ws != null and _ws.get_ready_state() in \
[WebSocketPeer.STATE_OPEN, WebSocketPeer.STATE_CONNECTING]:
_ws.close(1000, "client_logout")
# STATE_CLOSED is detected on the next _process() poll,
# which calls _on_ws_closed() → _schedule_reconnect() automatically.
# ── Connection helpers ────────────────────────────────────────────────────────
func _connect_now() -> void:
_ws = WebSocketPeer.new()
# content.sync.ack for a full card catalog can be several hundred KB.
# Godot's default is 65535 bytes which triggers code 1009 on large responses.
_ws.inbound_buffer_size = 4 * 1024 * 1024 # 4 MB
_state = _State.CONNECTING
var err := _ws.connect_to_url(SERVER_URL)
if err != OK:
push_warning("Network: connect_to_url failed — %s" % error_string(err))
_schedule_reconnect()
return
if debug_log_packets:
print("[Net] Connecting → %s" % SERVER_URL)
func _on_ws_opened() -> void:
_state = _State.CONNECTED
_reconnect_delay = 1.0
_last_rx_time = _now()
_ping_sent_at = -1.0
if debug_log_packets:
print("[Net] Connected")
connected.emit()
func _on_ws_closed() -> void:
var code := _ws.get_close_code()
var reason := _ws.get_close_reason()
if debug_log_packets:
print("[Net] Closed code=%d reason=%s" % [code, reason])
# Map server-encoded close reasons to error codes so callers (e.g. Auth.gd)
# can take the right action. Godot discards buffered data packets when the
# close frame arrives, so the reason field is the only signal we have.
var error_code: String
var error_msg: String
match reason:
"auth_failed":
error_code = "AUTH_FAILED"
error_msg = "Session expired or revoked."
"auth_required":
error_code = "AUTH_REQUIRED"
error_msg = "Authentication required."
_:
error_code = "DISCONNECTED"
error_msg = "Connection lost."
# Fail all pending requests immediately.
for seq in _pending.keys():
var cb: Dictionary = _pending[seq]
if cb[&"on_error"].is_valid():
cb[&"on_error"].call(error_code, error_msg)
_pending.clear()
_ping_seq = -1
_ping_sent_at = -1.0
_schedule_reconnect()
disconnected.emit()
func _schedule_reconnect() -> void:
_state = _State.RECONNECTING
_reconnect_timer = _reconnect_delay
_reconnect_delay = minf(_reconnect_delay * 2.0, MAX_RECONNECT_DELAY)
if debug_log_packets:
print("[Net] Reconnecting in %.1f s (next backoff=%.1f s)"
% [_reconnect_timer, _reconnect_delay])
# ── Packet I/O ────────────────────────────────────────────────────────────────
func _poll_packets() -> void:
while _ws.get_available_packet_count() > 0:
var raw := _ws.get_packet()
var text := raw.get_string_from_utf8()
_last_rx_time = _now()
_ping_sent_at = -1.0 # Any received packet resets the ping watchdog.
if debug_log_packets:
print("[Net] << %s" % text)
var parsed: Variant = JSON.parse_string(text)
#print("[Parsed Type] ", type_string(typeof(parsed)))
if typeof(parsed) != TYPE_DICTIONARY:
if (parsed != null):
push_warning("Network: non-object packet — %s" % text)
continue
_dispatch(parsed as Dictionary)
func _dispatch(packet: Dictionary) -> void:
var ref : int = packet.get("ref", -1)
var type : String = packet.get("type", "")
var payload: Variant = packet.get("payload", {})
if ref >= 0 and _pending.has(ref):
var cb: Dictionary = _pending[ref]
_pending.erase(ref)
if type == "error":
var error_code: String = (payload as Dictionary).get("errorCode", "UNKNOWN")
var message: String = (payload as Dictionary).get("message", "")
# UNKNOWN_TYPE for our own keepalive ping is expected — swallow it.
if ref == _ping_seq and error_code == "UNKNOWN_TYPE":
return
if cb[&"on_error"].is_valid():
cb[&"on_error"].call(error_code, message)
else:
if cb[&"on_reply"].is_valid():
cb[&"on_reply"].call(type, payload)
return
# Not a reply to a known request — broadcast/push to listeners.
message_received.emit(type, payload)
func _send_raw(msg: Dictionary) -> void:
if _ws == null or _ws.get_ready_state() != WebSocketPeer.STATE_OPEN:
push_warning("Network: dropped send (not connected) type=%s"
% msg.get("type", "?"))
return
var text := JSON.stringify(msg)
if debug_log_packets:
print("[Net] >> %s" % text)
_ws.send_text(text)
# ── Keepalive ─────────────────────────────────────────────────────────────────
func _tick_keepalive() -> void:
var now := _now()
if _ping_sent_at >= 0.0:
# Ping already in flight — check for timeout.
if now - _ping_sent_at > KEEPALIVE_TIMEOUT_SEC:
push_warning("Network: keepalive timeout — forcing reconnect")
_ws.close(1001, "keepalive_timeout")
_on_ws_closed()
return
if now - _last_rx_time >= KEEPALIVE_INTERVAL_SEC:
# Send application-level ping. The server has no handler so it will
# reply with error UNKNOWN_TYPE, which is silently swallowed in
# _dispatch(). The reply itself resets _ping_sent_at and counts as
# proof the round-trip works.
_seq += 1
_ping_seq = _seq
_pending[_ping_seq] = { &"on_reply": Callable(), &"on_error": Callable() }
_send_raw({ "type": "network.ping", "seq": _ping_seq, "payload": {} })
_ping_sent_at = now
if debug_log_packets:
print("[Net] Keepalive ping seq=%d" % _ping_seq)
func _now() -> float:
return Time.get_ticks_msec() / 1000.0