← All Workshops

MudEngine Part 7: Save & Load

Step 16 / 17

Sync to disk — autosave every minute

So far every mutation writes straight to Players.toml: join, move, and disconnect each call persistence::save_players(). Simple and durable — but it is also write amplification. A player tapping the arrow keys triggers a file write on every keystroke, even though the next move overwrites it a millisecond later.

Let's switch to a write-behind / sync model, exactly like a filesystem that buffers writes in memory and flushes them periodically:

  • the game state lives in memory — GAME_STATE stays the source of truth, and handlers only mutate it;
  • a background task takes a snapshot of the state and writes it to Players.toml every AUTOSAVE_INTERVAL;
  • the interval is a configurable constant and defaults to 60 seconds;
  • a crash loses at most the changes made since the last flush — the normal durability contract of write-behind storage.

Three changes: refactor persistence.rs, remove the inline saves from server.rs, then add the autosave task.

✂️ Replace, don't append

Keep load_world, load_players, and can_move exactly as they are. Only save_players changes — split it into a snapshot() half and a write_players() half. Once you're done, save_players no longer exists in the codebase.

The block below shows the complete persistence.rs at this stage — models, load_world, load_players, snapshot, write_players, and can_move. Replacing the whole file wholesale is the safest way to make the swap (it guarantees no stale save_players call sites survive inside this file).

mud-engine/src/game/persistence.rs
use std::collections::HashMap;

use serde::{Deserialize, Serialize};

// ── Shared models: one type per concept, reused for TOML, runtime, and wire ──

/// A single exit — matches the `{ direction, destination }` entries in Game.toml,
/// lives on every runtime room, and is sent to clients for the world grid.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct Exit {
    pub direction: String,
    pub destination: usize,
}

/// Room info sent to clients — and the same type Game.toml deserializes into.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct RoomInfo {
    pub id: usize,
    pub name: String,
    pub description: String,
    pub exits: Vec<Exit>,
}

/// A connected player — the type Players.toml deserializes into, the value in
/// GameState.players, and the wire type broadcast to clients.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct PlayerInfo {
    pub id: String,
    pub name: String,
    pub room: usize,
}

// ── TOML wrappers: thin containers for the file shape only ──

#[derive(Serialize, Deserialize)]
struct TomlWorld {
    rooms: Vec<RoomInfo>,
}

#[derive(Serialize, Deserialize)]
struct TomlPlayers {
    #[serde(default)]
    players: Vec<PlayerInfo>,
}

// ── Runtime game state (server only) ──

#[cfg(feature = "server")]
pub struct GameState {
    pub rooms: Vec<RoomInfo>,
    pub players: HashMap<String, PlayerInfo>,
}

// ── Persistence functions (server only) ──

#[cfg(feature = "server")]
pub fn load_world(path: &str) -> Vec<RoomInfo> {
    let content =
        std::fs::read_to_string(path).unwrap_or_else(|e| panic!("Failed to read {}: {}", path, e));
    let toml_world: TomlWorld =
        toml::from_str(&content).unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e));

    toml_world.rooms
}

#[cfg(feature = "server")]
pub fn load_players(path: &str) -> HashMap<String, PlayerInfo> {
    let Ok(content) = std::fs::read_to_string(path) else {
        return HashMap::new();
    };
    let toml_players: TomlPlayers =
        toml::from_str(&content).unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e));

    toml_players
        .players
        .into_iter()
        .map(|p| (p.id.clone(), p))
        .collect()
}

#[cfg(feature = "server")]
/// Serialize the live state into the TOML that goes into Players.toml.
/// This is fast (a few strings) and safe to do while holding the lock.
/// The disk write itself happens separately, in `write_players`.
pub fn snapshot(state: &GameState) -> String {
    let toml_players = TomlPlayers {
        players: state.players.values().cloned().collect(),
    };
    toml::to_string_pretty(&toml_players).unwrap()
}

#[cfg(feature = "server")]
/// Write a serialized snapshot to Players.toml. Call this *outside* the lock.
pub fn write_players(toml_str: &str) {
    std::fs::write("Players.toml", toml_str).unwrap();
}

#[cfg(feature = "server")]
pub fn can_move(state: &GameState, from_room: usize, direction: &str) -> Option<usize> {
    state
        .rooms
        .iter()
        .find(|r| r.id == from_room)
        .and_then(|r| {
            r.exits
                .iter()
                .find(|e| e.direction == direction)
                .map(|e| e.destination)
        })
}
mud-engine/src/game/server.rs
use dioxus::prelude::*;
use dioxus_fullstack::{WebSocketOptions, Websocket};

use super::messages::{ClientMessage, PlayerInfo, ServerMessage};
use super::persistence::{self, RoomInfo};

#[cfg(feature = "server")]
use super::persistence::GameState;

// ── Server-only state ──

#[cfg(feature = "server")]
mod srv {
    use std::sync::{LazyLock, Mutex};
    use std::time::Duration;
    use tokio::sync::broadcast;
    use tokio::time::{interval, MissedTickBehavior};

    use super::*;

    /// How often the in-memory game state is flushed to Players.toml.
    /// Configurable — crank it down (e.g. 5s) while testing, keep it at
    /// 60s in production. Crashes lose at most one interval of changes.
    const AUTOSAVE_INTERVAL: Duration = Duration::from_secs(60);

    /// The authoritative game state — rooms and connected players.
    /// The world comes from Game.toml (static); players from Players.toml (live).
    pub static GAME_STATE: LazyLock<Mutex<GameState>> = LazyLock::new(|| {
        // Start the background autosave task before any player connects.
        let _ = LazyLock::force(&AUTOSAVE);
        Mutex::new(GameState {
            rooms: persistence::load_world("Game.toml"),
            players: persistence::load_players("Players.toml"),
        })
    });

    /// Background task: every AUTOSAVE_INTERVAL, persist the in-memory state.
    /// The TOML view is built under the lock; the file write happens without it,
    /// so game ticks never block on disk I/O.
    pub static AUTOSAVE: LazyLock<()> = LazyLock::new(|| {
        tokio::spawn(async move {
            let mut tick = interval(AUTOSAVE_INTERVAL);
            tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
            tick.tick().await; // first tick fires immediately — wait a full interval

            loop {
                tick.tick().await;
                let snapshot = {
                    let state = GAME_STATE.lock().unwrap();
                    persistence::snapshot(&state)
                };
                persistence::write_players(&snapshot);
            }
        });
        ()
    });

    /// Broadcast channel — every connected WebSocket subscribes.
    pub static BROADCAST: LazyLock<broadcast::Sender<ServerMessage>> = LazyLock::new(|| {
        let (tx, _) = broadcast::channel(64);
        tx
    });
}

// ── WebSocket endpoint ──

#[get("/api/mud_ws?name")]
pub async fn mud_ws(
    name: String,
    options: WebSocketOptions,
) -> Result<Websocket<ClientMessage, ServerMessage>> {
    let id = uuid::Uuid::new_v4().to_string();
    let player_name = name.clone();

    // 1. Register the new player and build room info for the client
    let room_infos: Vec<RoomInfo>;
    {
        let mut state = srv::GAME_STATE.lock().unwrap();
        state.players.insert(
            id.clone(),
            PlayerInfo {
                id: id.clone(),
                name: name.clone(),
                room: 4, // Town Square
            },
        );

        // Rooms are already RoomInfo — the wire type — so they go straight out.
        room_infos = state.rooms.clone();
    }

    // 2. Subscribe to the broadcast channel
    let mut rx = srv::BROADCAST.subscribe();

    // 3. Announce the new player to everyone
    let _ = srv::BROADCAST.send(ServerMessage::PlayerJoined(PlayerInfo {
        id: id.clone(),
        name: name.clone(),
        room: 4,
    }));

    // 4. Build the initial state snapshot for this new player
    let initial_state = {
        let state = srv::GAME_STATE.lock().unwrap();
        ServerMessage::State {
            players: state.players.values().cloned().collect(),
            your_id: id.clone(),
            rooms: room_infos,
        }
    };

    // 5. Upgrade the HTTP connection to a WebSocket
    let ws = options.on_upgrade(move |mut socket| async move {
        let _ = socket.send(initial_state).await;

        // ── Message loop ──
        loop {
            tokio::select! {
                msg = socket.recv() => {
                    match msg {
                        Ok(ClientMessage::Move { direction }) => {
                            let dir = match direction.as_str() {
                                "n" => "north", "s" => "south",
                                "e" => "east", "w" => "west",
                                d => d,
                            };

                            let new_room = {
                                let mut state = srv::GAME_STATE.lock().unwrap();
                                let current = state.players.get(&id).unwrap().room;
                                let next = persistence::can_move(&state, current, dir);
                                if let Some(next) = next {
                                    state.players.get_mut(&id).unwrap().room = next;
                                    Some(next)
                                } else {
                                    None
                                }
                            };

                            if let Some(room) = new_room {
                                let _ = srv::BROADCAST.send(
                                    ServerMessage::PlayerMoved(PlayerInfo {
                                        id: id.clone(),
                                        name: player_name.clone(),
                                        room,
                                    }),
                                );
                            }
                        }
                        Err(_) => break,
                    }
                }

                msg = rx.recv() => {
                    match msg {
                        Ok(server_msg) => {
                            if socket.send(server_msg).await.is_err() {
                                break;
                            }
                        }
                        Err(_) => break,
                    }
                }
            }
        }

        // ── Cleanup on disconnect ──
        {
            let mut state = srv::GAME_STATE.lock().unwrap();
            state.players.remove(&id);
        }
        let _ = srv::BROADCAST.send(ServerMessage::PlayerLeft { id });
    });

    Ok(ws)
}
✂️ Remove the inline saves

Compare this whole-file listing with the one from the Update the WebSocket Endpoint step — the srv module is a pure in-memory mutator now. The naive version called persistence::save_players(&state); in exactly three places, all gone:

  1. right after the join-insert at the top of mud_ws (step 1, Register the new player)
  2. inside the Move handler, right after player.room = next
  3. in the disconnect cleanup, after state.players.remove(&id)

That's all — the WebSocket handler no longer owns persistence. The autosave task is the only writer.

🎯 Why snapshot under the lock, write outside?

The Mutex serialises game logic between concurrent WebSocket tasks. Writing the file while holding the lock would serialise the whole game behind one disk write. So persistence is split in two:

  • snapshot() — builds the TOML string. Taking ownership of a few small strings is microseconds, so it is fine inside the lock.
  • write_players() — the actual std::fs::write. This is where the blocking I/O happens; the autosave task calls it after the lock is released.

Because the autosave task is the only writer, concurrent writes don't race either — no extra lock needed.

💡 How the timer works

tokio::time::interval(period) yields a stream of ticks. Two details matter:

  • The first tick fires immediately (an interval quirk). We consume it with a bare tick.tick().await before the loop, so the first actual save happens one full interval after startup, and every tick after that is exactly AUTOSAVE_INTERVAL apart.
  • MissedTickBehavior::Skip means a delayed tick (e.g. during a GC pause) never fires a burst of catch-up writes — it simply resets for the next interval.

The interval is a plain const AUTOSAVE_INTERVAL: Duration, so tuning it is a one-line change. Set it to Duration::from_secs(5) while developing and watch syncs happen live; ship it at 60 s.

interval and MissedTickBehavior need tokio's time feature — that's why the dependencies step enabled ["sync", "time"].

⚠️ Crash semantics — the sync contract

With write-behind storage, the on-disk snapshot lags the in-memory state by at most one AUTOSAVE_INTERVAL. That is exactly the trade a filesystem makes — ext4 mounts with delayed allocation, and a power cut can roll the disk back to the last committed write. The same contract applies here:

  • Crash — the most recent actions are lost; Players.toml still holds the last synced state. On restart those entries are loaded and shown until their players reconnect under fresh connection IDs.
  • Graceful restart — the disconnect handlers removed the players from memory, and the next tick syncs that. Nothing extra to do.

Note what the sync buffer does not touch: Game.toml. It is static world data, so it never passes through the autosave task — only the live state does.

🧪 Testing the sync

Before testing, lower AUTOSAVE_INTERVAL to Duration::from_secs(5) so you don't wait a minute between writes:

  1. Run dx serve --open and join as Alice
  2. Move to another room, then immediately open Players.toml — Alice's room field still shows the old value (the write hasn't happened yet)
  3. Wait a few seconds (the tick), re-read the file — the room field now matches
  4. Refresh Alice's tab — the sidebar loads from the live in-memory state, unchanged
  5. Open Game.toml — still untouched, as always
  6. Kill the server (Ctrl+C) mid-session, restart it, and check what got loaded: whatever the last tick committed
Step 16 / 17