← All Workshops

MudEngine Part 8: Inventory & Chat

Step 6 / 14

Split Actions into Separate Server Files

The WebSocket handler gets three new message types to handle: Say, Take, and Drop. Each follows the same pattern: validate, mutate the in-memory state, then broadcast the result — no disk writes (the autosave task owns persistence now).

Rather than growing the endpoint into one giant match block, we turn the server into a server/ directory module with one file per action. The Move handler moves into its own file too, so mud_ws becomes a thin dispatcher.

New file layout

src/game/server/mod.rs    ← statics (GAME_STATE / AUTOSAVE / BROADCAST) + mud_ws endpoint
src/game/server/move.rs   ← Move handler
src/game/server/say.rs    ← Say handler
src/game/server/take.rs   ← Take handler
src/game/server/drop.rs   ← Drop handler

Delete the old src/game/server.rs (a single file with an inner mod srv) and replace it with the server/ directory. The statics that lived inside mod srv move up into server/mod.rs, and each action lives in its own file. Every handler acquires the GAME_STATE lock itself, validates, mutates, then broadcasts its result — the endpoint only routes each ClientMessage to the right handler.

Also update the initial State message to fill RoomInfo.items from the live ground, and make PlayerMoved carry the player's real inventory so the roster stays accurate.

mud-engine/src/game/server/mod.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;

// ── Action handlers — one file per action ──
#[cfg(feature = "server")]
mod move_handler;
#[cfg(feature = "server")]
mod say_handler;
#[cfg(feature = "server")]
mod take_handler;
#[cfg(feature = "server")]
mod drop_handler;

// ── Server-only state ──

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

/// 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.
#[cfg(feature = "server")]
const AUTOSAVE_INTERVAL: Duration = Duration::from_secs(60);

/// The authoritative game state — rooms, connected players, item positions.
/// The world comes from Game.toml (static); players and ground from Players.toml (live).
#[cfg(feature = "server")]
pub static GAME_STATE: LazyLock<Mutex<GameState>> = LazyLock::new(|| {
    // Start the background autosave task before any player connects.
    let _ = LazyLock::force(&AUTOSAVE);

    // Live state from the last session (players + inventories + ground overrides)
    let live = persistence::load_players("Players.toml");

    // Seed the ground from the static item layout, then apply live changes
    let mut ground = persistence::seed_ground("Game.toml");
    for (room, items) in live.ground {
        ground.insert(room, items);
    }

    Mutex::new(GameState {
        rooms: persistence::load_world("Game.toml"),
        players: live.players,
        ground,
    })
});

/// 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.
#[cfg(feature = "server")]
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.
#[cfg(feature = "server")]
pub static BROADCAST: LazyLock<broadcast::Sender<ServerMessage>> = LazyLock::new(|| {
    let (tx, _) = broadcast::channel(64);
    tx
});
💡 From `mod srv` to a directory module

In Part 7 the server lived in a single server.rs file whose statics were wrapped in an inner mod srv { ... }. Splitting a Rust module into multiple files uses a directory module: replace server.rs with a server/ folder holding a mod.rs plus one file per sub-module.

  • pub mod server; in src/game.rs auto-resolves to src/game/server/mod.rs (once server.rs is deleted).
  • The old inner mod srv is dissolved: its statics (GAME_STATE, AUTOSAVE, BROADCAST) now sit at the top of server/mod.rs, each behind #[cfg(feature = "server")].
  • Each action is its own module — mod move_handler;, mod say_handler;, mod take_handler;, mod drop_handler; — declared in mod.rs and implemented in the matching file. They are #[cfg(feature = "server")] too, because they touch server-only state; the client build never compiles them.
  • Handlers reach the statics through super::{GAME_STATE, BROADCAST} and the shared types through crate::game::{messages, persistence}.
mud-engine/src/game/server/mod.rs
// ── WebSocket endpoint ──

#[get("/api/mud_ws?name")]
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 = GAME_STATE.lock().unwrap();
        state.players.insert(
            id.clone(),
            PlayerInfo {
                id: id.clone(),
                name: name.clone(),
                room: 4,
                items: Vec::new(),
            },
        );

        // Rooms are already RoomInfo; override the live `items` from `ground`.
        room_infos = state
            .rooms
            .iter()
            .map(|r| {
                let mut room = r.clone();
                room.items = state.ground.get(&r.id).cloned().unwrap_or_default();
                room
            })
            .collect();
    }

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

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

    // 4. Build the initial state snapshot for this new player
    let initial_state = {
        let state = 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 — each ClientMessage defers to its own handler file ──
        loop {
            tokio::select! {
                msg = socket.recv() => {
                    match msg {
                        Ok(ClientMessage::Move { direction }) => {
                            move_handler::run(id.clone(), player_name.clone(), direction);
                        }
                        Ok(ClientMessage::Say { message }) => {
                            say_handler::run(id.clone(), player_name.clone(), message);
                        }
                        Ok(ClientMessage::Take { item }) => {
                            take_handler::run(id.clone(), player_name.clone(), item);
                        }
                        Ok(ClientMessage::Drop { item }) => {
                            drop_handler::run(id.clone(), player_name.clone(), item);
                        }
                        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 = GAME_STATE.lock().unwrap();

            // Drop all carried items into the player's current room
            if let Some(player) = state.players.get(&id) {
                let room_id = player.room;
                let ground = state.ground.entry(room_id).or_default();
                for item in &player.items {
                    if !ground.contains(item) {
                        ground.push(item.clone());
                    }
                }
            }

            state.players.remove(&id);
        }
        let _ = BROADCAST.send(ServerMessage::PlayerLeft { id });
    });

    Ok(ws)
}
mud-engine/src/game/server/move.rs
use super::{BROADCAST, GAME_STATE};
use crate::game::messages::{PlayerInfo, ServerMessage};
use crate::game::persistence;

/// Handle a player move request: validate the exit, update the player's room,
/// and broadcast a `PlayerMoved` (with the real inventory) if the move succeeded.
pub fn run(player_id: String, player_name: String, direction: String) {
    let dir = match direction.as_str() {
        "n" => "north",
        "s" => "south",
        "e" => "east",
        "w" => "west",
        d => d,
    };

    let (new_room, items) = {
        let mut state = GAME_STATE.lock().unwrap();
        let current = state.players.get(&player_id).unwrap().room;
        let next = persistence::can_move(&state, current, dir);
        if let Some(next) = next {
            state.players.get_mut(&player_id).unwrap().room = next;
        }
        let items = state
            .players
            .get(&player_id)
            .map(|p| p.items.clone())
            .unwrap_or_default();
        (next, items)
    };

    if let Some(room) = new_room {
        let _ = BROADCAST.send(ServerMessage::PlayerMoved(PlayerInfo {
            id: player_id,
            name: player_name,
            room,
            items,
        }));
    }
}
mud-engine/src/game/server/say.rs
use super::{BROADCAST, GAME_STATE};
use crate::game::messages::ServerMessage;

/// Handle a chat message: read the player's current room and broadcast it to
/// everyone. Each client filters by `room`, so only nearby players display it.
pub fn run(player_id: String, player_name: String, message: String) {
    let current_room = {
        let state = GAME_STATE.lock().unwrap();
        state.players.get(&player_id).map(|p| p.room).unwrap_or(4)
    };

    let _ = BROADCAST.send(ServerMessage::Chat {
        from: player_name,
        message,
        room: current_room,
    });
}
mud-engine/src/game/server/take.rs
use super::{BROADCAST, GAME_STATE};
use crate::game::messages::ServerMessage;

/// Handle a take request: validate the item is on the floor of the player's
/// current room, move it into their inventory, and broadcast `ItemTaken` if it
/// succeeded.
pub fn run(player_id: String, player_name: String, item: String) {
    let mut success = false;
    {
        let mut state = GAME_STATE.lock().unwrap();
        let room_id = state.players.get(&player_id).unwrap().room;

        if let Some(items) = state.ground.get_mut(&room_id) {
            if let Some(pos) = items.iter().position(|i| i == &item) {
                items.remove(pos);
                state.players
                    .get_mut(&player_id)
                    .unwrap()
                    .items
                    .push(item.clone());
                success = true;
            }
        }
    }

    if success {
        let _ = BROADCAST.send(ServerMessage::ItemTaken {
            player_id,
            player_name,
            item,
        });
    }
}
mud-engine/src/game/server/drop.rs
use super::{BROADCAST, GAME_STATE};
use crate::game::messages::ServerMessage;

/// Handle a drop request: validate the player is carrying the item, move it onto
/// the floor of their current room, and broadcast `ItemDropped` if it succeeded.
pub fn run(player_id: String, player_name: String, item: String) {
    let mut success = false;
    let dropped_room = {
        let mut state = GAME_STATE.lock().unwrap();
        let room_id = state.players.get(&player_id).unwrap().room;

        if let Some(pos) = state
            .players
            .get_mut(&player_id)
            .unwrap()
            .items
            .iter()
            .position(|i| i == &item)
        {
            state.players.get_mut(&player_id).unwrap().items.remove(pos);
            state.ground.entry(room_id).or_default().push(item.clone());
            success = true;
        }
        room_id
    };

    if success {
        let _ = BROADCAST.send(ServerMessage::ItemDropped {
            player_id,
            player_name,
            item,
            room: dropped_room,
        });
    }
}
🎯 Why validate inside the lock

Every handler — Move, Say, Take, and Drop — acquires its own GAME_STATE.lock() scope to perform its validation and mutation. This is critical:

  1. Atomicity — no other WebSocket handler can interleave between "check item exists" and "move item". This prevents race conditions where two players try to take the same item simultaneously.
  2. Isolation from disk — the handlers never write a file themselves. Persistence belongs to the autosave task from Part 7, so disk I/O stays out of the critical section entirely.
  3. Simplicity — no need for optimistic locking or retry logic. The Mutex guarantees sequential access.

Splitting each action into its own file keeps this pattern identical for all four: acquire the lock, validate, mutate, drop the lock, then broadcast. When a broadcast is sent after the lock is released, concurrent handlers can't deadlock on each other.

PlayerMoved carries the player's real items vector, so the roster always stays accurate even if a player moves in the middle of a pickup or drop.

Step 6 / 14