MudEngine Part 7: Save & Load
Replace Server State
The old server kept players in a standalone PLAYERS static and validated moves against the EXITS constant from room_data.rs. The new code replaces all of that with GAME_STATE — a single LazyLock<Mutex<GameState>> that assembles its two halves from the two files: rooms from load_world("Game.toml"), players from load_players("Players.toml").
The load/save functions (load_world, load_players, save_players, can_move) now live in persistence.rs. The two statics (GAME_STATE and BROADCAST) stay in the srv module inside server.rs — they are server-only implementation details.
We also remove the old EXITS constant from room_data.rs. Movement validation now searches the loaded room data by ID instead of indexing into a static slice.
std::sync::Mutex and std::sync::LazyLock are both part of std — no extra dependency needed.
LazyLockinitialises the game state the first timeGAME_STATE.lock()is called, not at program start. This means the world and the player file are loaded lazily, which works fine since the first WebSocket connection triggers the load.Mutexprotects the state across the threaded Tokio runtime. All game operations (join, move, leave, save) hold the lock briefly and then release it.std::fs::writeis synchronous and blocking, but sincePlayers.tomlis tiny (a handful of lines), the lock is held for under a millisecond — negligible in a Tokio context, and simpler than spawning a write task.
The save_players call happens inside the locked scope, right after the mutation. This guarantees the disk file is always consistent with the in-memory state.