Update README.md

This commit is contained in:
2025-12-01 08:27:57 +00:00
parent e9eb37f665
commit 7983be56e4

432
README.md
View File

@@ -1,300 +1,272 @@
# ✅ Project Status Report
# tic-tac-toe — Authoritative Multiplayer Game Server (Nakama + Go)
## Multiplayer Tic-Tac-Toe Platform
**To:** CTO & Technical Interview Panel
**Date:** November 29, 2025
**Version:** v1.0.0
A production-grade, server-authoritative multiplayer backend built using **Nakama 3**, **Go plugins**, and **PostgreSQL**, deployed via **Drone CI/CD** and exposed securely through **Traefik**.
---
## **1. Objective**
## 🚀 Overview
Design and implement a scalable, server-authoritative multiplayer game system using **Nakama + custom Go plugins**, featuring:
This repository contains a fully authoritative Tic-Tac-Toe backend built on **Nakama 3.21.0 ARM**, using a custom **Go plugin** to implement game logic, matchmaking, validation, leaderboards, and session management.
* Authentication
* Matchmaking
* Authoritative gameplay
* Leaderboards
* A production-ready UI
* Fully automated CI/CD and Docker deployment pipeline
The server ensures:
The system is now deployable on **any ARM or x86 infrastructure, including Google Cloud**.
* **Zero client trust**
* **Deterministic gameplay**
* **Secure matchmaking**
* **Validated moves**
* **Authoritative outcomes**
Designed for scalability, extensibility, and cloud deployment (GCP, AWS, or ARM homelab environments).
---
## **2. Current Completion Summary**
## ⭐ Key Features
| Requirement | Status |
| -------------------------------------------- | ------------------------ |
| Install Nakama + PostgreSQL | ✅ Completed |
| Custom Go server plugins (ARM compatible) | ✅ Completed |
| Server-authoritative Tic-Tac-Toe | ✅ Completed |
| Real-time WebSocket communication | ✅ Completed |
| Device-based authentication | ✅ Completed |
| JWT-based session management | ✅ Completed |
| Match creation & joining | ✅ Completed |
| **Matchmaking queue support** | ✅ Completed |
| **Game state validation & turn enforcement** | ✅ Completed |
| **Leaderboard system** | ✅ Completed |
| **UI Game Client (production build)** | ✅ Completed |
| Google Cloud deployment | 🟡 Pending |
| **Drone CI/CD build & deploy pipeline** | ✅ Completed |
Backend is **fully authoritative** and stable. UI is **production-ready** but needs polish and error recovery improvements.
* **Authoritative Go match handler** (`tictactoe`)
* Device-ID authentication + JWT session
* Matchmaking queue support
* Deterministic game validation
* Match lifecycle handling
* Disconnect handling & forfeit detection
* Leaderboards creation + scoring
* Production-grade CI/CD with Drone
* Automated ARM Docker builds
* Full Traefik routing (HTTP + WebSocket)
* Compatible with x86/ARM/GCP
---
## **3. Core Technical Architecture**
## 🧩 Architecture
* **Backend:** Nakama 3.21.0 (ARM build)
* **Runtime Logic:** Go plugin (built with Go 1.21.6 for ABI compatibility)
* **Frontend:** React + Vite + Nakama JS
* **Database:** PostgreSQL 16
* **Networking:** WebSockets (secure / insecure configurable)
* **Authentication:** Device-ID auth → JWT session
* **Deployment:** Docker images with Drone CI/CD
* **Production UI Deployment:** BusyBox static server
### High-Level System Diagram
```mermaid
flowchart LR
UI[Frontend (React + Vite)] -->|WebSocket / REST| Traefik
Traefik --> Nakama[Nakama 3.21.0 ARM]
Nakama --> Plugin[Go Plugin main.so]
Nakama --> Postgres[(PostgreSQL)]
DroneCI --> Registry[Private Docker Registry]
Registry --> Nakama
```
---
## **4. Authentication**
## 🛠 Tech Stack
### Backend
**Backend**
* Device authentication
* Automatic account creation
* JWT session handling
* Nakama 3.21.0 ARM
* Go 1.21.6 (plugin ABI compatible)
* PostgreSQL 16
* Docker / multi-stage builds
* Drone CI/CD
* Traefik reverse proxy
### UI
**Cloud/Infra**
* Generates device UUID
* Uses `client.authenticateDevice()`
* Session stored in context
* Reconnect logic planned
* GCP-ready
* ARM homelab deployments
* Private registry support
---
## **5. Game Server Logic (Go)**
## 📦 Repository Structure
### ✔ State Initialization
* On second player join, server broadcasts full authoritative state.
### ✔ Turn Validation
Rejects:
* invalid coordinates
* occupied cells
* wrong turn
* malformed payloads
### ✔ Forfeit Detection
* Disconnects → match ends
* Final state broadcast to opponent
### ✔ Server Authority
* No client trust
* All moves validated server-side
* Structured logging everywhere
Result: **Deterministic, authoritative, cheat-proof gameplay.**
```
tic-tac-toe/
│── plugins/
│ ├── match.go
│ ├── matchmaking.go
│ └── leaderboard.go
│── Dockerfile
│── go.mod
│── go.sum
│── README.md
```
---
## **6. Real-Time Networking**
## 🔌 Registered Server Components
Validated end-to-end:
### 📌 Match Handler
* Match creation/join
* Matchmaker queues/matching
* OpCode 1 → player move submission
* OpCode 2 → authoritative board broadcast
Name: **`tictactoe`**
Python simulator & UI both confirm:
Handles:
* correct turn ordering
* full sync
* stable sockets
---
## **7. Matchmaking System**
### Backend
* `MatchmakerMatched` hook ensures:
* valid mode
* same mode for both players
* exactly two players
* Server creates authoritative match
* RPC `leave_matchmaking` implemented
### UI
* Mode selection (classic / blitz)
* Queue → ticket → matched → auto-join
* Uses Vite-driven environment variables for dynamic host/port selection
**Status:** Fully functional
---
## **8. Leaderboards**
### Backend
* Leaderboard created on startup
* Win → +1 score
* Metadata logged
### UI
* Leaderboard display works via API
Remaining UI polish:
* improved styling
* sorting
---
## **9. UI Implementation Status (React + Vite)**
### ✔ Implemented
* Authentication
* WebSocket session handling
* Matchmaking integration
* Full gameplay loop
* Turn validation
* State updates
* End-of-game status
* Leaderboard viewing
* Environment-configurable host, port, SSL, server key
* Win/loss/draw
* Disconnect forfeit
* Broadcasting authoritative state
### 🟡 Partially Implemented
### 📌 RPCs
* Error handling (WS failures, move rejections)
* Resume/reconnect logic
* UI layout consistency
* Mobile/responsive UI
* Animation/transition polish
| RPC Name | Purpose |
| ----------------------- | ---------------------------------------- |
| **`leave_matchmaking`** | Allows clients to exit matchmaking queue |
### 🔴 Missing / Planned
### 📌 Matchmaker Hook
* Rematch flow
* Lobby navigation
* Disconnect-recovery UX
| Hook | Purpose |
| ----------------------- | --------------------------------------------------------- |
| **`MatchmakerMatched`** | Validates matchmaker tickets and instantiates a new match |
---
## **10. Testing & Validation**
## 🎮 Gameplay Protocol
### Backend
### OpCodes
* Test coverage for win/loss/draw
* Illegal moves scenarios
* Disconnect behavior
* Matchmaking scaling
### UI
* Verified across full flow
* Missing stress and mobile testing
| OpCode | Direction | Meaning |
| ------ | --------------- | ----------------------------- |
| **1** | Client → Server | Submit move `{x, y}` |
| **2** | Server → Client | Full authoritative game state |
---
## **11. Google Cloud Deployment Plan**
## 🧠 Authoritative Flow Diagram
| Component | GCP Service |
| ------------- | ------------------------------- |
| Nakama server | Compute Engine VM (Docker) |
| PostgreSQL | Cloud SQL |
| Game UI | Cloud Run / Firebase Hosting |
| Networking | HTTPS Load Balancer + Static IP |
| Secrets | Secret Manager |
```mermaid
sequenceDiagram
participant C1 as Client 1
participant C2 as Client 2
participant S as Nakama + Go Plugin
Estimated time: **68 hours**
C1->>S: Matchmaker Join
C2->>S: Matchmaker Join
S->>S: MatchmakerMatched()
S-->>C1: Matched
S-->>C2: Matched
C1->>S: OpCode 1 (Move)
S->>S: Validate Move
S-->>C1: OpCode 2 (Updated State)
S-->>C2: OpCode 2 (Updated State)
```
---
## **12. Risks & Considerations**
## ⚙️ Build & Development
| Risk | Mitigation |
| ------------------------- | ------------------------------- |
| UI lacks reconnect logic | Add retry + resume capabilities |
| No rematch flow | Add match lifecycle management |
| Minimal mobile UI | Add responsive layout |
| Cloud deployment pending | Prioritize next sprint |
| Missing polish in UI flow | Add app shell + transitions |
### Build Go Plugin
Backend has *no major technical risks*. UI polish is the only remaining area.
```
CGO_ENABLED=1 go build \
--trimpath \
--buildmode=plugin \
-o build/main.so \
./plugins
```
### Run Nakama Locally
```
nakama migrate up --database.address "$DB_ADDR"
nakama \
--database.address "$DB_ADDR" \
--socket.server_key="$SERVER_KEY"
```
---
## **13. New CI/CD Enhancements (v1.0.0)**
## 🐳 Docker Build (Multi-Stage)
### ✔ Fully Automated Drone Pipeline Added
```dockerfile
FROM --platform=linux/arm64 golang:1.21.6 AS plugin_builder
* Fetch & validate latest Git tags
* Skip image build if tag already exists
* Build production UI image with correct Vite env
* Push to private registry
* Stop old containers and auto-run the new one
* ARM-compatible builds
RUN go mod download
COPY . .
RUN CGO_ENABLED=1 go build --buildmode=plugin -o build/main.so ./plugins
### ✔ New Frontend Dockerfile
* Multi-stage build using Node → BusyBox
* Extremely small production image
* Environment-driven configuration
### ✔ Go Plugin Build Fix
* Updated to Go **1.21.6** to match Nakama
* Fixes plugin ABI mismatch: `internal/goarch`
### ✔ Improved Repository Hygiene
* Added `.dockerignore`
* Eliminated unnecessary build context
FROM heroiclabs/nakama:3.21.0-arm
COPY --from=plugin_builder /workspace/build/main.so /nakama/data/modules/main.so
ENTRYPOINT ...
```
---
## **14. Executive Summary**
## 🤖 CI/CD — Drone Pipeline
### Issues Encountered
Drone performs:
Several areas required deep debugging, adding roughly **+1 day** of engineering time:
1. Fetch latest Git tag
2. Check if Docker image already exists
3. Build Nakama + plugin
4. Push to private registry
5. Stop old container
6. Deploy new Nakama server automatically
* Aligning UI matchmaking with authoritative server systems
* Handling Nakama JS socket lifecycle, ticket flow, and session timing
* OpCode synchronization and state update mapping
* Environment variable mismatches between Vite and production builds
* WebSocket connection reset issues and CORS origins
### Current State
The platform is now:
* **Fully playable**
* **Authoritative**
* **Stable across backend + UI**
* **CI/CD automated**
* **Docker deployable**
Any remaining work is **purely UI/UX polishing and cloud deployment**.
Full pipeline included in repository (`.drone.yml`).
---
## **Conclusion**
## 🌐 Traefik Routing
The system is production-ready at the backend level and feature-complete at the gameplay level. With UI refinements and deployment, the platform will be fully presentation-ready.
### HTTPS
**The project is now stable, secure, and demonstrates full multiplayer systems engineering capability end-to-end.**
```
nakama.aetoskia.com
/ → HTTP API
/ws → WebSocket (real-time)
```
Includes:
* CORS rules
* WebSocket upgrade headers
* Certificate resolver
* Secure default middlewares
---
## 🔧 Environment Variables
| Variable | Description |
| --------------- | ---------------------------- |
| `DB_ADDR` | PostgreSQL connection string |
| `SERVER_KEY` | Nakama server key |
| `REGISTRY_HOST` | Private registry |
---
## 📊 Leaderboards
* Created during server start
* Score: `+1` on win
* Metadata logged (mode, player IDs)
---
## 🧪 Testing
* Win/loss/draw simulation
* Invalid move rejection
* Disconnect → forfeit
* Load testing matchmaking
---
## 📈 Production Deployment
Supported on:
* ARM homelabs (Raspberry Pi)
* Google Cloud (Compute Engine + Cloud SQL)
* AWS EC2
* Kubernetes (optional)
---
## 🤝 Contributing
1. Fork repo
2. Create feature branch
3. Write tests
4. Submit PR
Coding style: Go fmt + idiomatic Go; follow Nakama plugin constraints.
---