← All Workshops

MudEngine Part 11: Peer-to-Peer with iroh

Step 4 / 14

Delete the server and free the game logic

The Axum handlers live in src/game/server/ (mod.rs, move_handler.rs, say_handler.rs, take_handler.rs, drop_handler.rs, quest.rs), and most of the runtime game code in game/persistence.rs — GameState, QuestStatus, load_world, load_players, write_players, can_move — is gated behind #[cfg(feature = "server")]. Neither can survive: there is no server feature anymore, and the host's own binary must own the engine directly.

Delete the whole directory first:

rm -rf src/game/server

Now the game headers. src/game.rs drops the server module and announces the new shape — note the relay module only exists on wasm:

  • engine — the transport-agnostic game engine (new)
  • net — the iroh P2P layer (new)
  • relay — the browser half of the mesh bridge (wasm-only stub, step 2)
  • persistence, messages, random_name — as before
mud-engine/src/game.rs
pub mod engine;
pub mod messages;
pub mod net;
pub mod persistence;
pub mod random_name;
#[cfg(target_arch = "wasm32")]
pub mod relay;
🔍 Why relay on wasm only

Browsers cannot open UDP sockets, so QUIC is impossible inside a tab. The wasm build therefore talks to the host's gossip topic over a WebSocket relay instead — but only the browser side of that bridge lives in relay.rs. The relay server half is what the host would run; that is step 2 of this part. The desktop mesh itself never touches the relay.

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,
}

/// The single room type: Game.toml seed, runtime room, and wire payload.
/// `items` is the static item layout from Game.toml; the live positions live in
/// `GameState.ground` and override it when the State message is built.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct RoomInfo {
    pub id: usize,
    pub name: String,
    pub description: String,
    pub exits: Vec<Exit>,
    pub items: Vec<String>,
}

/// The single player type: Players.toml, runtime map, and wire message.
/// `items` is the player's carried inventory.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
pub struct PlayerInfo {
    pub id: String,
    pub name: String,
    pub room: usize,
    pub items: Vec<String>,
}

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

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

/// One live ground override: a room and the items currently lying there.
/// This is the file shape for `[[room_items]]` in Players.toml — the only
/// genuine conversion left, because TOML stores arrays of tables while the
/// runtime keeps a `HashMap<usize, Vec<String>>`.
#[derive(Serialize, Deserialize)]
struct TomlRoomItems {
    room: usize,
    items: Vec<String>,
}

#[derive(Serialize, Deserialize)]
struct TomlPlayers {
    #[serde(default)]
    players: Vec<PlayerInfo>,
    #[serde(default)]
    room_items: Vec<TomlRoomItems>,
    /// Live quest bit: whether the quest is complete.
    #[serde(default)]
    quest_completed: Option<bool>,
}

// ── Quest config (mirrors the `[quest]` section in Game.toml) ──

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TomlQuestGuardian {
    pub name: String,
    pub room_id: usize,
    pub label: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TomlQuestReward {
    pub source_room_id: usize,
    pub target_room_id: usize,
    pub direction: String,
    pub target_name: String,
    pub target_description: String,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TomlQuest {
    pub name: String,
    pub retrieval_item: String,
    pub completion_room: usize,
    pub guardians: Vec<TomlQuestGuardian>,
    pub reward: TomlQuestReward,
}

/// Runtime quest state — tracked live on the server.
/// Only the `completed` flag is persisted (to Players.toml via the autosave task).
pub struct QuestStatus {
    pub config: TomlQuest,
    /// Whether the portal gate is open right now — session-only, never persisted.
    pub previously_active: bool,
    /// Whether the Star Fragment reached the King. Persisted.
    pub completed: bool,
}

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

pub struct GameState {
    pub rooms: Vec<RoomInfo>,
    pub players: HashMap<String, PlayerInfo>,
    /// Live item positions: which items currently lie on the floor of each room.
    /// Seeded from Game.toml, then flushes to Players.toml via the autosave task.
    pub ground: HashMap<usize, Vec<String>>,
    /// The active quest, if Game.toml has a `[quest]` section.
    pub quest: Option<QuestStatus>,
}

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

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
}

/// Read Game.toml and build the initial item layout: room_id → items lying there.
pub fn seed_ground(path: &str) -> HashMap<usize, Vec<String>> {
    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
        .into_iter()
        .map(|r| (r.id, r.items))
        .collect()
}

/// Read the static `[quest]` section from Game.toml, if present.
pub fn load_quest(path: &str) -> Option<TomlQuest> {
    let toml_game: TomlQuestConfig = toml::from_str(
        &std::fs::read_to_string(path).unwrap_or_else(|e| panic!("Failed to read {}: {}", path, e)),
    )
    .unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e));
    toml_game.quest
}

#[derive(Deserialize)]
struct TomlQuestConfig {
    #[serde(default)]
    quest: Option<TomlQuest>,
}

/// What load_players returns: the live players, ground overrides, and quest flag.
pub struct LiveState {
    pub players: HashMap<String, PlayerInfo>,
    /// rooms whose ground has diverged from the Game.toml seed
    pub ground: HashMap<usize, Vec<String>>,
    /// persisted quest completion flag (None when never set)
    pub quest_completed: Option<bool>,
}

pub fn load_players(path: &str) -> LiveState {
    let Ok(content) = std::fs::read_to_string(path) else {
        return LiveState {
            players: HashMap::new(),
            ground: HashMap::new(),
            quest_completed: None,
        };
    };
    let toml_players: TomlPlayers =
        toml::from_str(&content).unwrap_or_else(|e| panic!("Failed to parse {}: {}", path, e));

    let players = toml_players
        .players
        .into_iter()
        .map(|p| (p.id.clone(), p))
        .collect();

    let ground = toml_players
        .room_items
        .into_iter()
        .map(|ri| (ri.room, ri.items))
        .collect();

    LiveState {
        players,
        ground,
        quest_completed: toml_players.quest_completed,
    }
}

/// Serialize the live state into the TOML that goes into Players.toml.
/// Fast (a few strings), so it is safe to run 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(),
        room_items: state
            .ground
            .iter()
            .map(|(room, items)| TomlRoomItems {
                room: *room,
                items: items.clone(),
            })
            .collect(),
        quest_completed: state.quest.as_ref().map(|q| q.completed),
    };
    toml::to_string_pretty(&toml_players).unwrap()
}

/// 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();
}

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)
        })
}
🔍 What changed in persistence

Every #[cfg(feature = "server")] attribute is gone. The shared models (RoomInfo, PlayerInfo, Exit), the TOML wrappers, the quest config, and the load/snapshot functions all compile for every target now.

Note GameState keeps a live ground: HashMap<usize, Vec<String>> ("which items lie on the floor right now") separate from the static RoomInfo.items seed — the engine seeds ground from Game.toml, then applies the persisted overrides from Players.toml. snapshot() + write_players() are what the engine's autosave task flushes every 60 seconds.

Step 4 / 14