You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

333 lines
15 KiB
Markdown

# Know Foolery - Technical Architecture Documentation
## Architecture Overview
Know Foolery follows a microservices architecture with clear separation between frontend presentation, backend services, and data persistence layers. The system is designed for cross-platform compatibility, scalability, and maintainability.
## Technical Architecture
### Frontend Architecture
- **Web Application**: React with TypeScript, vite and React Native Web
- **Mobile Applications**: React Native with Expo for iOS and Android
- **Desktop Applications**: Wails for macOS, Windows, and Linux, with the web application packaged for the deployement in the Wails app
- **UI Framework**: Gluestack UI for consistent cross-platform design
### Backend Architecture
- **Business Logic**: Domain Driven Design approach
- **Microservices**: Go-based services with clear domain boundaries
- **API Gateway**: Centralized routing, authentication, and rate limiting
- **Database ORM**: Ent for type-safe database operations
- **Communication**: gRPC for inter-service communication
- **External APIs**: Repository pattern for external integrations
### Domain Design
- **Aggregates**: User, Theme, Question, GameSession
- **Value Objects**: Hint, Attempt, Answer, Score
- **Domain Services**: Scoring
### Microservices Design
#### Core Services
1. **Game Service**: Session management, scoring logic, attempts tracking
2. **Question Service**: CRUD operations for questions, themes, hints
3. **User Service**: Player registration and profile management
4. **Leaderboard Service**: Score calculations, rankings, statistics
5. **Session Service**: Timer management, session state persistence
6. **Admin Service**: Question and user management with OAuth protection
7. **Gateway Service**: API routing, authentication, rate limiting
#### External Services
1. **Zitadel**: Self-hosted OAuth 2.0/OIDC authentication
2. **PostgreSQL**: Primary database for production application data
3. **sqlite**: Database for test application data
4. **Redis**: Session state and caching layer
### Database Design
#### Core Entities
- **Users**: ID, name, created_at (minimal player data)
- **Themes**: ID, theme, metadata
- **Questions**: ID, ID of theme, text, answer, hint, metadata
- **GameSessions**: ID, ID of user, score, start_time, end_time, is_active
- **Attempts**: ID, ID of GameSession, answer
- **Leaderboard**: Aggregated scores and rankings
- **AuditLogs**: Admin actions and security events
#### Data Relationships
- Questions belong to themes
- GameSessions track multiple question attempts for a user
- Leaderboard aggregates from GameSessions
- AuditLogs reference users and actions
## Deployment & Infrastructure
### Development Environment
- **Local Development**: SQLite for rapid iteration
- **Docker Compose**: Containerized development environment
- **Testing**: Comprehensive unit, integration, and E2E testing
### Production Environment
- **Container Orchestration**: Kubernetes for production deployment
- **Database**: PostgreSQL with high availability configuration
- **Monitoring**: Prometheus, Grafana, Jaeger for observability
- **CI/CD**: GitHub Actions for automated testing and deployment
### Cross-Platform Deployment
- **Web**: Standard web application deployment
- **Mobile**: iOS App Store and Google Play Store distribution
- **Desktop**: Wails applications for major operating systems
## System Architecture Diagram
```
┌────────────────────────────────────────────────────────────────────────────┐
│ Client Layer │
│ ┌──────────────┐ ┌──────────────┐ ┌───────────────┐ ┌─────────────┐ │
│ │ Web App │ │ Mobile iOS │ │ Mobile Android│ │ Desktop │ │
│ │ (React) │ │(React Native)│ │(React Native) │ │ (Wails) │ │
│ └──────────────┘ └──────────────┘ └───────────────┘ └─────────────┘ │
└────────────────────────────────────────────────────────────────────────────┘
HTTPS/WSS
┌─────────────────────────────────────────────────────────────────────────────┐
│ API Gateway Layer │
│ ┌────────────────────────────────────────────────────────────────────────┐ │
│ │ NGINX + API Gateway Service (Go) │ │
│ │ • Authentication & Authorization │ │
│ │ • Rate Limiting & CORS │ │
│ │ • Request Routing & Load Balancing │ │
│ │ • Security Headers & Input Validation │ │
│ └────────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
gRPC/HTTP
┌─────────────────────────────────────────────────────────────────────────────┐
│ Microservices Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ Game │ │ Question │ │ User │ │ Leaderboard │ │
│ │ Service │ │ Service │ │ Service │ │ Service │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ┌─────────────┐ ┌─────────────┐ │
│ │ Session │ │ Admin │ │
│ │ Service │ │ Service │ │
│ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
Database Connections
┌─────────────────────────────────────────────────────────────────────────────┐
│ Data & External Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ PostgreSQL │ │ Redis │ │ Zitadel │ │ Observabi- │ │
│ │ Primary │ │ Cache & │ │ OAuth │ │ lity │ │
│ │ Database │ │ Sessions │ │ Provider │ │ Stack │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
## Technology Stack
- **Web Application**: React with TypeScript, vite and React Native Web
- **Mobile Applications**: React Native with Expo for iOS and Android
- **Desktop Applications**: Wails for macOS, Windows, and Linux, with the web application packaged for the deployement in the Wails app
- **UI Framework**: Gluestack UI for consistent cross-platform design
### Frontend Technologies
```yaml
Web Application:
Framework: React 18.2+
Language: TypeScript 5.0+
Build Tool: Vite 4.0+
UI Library: Gluestack UI (React Native Web)
Styling: NativeWind/Tailwind CSS 3.0+
State Management: React Context + useReducer
Testing: Jest + React Testing Library + Playwright
Mobile Applications:
Framework: React Native 0.81+
Language: TypeScript 5.9+
UI Library: Gluestack UI (Native)
Navigation: Expo 54+
State Management: React Context + useReducer
Testing: Jest + React Native Testing Library
Desktop Application:
Framework: Wails 2.10+
Template: wails-vite-react-ts-tailwind-template
```
### Backend Technologies
```yaml
Microservices:
Language: Go 1.25+
HTTP Framework: Fiber 3.0+
gRPC: Protocol Buffers + gRPC-Go
Database ORM: Ent (Facebook)
Authentication: JWT + Zitadel Integration
Testing: Go testing + testcontainers
API Gateway:
Reverse Proxy: NGINX
Gateway Service: Go + Fiber
Load Balancing: Round-robin + Health checks
Rate Limiting: Redis-based sliding window
```
### Data Technologies
```yaml
Primary Database:
Engine: PostgreSQL 15+
Connection Pooling: pgxpool
Migrations: Ent migrations
Backup: pg_dump + Object Storage
Cache Layer:
Engine: Redis 7+
Use Cases: Sessions, Rate limiting, Cache
Clustering: Redis Cluster (Production)
Persistence: RDB + AOF
Authentication:
Provider: Zitadel (Self-hosted)
Protocol: OAuth 2.0 + OpenID Connect
Tokens: JWT with RS256 signing
MFA: TOTP + WebAuthn
```
### Infrastructure Technologies
```yaml
Containerization:
Runtime: Docker 24+
Orchestration: Kubernetes 1.28+
Registry: Private Docker Registry
Observability:
Metrics: Prometheus + Node Exporter
Visualization: Grafana + Custom Dashboards
Tracing: Jaeger + OpenTelemetry
Logging: Structured logging + Loki
CI/CD:
Platform: GitHub Actions
Testing: Automated test suites
Security: SAST/DAST scanning
Deployment: GitOps with ArgoCD
```
## Microservices Design
### Service Boundaries
#### 1. Game Service
```go
// API Endpoints
POST /api/v1/game/start // Start new game session
GET /api/v1/game/session/{id} // Get session details
POST /api/v1/game/answer // Submit answer
POST /api/v1/game/hint // Request hint
POST /api/v1/game/end // End session
GET /api/v1/game/status/{id} // Get session status
```
#### 2. Question Service
```go
// API Endpoints
GET /api/v1/questions/themes/random/{id} // Get random question in a theme
GET /api/v1/questions/random // Get random question in a theme
GET /api/v1/questions/{id} // Get specific question
GET /api/v1/questions/themes // List available themes
POST /api/v1/questions // Create question (admin)
PUT /api/v1/questions/{id} // Update question (admin)
DELETE /api/v1/questions/{id} // Delete question (admin)
GET /api/v1/questions // List all questions (admin)
POST /api/v1/questions/bulk // Bulk question import (admin)
```
#### 3. User Service
```go
// API Endpoints
POST /api/v1/users/register // Register new player
GET /api/v1/users/profile // Get user profile
PUT /api/v1/users/profile // Update profile
GET /api/v1/users/sessions // Get session history
DELETE /api/v1/users/profile // Delete account (GDPR)
GET /api/v1/users // List all users (admin)
DELETE /api/v1/users // Delete user (admin)
```
#### 4. Leaderboard Service
```go
// API Endpoints
GET /api/v1/leaderboard/top10 // Get top 10 scores
GET /api/v1/leaderboard/stats // Get game statistics
GET /api/v1/leaderboard/player/{id} // Get player ranking
POST /api/v1/leaderboard/update // Update scores (internal)
```
#### 5. Session Service
```go
// API Endpoints
POST /api/v1/sessions // Create session
GET /api/v1/sessions/{id} // Get session
PUT /api/v1/sessions/{id} // Update session
DELETE /api/v1/sessions/{id} // End session
GET /api/v1/sessions/{id}/timer // Get timer status
```
#### 6. Admin Service
```go
// API Endpoints
POST /api/v1/admin/auth // Admin authentication
GET /api/v1/admin/dashboard // Dashboard data
GET /api/v1/admin/audit // Audit logs
```
### Inter-Service Communication
#### Service Mesh Architecture
```yaml
Communication Patterns:
Synchronous: gRPC for real-time operations
Asynchronous: Event-driven via message queues (future)
Service Discovery:
Registry: Kubernetes DNS
Health Checks: HTTP /health endpoints
Load Balancing: Round-robin with health awareness
Circuit Breaker:
Pattern: Hystrix-style circuit breakers
Fallback: Graceful degradation
Timeout: Context-based timeouts
```
#### gRPC Service Definitions
```protobuf
// game_service.proto
service GameService {
rpc StartGame(StartGameRequest) returns (StartGameResponse);
rpc SubmitAnswer(SubmitAnswerRequest) returns (SubmitAnswerResponse);
rpc GetSession(GetSessionRequest) returns (GetSessionResponse);
rpc EndGame(EndGameRequest) returns (EndGameResponse);
}
// question_service.proto
service QuestionService {
rpc GetRandomQuestion(RandomQuestionRequest) returns (Question);
rpc ValidateAnswer(ValidateAnswerRequest) returns (ValidationResponse);
rpc GetQuestionHint(HintRequest) returns (HintResponse);
}
// leaderboard_service.proto
service LeaderboardService {
rpc UpdateScore(UpdateScoreRequest) returns (UpdateScoreResponse);
rpc GetTopScores(TopScoresRequest) returns (TopScoresResponse);
rpc GetPlayerRank(PlayerRankRequest) returns (PlayerRankResponse);
}
```
This technical architecture provides a solid foundation for building a scalable, secure, and maintainable quiz game platform with cross-platform capabilities.