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.

340 lines
16 KiB
Markdown

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# Know Foolery - Application Architecture Documentation
## Application 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.
### Frontend Architecture
- **Web Application**: Responsive web application
- **Mobile Applications**: Cross platform application for iOS and Android
- **Desktop Applications**: Cross platform application for MacOS, Windows and Linux. Packages the web application
### Backend Architecture
- **Business Logic**: Domain Driven Design approach
- **Microservices**: Services with clear domain boundaries
- **API Gateway**: Centralized routing, authentication, and rate limiting
- **Database ORM**: For type-safe database operations
- **Communication**: gRPC for inter-service synchronous communication
- **External APIs**: Repository pattern for external integrations
### External Services
- **Authentication**: OAuth 2.0/OIDC authentication
- **Relational Database**: For production application data
- **Cache**: Session state and caching layer
## Application Design
### Microservices Design
1. **Game Session Service**:
- Responsibilities: Session management, pick next question (excluding already answered), scoring logic, attempts tracking, enforce timer, anti-cheat checks.
- Scaling driver: concurrent players, realtime updates.
- Interfaces:
- Commands:
- POST /sessions/start → Start new game session for a player (user)
- POST /sessions/end → End game session
- POST /sessions/{id}/answer → Submit answer
- POST /sessions/{id}/hint → Request hint
- Queries
- GET /sessions/{id} → Get session details, including status and timer
- GET /sessions/{id}/question → Get the current question for the session
- Domain driven design:
- **Aggregates**: GameSession
- **Value Objects**: Attempt, Score
- **Domain Services**: Scoring
- Storage:
- Core entities:
- **Sessions**: id, id of user, score, start_time, end_time, is_active
- **Session_Questions**: id, id of question
- **Attempts**: id, id of Session_Questions, answer, score
- Data relationships : Sessions track multiple question attempts for a user
2. **Question Bank Service**:
- Responsibilities: CRUD operations for questions, themes, hints, random selection API with filters (and “exclude these ids”).
- Scaling driver: editorial ops, cacheable reads.
- Interfaces:
- Commands:
- POST /questions/random?theme=… with body {exclude:[ids]} → returns 1 random question
- Queries
- GET /questions/{id} → Get specific question
- Admin:
- POST /admin/questions → Create question
- PUT /admin/questions/{id} → Update question
- DELETE /admin/questions/{id} → Delete question
- GET /admin/themes → List available themes
- GET /admin/themes/{id}/questions → List all questions for a theme
- POST /admin/questions/bulk → Bulk question import
- Domain driven design:
- **Aggregates**: Theme, Question
- **Value Objects**: Hint, Answer
- Storage:
- Core entities:
- **Themes**: id, theme, metadata
- **Questions**: id, theme_fk, text, answer, hint, difficulty, metadata
- Data relationships : Questions belong to themes
- Notes: easily cache popular themes; can be read-replicated/CDNed if needed.
3. **Leaderboard Service**:
- Responsibilities: compute top-10, success rate, keep historical scores, player statistics.
- Scaling driver: heavy reads; write via events from Session svc.
- Interfaces:
- Queries
- GET /leaderboard/top10 → Get top 10 scores
- GET /leaderboard/players/{id} → Get player ranking and history
- GET /leaderboard/stats → Get game statistics
- Commands
- POST /leaderboard/update → Update scores (internal)
- Storage:
- Core entities:
- **Scores**: session_id, player, points, duration, questions_answered, correct_count, created_at
- **Leaderboard**: Aggregated scores and rankings (top10 materialized view/cache)
- Data relationships : Leaderboard aggregates from GameSessions
- Notes: can be eventually consistent (seconds). Cache responses (Redis) with short TTL.
4. **User Service**: Player registration and profile management
- Responsibilities: Identity & Accounts management including email verification, Consent & Compliance (GDPR)
- Scaling driver: registration bursts (marketing campaigns), auth traffic
- Interfaces:
- Queries
- GET /users/{id} → Get user profile (restricted to the user)
- Commands
- POST /users/register → Register new player
- POST /users/verify-email
- PUT /users/{id} → Update profile
- Admin
- GET /admin/users?email=… → Get user profile (PII; protected)
- GET /admin/users → List all users (admin)
- POST /admin/users/{id}/block|unblock|delete
- POST /admin/users/{id}/resend-verification
- POST /admin/users/{id}/export → enqueues GDPR export job
- POST /admin/users/{id}/erase → soft-delete + downstream purge events
- DELETE /users/{id} → Delete account (GDPR)
- Domain driven design:
- **Aggregates**: User
- Storage:
- Core entities:
- **Users**: ID, name, display_name, created_at, updated_at, deleted_at
- **user_contact**: email unique, email_verified_at
- **user_consent**: marketing_email bool, consent_at, email_token (token unique), purpose (verify|login|change_email), expires_at, used_at
5. **Admin Service**:
- Responsibilities: Admin authentication, dashboard, audit logs access
- Interfaces:
- Commands
- POST /admin/auth → Admin authentication
- Admin
- GET /admin/dashboard → Dashboard data
- GET /admin/audit → Audit logs
- Storage:
- Core entities:
- **AuditLogs**: Admin actions and security events. Security events reference users and actions
6. **Gateway Service**:
- Responsibilities: API routing, authentication, rate limiting
## 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 Session│ │Question Bank│ │ User │ │ Leaderboard │ │
│ │ Service │ │ Service │ │ Service │ │ Service │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
│ ┌─────────────┐ │
│ │ Admin │ │
│ │ Service │ │
│ └─────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
Database Connections
┌─────────────────────────────────────────────────────────────────────────────┐
│ Data & External Layer │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ PostgreSQL │ │ Redis │ │ Zitadel │ │ Observabi- │ │
│ │ Primary │ │ Cache & │ │ OAuth │ │ lity │ │
│ │ Database │ │ Sessions │ │ Provider │ │ Stack │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
```
### 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 for production
```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
```
### Data Technologies for development
```yaml
Primary Database:
Engine: Sqlite
Migrations: Ent migrations
Cache Layer:
Engine: Mock object created for the project
Authentication:
Provider: Mock object created for the project
Protocol: OAuth 2.0 + OpenID Connect
Tokens: JWT with RS256 signing
```
### Inter-Service Communication
#### Service Mesh Architecture
```yaml
Communication Patterns:
Synchronous: gRPC for real-time operations
Asynchronous: asynchronous gRPC calls (Event-driven via message queues in the 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);
}
```
## 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
### 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
```