Creating a robust, scalable, and maintainable Wordle game using FastAPI, WebSockets, Event Sourcing, and adhering to Domain-Driven Design (DDD) principles requires careful architectural planning and clean code organization. Below is a comprehensive guide, complete with code examples, to help you build this application efficiently.
Table of Contents
- Project Structure
- Dependencies
- Configuration
- Domain Layer
- Application Layer
- Infrastructure Layer
- Interface Layer
- Background Tasks
- Putting It All Together
Project Structure
Following a layered architecture inspired by DDD, organize your project as follows:
wordle_app/
├── app/
│ ├── domain/
│ │ ├── entities.py
│ │ ├── events.py
│ │ └── value_objects.py
│ ├── application/
│ │ └── services.py
│ ├── infrastructure/
│ │ ├── repositories.py
│ │ ├── event_store.py
│ │ ├── auth.py
│ │ └── websocket_handler.py
│ ├── interfaces/
│ │ └── websocket_router.py
│ ├── config.py
│ └── main.py
├── tests/
│ └── ...
├── requirements.txt
└── README.md
Dependencies
Ensure you have the following dependencies in your requirements.txt:
fastapi
uvicorn
python-jose[cryptography]
sqlalchemy
asyncpg
pydantic
databases
redis
aioredis
APScheduler
Install them using:
pip install -r requirements.txt
Configuration
Create a configuration module to manage settings, such as the JWT secret, database URLs, etc.
# app/config.py
from pydantic import BaseSettings
class Settings(BaseSettings):
jwt_secret: str
database_url: str
event_store_url: str
word_list_table: str = "words"
game_event_table: str = "game_events"
secret_key: str
algorithm: str = "HS256"
class Config:
env_file = ".env"
settings = Settings()
Domain Layer
Entities
Represent the core business logic and entities. For Wordle, the primary entity is the Game.
# app/domain/entities.py
from typing import List
from uuid import UUID, uuid4
from .events import GameEvent
from .value_objects import Word
class Game:
def __init__(self, user_uuid: UUID, word: Word):
self.game_id = uuid4()
self.user_uuid = user_uuid
self.word = word
self.tries = []
self.max_attempts = word.length
self.is_complete = False
def add_attempt(self, attempt: Word):
if self.is_complete:
raise ValueError("Game already completed")
if len(self.tries) >= self.max_attempts:
raise ValueError("Maximum attempts reached")
self.tries.append(attempt)
# Emit events as needed
if attempt.value.lower() == self.word.value.lower():
self.is_complete = True
# Emit GameCompletedEvent
Value Objects
Encapsulate value-related logic, such as Word.
# app/domain/value_objects.py
from pydantic import BaseModel, validator
class Word(BaseModel):
value: str
@property
def length(self) -> int:
return len(self.value)
@validator('value')
def validate_word(cls, v):
if not v.isalpha():
raise ValueError('Word must contain only letters')
return v.lower()
Events
Define events for event sourcing. Each significant action in the domain emits an event.
# app/domain/events.py
from abc import ABC
from dataclasses import dataclass
from uuid import UUID
from datetime import datetime
class GameEvent(ABC):
game_id: UUID
timestamp: datetime
@dataclass
class GameStarted(GameEvent):
game_id: UUID
user_uuid: UUID
word_length: int
timestamp: datetime = datetime.utcnow()
@dataclass
class AttemptMade(GameEvent):
game_id: UUID
attempt: str
timestamp: datetime = datetime.utcnow()
@dataclass
class GameCompleted(GameEvent):
game_id: UUID
success: bool
timestamp: datetime = datetime.utcnow()
Application Layer
Services
Implement application-specific logic, orchestrating domain entities and events.
# app/application/services.py
from uuid import UUID
from typing import List
from app.domain.entities import Game
from app.domain.value_objects import Word
from app.domain.events import GameStarted, AttemptMade, GameCompleted
from app.infrastructure.repositories import WordRepository, GameRepository
from app.infrastructure.event_store import EventStore
class GameService:
def __init__(self, word_repo: WordRepository, game_repo: GameRepository, event_store: EventStore):
self.word_repo = word_repo
self.game_repo = game_repo
self.event_store = event_store
async def start_new_game(self, user_uuid: UUID) -> Game:
word = await self.word_repo.get_random_word()
game = Game(user_uuid=user_uuid, word=Word(value=word))
await self.game_repo.save(game)
event = GameStarted(game_id=game.game_id, user_uuid=user_uuid, word_length=game.word.length)
await self.event_store.store_event(event)
return game
async def make_attempt(self, game_id: UUID, attempt_str: str) -> Game:
game = await self.game_repo.get(game_id)
if not game:
raise ValueError("Game not found")
attempt = Word(value=attempt_str)
game.add_attempt(attempt)
await self.game_repo.save(game)
event = AttemptMade(game_id=game_id, attempt=attempt.value)
await self.event_store.store_event(event)
if game.is_complete:
completion_event = GameCompleted(game_id=game_id, success=(attempt_str.lower() == game.word.value.lower()))
await self.event_store.store_event(completion_event)
return game
Infrastructure Layer
Repositories
Interfaces to interact with the database.
# app/infrastructure/repositories.py
from abc import ABC, abstractmethod
from uuid import UUID
from typing import Optional
from app.domain.entities import Game
from app.config import settings
from databases import Database
class WordRepository(ABC):
@abstractmethod
async def get_random_word(self) -> str:
pass
class GameRepository(ABC):
@abstractmethod
async def save(self, game: Game) -> None:
pass
@abstractmethod
async def get(self, game_id: UUID) -> Optional[Game]:
pass
class SQLWordRepository(WordRepository):
def __init__(self, db: Database):
self.db = db
async def get_random_word(self) -> str:
query = f"SELECT word FROM {settings.word_list_table} ORDER BY RANDOM() LIMIT 1"
row = await self.db.fetch_one(query)
return row['word']
class SQLGameRepository(GameRepository):
def __init__(self, db: Database):
self.db = db
async def save(self, game: Game) -> None:
query = f"""
INSERT INTO games (game_id, user_uuid, word, tries, is_complete)
VALUES (:game_id, :user_uuid, :word, :tries, :is_complete)
ON CONFLICT (game_id) DO UPDATE
SET tries = :tries, is_complete = :is_complete
"""
await self.db.execute(query, values={
"game_id": str(game.game_id),
"user_uuid": str(game.user_uuid),
"word": game.word.value,
"tries": [attempt.value for attempt in game.tries],
"is_complete": game.is_complete
})
async def get(self, game_id: UUID) -> Optional[Game]:
query = f"SELECT * FROM games WHERE game_id = :game_id"
row = await self.db.fetch_one(query, values={"game_id": str(game_id)})
if row:
game = Game(user_uuid=UUID(row['user_uuid']), word=Word(value=row['word']))
game.game_id = UUID(row['game_id'])
game.tries = [Word(value=word) for word in row['tries']]
game.is_complete = row['is_complete']
return game
return None
Event Store
Store and retrieve events for event sourcing.
# app/infrastructure/event_store.py
from typing import List
from uuid import UUID
from app.domain.events import GameEvent
from abc import ABC, abstractmethod
from app.config import settings
from databases import Database
import json
class EventStore(ABC):
@abstractmethod
async def store_event(self, event: GameEvent) -> None:
pass
@abstractmethod
async def get_events(self, game_id: UUID) -> List[GameEvent]:
pass
class SQLAlchemyEventStore(EventStore):
def __init__(self, db: Database):
self.db = db
async def store_event(self, event: GameEvent) -> None:
query = f"""
INSERT INTO {settings.game_event_table} (game_id, event_type, event_data, timestamp)
VALUES (:game_id, :event_type, :event_data, :timestamp)
"""
await self.db.execute(query, values={
"game_id": str(event.game_id),
"event_type": event.__class__.__name__,
"event_data": json.dumps(event.__dict__),
"timestamp": event.timestamp
})
async def get_events(self, game_id: UUID) -> List[GameEvent]:
query = f"SELECT * FROM {settings.game_event_table} WHERE game_id = :game_id ORDER BY timestamp ASC"
rows = await self.db.fetch_all(query, values={"game_id": str(game_id)})
events = []
for row in rows:
event_type = row['event_type']
event_data = json.loads(row['event_data'])
if event_type == "GameStarted":
events.append(GameStarted(**event_data))
elif event_type == "AttemptMade":
events.append(AttemptMade(**event_data))
elif event_type == "GameCompleted":
events.append(GameCompleted(**event_data))
# Add more event types as needed
return events
Authentication
Handle JWT decoding and validation.
# app/infrastructure/auth.py
from fastapi import WebSocket, Depends, HTTPException
from jose import jwt, JWTError
from app.config import settings
from uuid import UUID
class User:
def __init__(self, user_uuid: UUID, user_name: str):
self.user_uuid = user_uuid
self.user_name = user_name
async def get_current_user(token: str) -> User:
try:
payload = jwt.decode(token, settings.jwt_secret, algorithms=[settings.algorithm])
user_uuid = UUID(payload.get("user_uuid"))
user_name = payload.get("user_name")
if user_uuid and user_name:
return User(user_uuid=user_uuid, user_name=user_name)
else:
raise HTTPException(status_code=401, detail="Invalid token payload")
except JWTError:
raise HTTPException(status_code=401, detail="Invalid JWT token")
def websocket_auth_dependency(websocket: WebSocket):
token = websocket.query_params.get("token")
if not token:
raise HTTPException(status_code=401, detail="Missing token")
return get_current_user(token)
WebSocket Handler
Manage WebSocket connections, ensuring authentication and handling game logic.
# app/infrastructure/websocket_handler.py
from fastapi import WebSocket
from app.application.services import GameService
from app.domain.value_objects import Word
from uuid import UUID
import json
class WebSocketHandler:
def __init__(self, game_service: GameService):
self.game_service = game_service
self.active_connections = {}
async def connect(self, websocket: WebSocket, user):
await websocket.accept()
self.active_connections[user.user_uuid] = websocket
# Optionally start a new game or send current game state
async def disconnect(self, websocket: WebSocket, user):
self.active_connections.pop(user.user_uuid, None)
async def receive(self, websocket: WebSocket, data: str, user):
message = json.loads(data)
action = message.get("action")
if action == "start_game":
game = await self.game_service.start_new_game(user.user_uuid)
await websocket.send_json({
"event": "game_started",
"game_id": str(game.game_id),
"word_length": game.word.length
})
elif action == "make_attempt":
game_id = UUID(message.get("game_id"))
attempt = message.get("attempt")
game = await self.game_service.make_attempt(game_id, attempt)
response = {
"event": "attempt_made",
"game_id": str(game.game_id),
"attempt": attempt,
"tries": [a.value for a in game.tries],
"is_complete": game.is_complete
}
await websocket.send_json(response)
else:
await websocket.send_json({"error": "Unknown action"})
Interface Layer
WebSocket Router
Define WebSocket routes and integrate with FastAPI.
# app/interfaces/websocket_router.py
from fastapi import APIRouter, WebSocket, WebSocketDisconnect, Depends
from app.infrastructure.auth import websocket_auth_dependency, get_current_user
from app.infrastructure.websocket_handler import WebSocketHandler
from app.application.services import GameService
from app.infrastructure.repositories import SQLWordRepository, SQLGameRepository
from app.infrastructure.event_store import SQLAlchemyEventStore
from app.config import settings
from databases import Database
router = APIRouter()
# Initialize Database
database = Database(settings.database_url)
# Initialize Repositories and Services
word_repo = SQLWordRepository(database)
game_repo = SQLGameRepository(database)
event_store = SQLAlchemyEventStore(database)
game_service = GameService(word_repo, game_repo, event_store)
ws_handler = WebSocketHandler(game_service)
@router.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket, user = Depends(websocket_auth_dependency)):
await ws_handler.connect(websocket, user)
try:
while True:
data = await websocket.receive_text()
await ws_handler.receive(websocket, data, user)
except WebSocketDisconnect:
await ws_handler.disconnect(websocket, user)
Background Tasks
Use APScheduler to schedule the creation of a new game every 24 hours and reset sessions.
# app/background_tasks.py
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from app.application.services import GameService
from app.infrastructure.repositories import WordRepository, GameRepository
from app.infrastructure.event_store import EventStore
from uuid import UUID
class BackgroundTaskManager:
def __init__(self, game_service: GameService):
self.scheduler = AsyncIOScheduler()
self.game_service = game_service
def start(self):
self.scheduler.add_job(self.create_new_daily_game, 'interval', hours=24, next_run_time=None)
self.scheduler.start()
async def create_new_daily_game(self):
# Logic to create a new game, e.g., select a new word and notify all users
pass
Putting It All Together
Finally, set up the FastAPI application, including startup and shutdown events.
# app/main.py
from fastapi import FastAPI
from app.interfaces.websocket_router import router as websocket_router
from app.background_tasks import BackgroundTaskManager
from app.application.services import GameService
from app.infrastructure.repositories import SQLWordRepository, SQLGameRepository
from app.infrastructure.event_store import SQLAlchemyEventStore
from app.config import settings
from databases import Database
app = FastAPI()
app.include_router(websocket_router)
# Initialize Database
database = Database(settings.database_url)
# Initialize Repositories and Services
word_repo = SQLWordRepository(database)
game_repo = SQLGameRepository(database)
event_store = SQLAlchemyEventStore(database)
game_service = GameService(word_repo, game_repo, event_store)
# Initialize Background Tasks
background_tasks = BackgroundTaskManager(game_service)
@app.on_event("startup")
async def startup():
await database.connect()
background_tasks.start()
# Optionally load initial game state
@app.on_event("shutdown")
async def shutdown():
await database.disconnect()
background_tasks.scheduler.shutdown()
Best Practices and Considerations
-
Layered Architecture: Separating concerns across Domain, Application, Infrastructure, and Interface layers ensures maintainability and scalability.
-
Dependency Injection: Inject dependencies like repositories and services to promote loose coupling and facilitate testing.
-
Event Sourcing: Storing events instead of just the current state allows for a complete history of actions, which is valuable for auditing and debugging.
-
Security: JWT is used for authenticating WebSocket connections, ensuring that only authorized users can participate.
-
Scalability: Using asynchronous components (async/await) and efficient libraries like databases and asyncpg ensures high performance.
-
Resilience: Proper error handling, validation, and use of robust libraries contribute to the application's reliability.
-
Testing: Although not included here, write comprehensive unit and integration tests to ensure each component behaves as expected.
-
Configuration Management: Utilize environment variables and a centralized configuration module to manage sensitive information and settings securely.
-
Documentation: Maintain clear documentation for each module and function to facilitate future development and onboarding.
-
Scheduling and State Management: Ensure that background tasks like daily game resets are managed correctly without affecting active user sessions.
By adhering to these principles and the provided structure, you can build a FastAPI-based Wordle game that is clean, efficient, and ready for production environments akin to high-standard applications like those from Google or Netflix.