Skip to content

senzenn/axum-server-client

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

2 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Axum Server & Client Testing Setup with tmux

A complete Rust-based HTTP server and client setup for local testing using Axum framework and tmux sessions.

πŸ—οΈ Project Architecture

This project demonstrates a classic client-server architecture where:

  • Server: A REST API built with Axum that handles HTTP requests
  • Client: A command-line application that sends HTTP requests to the server
  • Communication: HTTP/JSON over TCP on localhost
  • Isolation: Both run in separate tmux sessions for independent monitoring

Real-World Analogy 🌍

Think of this setup like a restaurant system:

  • Server = Kitchen πŸ‘¨β€πŸ³

    • Receives orders (HTTP requests)
    • Processes them (business logic)
    • Sends back food (HTTP responses)
    • Keeps track of all orders (in-memory storage)
  • Client = Customer/Waiter πŸ‘€

    • Places orders (sends HTTP requests)
    • Receives responses (gets the food)
    • Can check what's available (health check)
    • Can see order history (get messages)
  • tmux Sessions = Separate dining rooms 🏒

    • Kitchen operates independently in one room
    • Customer area in another room
    • You can peek into either room anytime
    • Both can work simultaneously

πŸ“ Project Structure

axum-test/
β”œβ”€β”€ Cargo.toml                 # Project dependencies
β”œβ”€β”€ README.md                  # This file
β”œβ”€β”€ setup-tmux.sh             # Automated setup script
└── src/
    β”œβ”€β”€ main.rs               # Default main (unused)
    └── bin/
        β”œβ”€β”€ server.rs         # HTTP server implementation
        └── client.rs         # HTTP client implementation

πŸ”§ Dependencies

[dependencies]
axum = "0.7"                  # Web framework
tokio = { version = "1.0", features = ["full"] }  # Async runtime
serde = { version = "1.0", features = ["derive"] } # Serialization
serde_json = "1.0"           # JSON support
reqwest = { version = "0.11", features = ["json"] } # HTTP client

πŸ–₯️ Server Implementation

Core Components

1. Data Structures

Message {
    id: u32,           // Unique identifier
    content: String,   // Message text
    timestamp: String, // Unix timestamp
}

2. Thread-Safe Storage

  • Uses OnceLock<Arc<Mutex<AppState>>> for thread-safe global state
  • Why this approach?
    • OnceLock: Initialize once, use everywhere
    • Arc: Shared ownership across threads
    • Mutex: Mutual exclusion for safe mutations
    • Alternative: In production, use databases like PostgreSQL/MongoDB

3. HTTP Endpoints

Method Endpoint Purpose Example Response
GET / Server status "πŸ¦€ Axum Server is running!"
GET /health Health check {"status": "healthy", "timestamp": 1234567890}
GET /messages List all messages [{"id": 1, "content": "Hello", "timestamp": "1234567890"}]
GET /messages?limit=5 List limited messages Same as above, but max 5 items
POST /messages Create new message {"id": 2, "content": "New message", "timestamp": "1234567891"}

4. Error Handling

  • Returns appropriate HTTP status codes
  • Validates input (empty messages rejected with 400 Bad Request)
  • Thread-safe operations with proper error propagation

πŸ’» Client Implementation

Interactive Menu System

The client provides a simple CLI interface:

πŸ”§ Axum Test Client
Server: http://127.0.0.1:9090
Commands:
  1 - Health check      (GET /health)
  2 - Get all messages  (GET /messages)
  3 - Create new message (POST /messages)
  q - Quit

Client Features

  • HTTP Client: Uses reqwest for making HTTP requests
  • JSON Handling: Automatic serialization/deserialization
  • Error Handling: Displays user-friendly error messages
  • Interactive: Real-time communication with server

πŸš€ Getting Started

Prerequisites

  • Rust 1.70+ installed
  • tmux installed (brew install tmux on macOS)

Quick Setup

  1. Clone and setup project:
cargo new axum-test --bin
cd axum-test
# Copy the provided Cargo.toml and source files
  1. Automated setup with tmux:
chmod +x setup-tmux.sh
./setup-tmux.sh
  1. Manual setup:
# Terminal 1: Start server
cargo run --bin server

# Terminal 2: Start client
cargo run --bin client

Using tmux Sessions

Starting Sessions

# Create server session
tmux new-session -d -s axum-server -c "$(pwd)" "cargo run --bin server"

# Create client session
tmux new-session -d -s axum-client -c "$(pwd)" "cargo run --bin client"

Managing Sessions

# List all sessions
tmux list-sessions

# Attach to server session (see server logs)
tmux attach-session -t axum-server

# Attach to client session (interact with API)
tmux attach-session -t axum-client

# Detach from current session
Ctrl+b, then d

# Kill sessions
tmux kill-session -t axum-server
tmux kill-session -t axum-client

πŸ§ͺ Testing Scenarios

Basic Workflow

  1. Start server β†’ See startup logs
  2. Start client β†’ Connect to server
  3. Health check β†’ Verify server is responding
  4. Create messages β†’ Add some test data
  5. Retrieve messages β†’ Verify data persistence
  6. Monitor server logs β†’ See request processing

Example Test Session

> 1                           # Health check
βœ… Server is healthy

> 3                           # Create message
Enter message content: Hello, World!
βœ… Created message: [1] Hello, World!

> 3                           # Create another
Enter message content: Testing API
βœ… Created message: [2] Testing API

> 2                           # Get all messages
πŸ“¬ Found 2 messages:
  [1] Hello, World! (1734567890)
  [2] Testing API (1734567891)

🎯 What This Setup Can Do

βœ… Capabilities

Server Side

  • βœ… Handle multiple concurrent HTTP requests
  • βœ… Store data in memory (thread-safe)
  • βœ… Provide RESTful API endpoints
  • βœ… Return JSON responses
  • βœ… Validate input data
  • βœ… Generate unique IDs automatically
  • βœ… Timestamp messages
  • βœ… Handle query parameters (?limit=N)
  • βœ… Provide health monitoring
  • βœ… Log all operations to console

Client Side

  • βœ… Make HTTP GET/POST requests
  • βœ… Handle JSON serialization/deserialization
  • βœ… Interactive command-line interface
  • βœ… Display formatted responses
  • βœ… Handle network errors gracefully
  • βœ… Real-time communication with server

Development Features

  • βœ… Hot reloading (restart to see code changes)
  • βœ… Separate monitoring of server and client
  • βœ… Real-time log viewing
  • βœ… Easy session management with tmux
  • βœ… Local development environment
  • βœ… No external dependencies (runs offline)

Learning Opportunities

  • βœ… HTTP protocol understanding
  • βœ… REST API design patterns
  • βœ… Async programming in Rust
  • βœ… Thread-safe programming
  • βœ… JSON handling
  • βœ… Error handling patterns
  • βœ… Client-server architecture

🚫 What This Setup Cannot Do

❌ Limitations

Production Readiness

  • ❌ No persistent storage - Data lost on server restart
  • ❌ No authentication/authorization - Anyone can access
  • ❌ No HTTPS/TLS - Communication not encrypted
  • ❌ No rate limiting - Vulnerable to spam/DoS
  • ❌ No input sanitization - Basic validation only
  • ❌ No logging framework - Just println! statements
  • ❌ No configuration management - Hardcoded values
  • ❌ No environment separation - Only works locally

Scalability Issues

  • ❌ Single server instance - No load balancing
  • ❌ Memory-only storage - Limited by RAM
  • ❌ No database - Can't handle large datasets
  • ❌ No caching - Every request hits main storage
  • ❌ No connection pooling - Basic HTTP handling
  • ❌ No horizontal scaling - Can't distribute load

Operational Limitations

  • ❌ No health monitoring - Basic health endpoint only
  • ❌ No metrics collection - No performance data
  • ❌ No graceful shutdown - Abrupt termination
  • ❌ No backup/recovery - Data loss on crash
  • ❌ No monitoring/alerting - No operational visibility
  • ❌ No deployment automation - Manual setup only

Protocol Limitations

  • ❌ HTTP only - No WebSocket support
  • ❌ No GraphQL - REST API only
  • ❌ No file uploads - Text messages only
  • ❌ No streaming - Request/response only
  • ❌ No real-time updates - Polling required
  • ❌ No compression - Raw JSON responses

Security Concerns

  • ❌ No input validation - Basic checks only
  • ❌ No SQL injection protection - Not applicable (no DB)
  • ❌ No CORS handling - Browser limitations
  • ❌ No request size limits - Memory exhaustion possible
  • ❌ No timeout handling - Long requests can hang
  • ❌ No audit logging - No security trail

πŸ“š Learning Extensions

Next Steps for Production

  1. Database Integration

    // Add to Cargo.toml
    sqlx = { version = "0.7", features = ["runtime-tokio-rustls", "postgres"] }
  2. Authentication

    // Add JWT or session-based auth
    jsonwebtoken = "8.3"
  3. Configuration

    // Environment-based config
    serde_env = "0.1"
  4. Logging

    // Structured logging
    tracing = "0.1"
    tracing-subscriber = "0.3"

Advanced Topics to Explore

  • Docker containerization
  • Kubernetes deployment
  • CI/CD pipelines
  • API documentation with OpenAPI
  • Integration testing
  • Performance benchmarking
  • Microservices architecture

πŸ” Troubleshooting

Common Issues

Server Won't Start

# Check if port is in use
lsof -i :9090

# Kill existing process
kill -9 <PID>

Client Can't Connect

# Verify server is running
curl http://127.0.0.1:9090/health

# Check firewall settings
# Ensure both client and server use same port

tmux Issues

# List all sessions
tmux list-sessions

# Kill all sessions
tmux kill-server

# Restart tmux
tmux new-session

Compilation Errors

# Clean build
cargo clean
cargo build

# Update dependencies
cargo update

πŸ“– Educational Value

This project serves as an excellent introduction to:

  1. Web Development: Understanding HTTP protocols, REST APIs, and client-server communication
  2. Rust Programming: Async programming, ownership, threading, and error handling
  3. DevOps Practices: Process management with tmux, local development setup
  4. API Design: RESTful endpoints, JSON serialization, status codes
  5. Testing Strategies: Manual testing, client simulation, integration testing

🀝 Contributing

Feel free to extend this project with:

  • Database integration
  • Authentication mechanisms
  • More endpoints
  • Better error handling
  • Configuration management
  • Docker containerization
  • Integration tests

πŸ“ License

This project is for educational purposes. Feel free to use and modify as needed.


Happy Coding! πŸ¦€

axum-server-client

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published