Godot client: version check + content sync + caching architecture

Client flow after auth is now:
  LoginScreen → auth_success → InitScreen → MainScreen

autoloads/ContentCache.gd
  - Cursor-based incremental sync via content.sync (PageSize=200)
  - Merges definition DTOs in-memory (id → Dictionary)
  - Persists to user://content/defs.json on sync completion
  - Incremental on repeat launches: 0 round trips when nothing changed
  - Signals: sync_progress(fetched_total), sync_complete(total), sync_failed(error)

scenes/init/InitScreen.tscn + init_screen.gd
  - Step 1: version.check (clientVersion="0.1.0", platform="web")
      UpdateRequired  → show "please refresh" panel, block
      UpdateAvailable → soft banner, continue
      Ok              → continue
      DISCONNECTED    → wait for Network.connected (one-shot), retry
      other error     → warn + proceed (don't block player on non-critical check)
  - Step 2: ContentCache.start_sync()
      Shows running card count while pages arrive
      On sync_complete: transition to MainScreen
      On sync_failed: show error + Retry button

scenes/login/login_screen.gd
  - _go_to_main() now routes to InitScreen instead of MainScreen directly

project.godot
  - ContentCache registered as autoload (loads before Auth)
  - pointing/emulate_touch_from_mouse=true for desktop browser testing

Caching architecture decision (see plan):
  - Layer 1 (definitions/text): always sync all eagerly — no privacy concern
  - Layer 2 (2D art): lazy by definition ID, CDN fetch on demand
  - Layer 3 (3D models/animations): set-bundle granularity + server-injected
    noise during match pre-warm to prevent cache oracle attack
    (Layer 2/3 implementation is future work)

Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)

Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
dingo
2026-02-27 21:31:47 -05:00
co-authored by Claude Happy
parent 3aaabe75e3
commit 2d6b20f3cb
5 changed files with 346 additions and 2 deletions
@@ -0,0 +1,140 @@
extends Node
## Local card-definition cache.
##
## Syncs all published card definitions from the server using the
## content.sync message (cursor-based, incremental). Definitions are text
## only (stats, CDN URLs for art/models) — no binary assets are stored here.
##
## Storage layout:
## user://content/defs.json — { "version": int, "defs": { id: dto } }
##
## Sync is incremental: on the first launch SinceVersion=0 fetches everything;
## on subsequent launches only cards changed since the stored cursor are fetched
## (usually 0 pages if nothing changed — instant).
##
## Usage:
## ContentCache.start_sync()
## ContentCache.get_definition("some-guid") → Dictionary or {}
## ContentCache.sync_complete.connect(...)
const CACHE_DIR := "user://content"
const CACHE_PATH := "user://content/defs.json"
const PAGE_SIZE := 200
signal sync_progress(fetched_total: int) ## Running count of total definitions in memory.
signal sync_complete(total: int) ## Emitted once sync finishes.
signal sync_failed(error: String) ## Emitted if sync cannot complete.
var _defs: Dictionary = {} ## definitionId (String) → definition Dictionary
var _sync_version: int = 0 ## Stored DefinitionVersion cursor.
var _is_syncing: bool = false
# ── Lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
_load_from_disk()
# ── Public API ────────────────────────────────────────────────────────────────
## Return the cached definition dictionary, or {} if not found.
func get_definition(id: String) -> Dictionary:
return _defs.get(id, {})
## True if the definition is cached.
func has_definition(id: String) -> bool:
return _defs.has(id)
## Returns all cached definition IDs.
func get_all_definition_ids() -> Array:
return _defs.keys()
## The current sync-version cursor (0 = never synced).
func get_sync_version() -> int:
return _sync_version
## Total number of definitions currently in memory.
func definition_count() -> int:
return _defs.size()
## Start (or resume) the incremental sync.
## Emits sync_progress during, sync_complete or sync_failed when done.
func start_sync() -> void:
if _is_syncing:
return
_is_syncing = true
_fetch_page(_sync_version)
# ── Sync loop ─────────────────────────────────────────────────────────────────
func _fetch_page(since_version: int) -> void:
Network.request(
"content.sync",
{ "sinceVersion": since_version, "pageSize": PAGE_SIZE },
func(_type: String, p: Variant): _on_page(p),
func(code: String, msg: String): _on_error(code, msg)
)
func _on_page(payload: Variant) -> void:
var p := payload as Dictionary
var cards : Array = p.get("cards", [])
var next_ver : int = p.get("currentVersion", _sync_version)
var has_more : bool = p.get("hasMore", false)
for card in cards:
var id: String = str(card.get("id", ""))
if not id.is_empty():
_defs[id] = card
_sync_version = next_ver
sync_progress.emit(_defs.size())
if has_more:
_fetch_page(next_ver)
else:
_is_syncing = false
_save_to_disk()
sync_complete.emit(_defs.size())
func _on_error(code: String, msg: String) -> void:
_is_syncing = false
var detail := msg if not msg.is_empty() else code
push_warning("ContentCache: sync failed — %s" % detail)
sync_failed.emit(detail)
# ── Persistence ───────────────────────────────────────────────────────────────
func _load_from_disk() -> void:
if not FileAccess.file_exists(CACHE_PATH):
return
var file := FileAccess.open(CACHE_PATH, FileAccess.READ)
if not file:
push_warning("ContentCache: could not open cache file")
return
var text := file.get_as_text()
file.close()
var parsed: Variant = JSON.parse_string(text)
if typeof(parsed) != TYPE_DICTIONARY:
push_warning("ContentCache: cache file is malformed — starting fresh")
return
var root := parsed as Dictionary
_sync_version = int(root.get("version", 0))
var defs: Variant = root.get("defs", {})
if typeof(defs) == TYPE_DICTIONARY:
_defs = defs as Dictionary
func _save_to_disk() -> void:
DirAccess.make_dir_recursive_absolute(CACHE_DIR)
var file := FileAccess.open(CACHE_PATH, FileAccess.WRITE)
if not file:
push_warning("ContentCache: could not write cache file")
return
file.store_string(JSON.stringify({ "version": _sync_version, "defs": _defs }))
file.close()
+5
View File
@@ -18,8 +18,13 @@ run/main_scene="res://scenes/login/LoginScreen.tscn"
[autoload]
Network="*res://autoloads/Network.gd"
ContentCache="*res://autoloads/ContentCache.gd"
Auth="*res://autoloads/Auth.gd"
[input_devices]
pointing/emulate_touch_from_mouse=true
[rendering]
renderer/rendering_method="mobile"
@@ -0,0 +1,72 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://scenes/init/init_screen.gd" id="1_init"]
[node name="InitScreen" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_init")
[node name="Background" type="ColorRect" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
color = Color(0.094, 0.094, 0.137, 1.0)
[node name="Center" type="CenterContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
[node name="VBox" type="VBoxContainer" parent="Center"]
layout_mode = 2
custom_minimum_size = Vector2(340, 0)
theme_override_constants/separation = 20
[node name="Logo" type="Label" parent="Center/VBox"]
layout_mode = 2
text = "ORIGIN"
horizontal_alignment = 1
theme_override_font_sizes/font_size = 36
[node name="StatusLabel" type="Label" parent="Center/VBox"]
unique_name_in_owner = true
layout_mode = 2
text = "Starting…"
horizontal_alignment = 1
autowrap_mode = 3
modulate = Color(0.75, 0.75, 0.8, 1.0)
theme_override_font_sizes/font_size = 14
[node name="UpdatePanel" type="VBoxContainer" parent="Center/VBox"]
unique_name_in_owner = true
layout_mode = 2
theme_override_constants/separation = 12
visible = false
[node name="UpdateMsg" type="Label" parent="Center/VBox/UpdatePanel"]
unique_name_in_owner = true
layout_mode = 2
text = "A required update is available."
horizontal_alignment = 1
autowrap_mode = 3
modulate = Color(1.0, 0.75, 0.3, 1.0)
theme_override_font_sizes/font_size = 14
[node name="RetryBtn" type="Button" parent="Center/VBox"]
unique_name_in_owner = true
layout_mode = 2
custom_minimum_size = Vector2(0, 48)
text = "Retry"
visible = false
theme_override_font_sizes/font_size = 15
@@ -0,0 +1,126 @@
extends Control
## Post-auth initialization screen.
##
## Runs on every launch after a successful authentication:
## 1. version.check — block on UpdateRequired; soft banner on UpdateAvailable
## 2. content.sync — incremental definition sync via ContentCache
## 3. Transition — change scene to MainScreen
##
## If the network is not yet up when this screen opens, we wait for the
## Network.connected signal before starting.
const CLIENT_VERSION := "0.1.0"
const PLATFORM := "web" # TODO: detect at runtime for native builds.
@onready var status_label : Label = %StatusLabel
@onready var update_panel : Control = %UpdatePanel
@onready var update_msg : Label = %UpdateMsg
@onready var retry_btn : Button = %RetryBtn
# ── Lifecycle ─────────────────────────────────────────────────────────────────
func _ready() -> void:
update_panel.visible = false
retry_btn.visible = false
ContentCache.sync_progress.connect(_on_sync_progress)
ContentCache.sync_complete.connect(_on_sync_complete)
ContentCache.sync_failed.connect(_on_sync_failed)
retry_btn.pressed.connect(_start)
if Network.is_online():
_start()
else:
_set_status("Connecting to server…")
Network.connected.connect(_start, CONNECT_ONE_SHOT)
func _exit_tree() -> void:
if ContentCache.sync_progress.is_connected(_on_sync_progress):
ContentCache.sync_progress.disconnect(_on_sync_progress)
if ContentCache.sync_complete.is_connected(_on_sync_complete):
ContentCache.sync_complete.disconnect(_on_sync_complete)
if ContentCache.sync_failed.is_connected(_on_sync_failed):
ContentCache.sync_failed.disconnect(_on_sync_failed)
# ── Initialization sequence ───────────────────────────────────────────────────
func _start() -> void:
update_panel.visible = false
retry_btn.visible = false
_set_status("Checking for updates…")
Network.request(
"version.check",
{ "clientVersion": CLIENT_VERSION, "platform": PLATFORM },
func(_type: String, p: Variant): _on_version_ok(p),
func(code: String, _msg: String): _on_version_error(code)
)
func _on_version_ok(payload: Variant) -> void:
var p := payload as Dictionary
var status := p.get("status", "Ok") as String
match status:
"UpdateRequired":
var url : String = p.get("downloadUrl", "") as String
var notes: String = p.get("releaseNotes", "") as String
update_panel.visible = true
if url.is_empty():
update_msg.text = (
"A required update is available.\n"
+ "Please refresh your browser to continue."
)
else:
update_msg.text = (
"A required update is available.\n%s\n\nRefresh your browser or visit:\n%s"
% [notes, url]
)
# Block here — do not proceed to sync.
"UpdateAvailable":
# Non-blocking soft notice, then continue.
_set_status("Update available (not required) — starting…")
_do_sync()
_: # "Ok" or anything unrecognised
_do_sync()
func _on_version_error(code: String) -> void:
if code == "DISCONNECTED":
# Lost connection before we got a reply — wait for reconnect and retry.
_set_status("Connection lost. Waiting to reconnect…")
Network.connected.connect(_start, CONNECT_ONE_SHOT)
return
# Any other error (server-side, unknown type, etc.): don't block the player.
push_warning("InitScreen: version check failed (%s) — proceeding anyway" % code)
_do_sync()
func _do_sync() -> void:
var cached := ContentCache.definition_count()
if cached > 0:
_set_status("Syncing card database… (%d cached)" % cached)
else:
_set_status("Downloading card database…")
ContentCache.start_sync()
# ── ContentCache signal handlers ──────────────────────────────────────────────
func _on_sync_progress(fetched_total: int) -> void:
_set_status("Syncing card database… (%d cards)" % fetched_total)
func _on_sync_complete(_total: int) -> void:
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")
func _on_sync_failed(error: String) -> void:
_set_status("Sync failed: %s" % error)
retry_btn.visible = true
# ── Helpers ───────────────────────────────────────────────────────────────────
func _set_status(text: String) -> void:
status_label.text = text
@@ -6,7 +6,8 @@ extends Control
## "Register" — email + password + display name → auth.register
##
## Listens to Auth.auth_success and Auth.auth_failed.
## On success: transitions to MainScreen.
## On success: transitions to InitScreen (which runs version check + content sync,
## then proceeds to MainScreen).
## On failure: shows an error message and re-enables the form.
# ── Node references (unique names set in the .tscn) ──────────────────────────
@@ -94,7 +95,7 @@ func _on_auth_failed(error_code: String, message: String) -> void:
# ── Helpers ───────────────────────────────────────────────────────────────────
func _go_to_main() -> void:
get_tree().change_scene_to_file("res://scenes/main/MainScreen.tscn")
get_tree().change_scene_to_file("res://scenes/init/InitScreen.tscn")
func _set_status(text: String, is_error: bool) -> void: