# Know Foolery - Design Guidelines ## Key Technical Orientations ### Go Service Structure - Services use Fiber v3 framework with structured error handling - Business logic separated into service layer with dependency injection - Ent ORM with schema-first approach and proper indexing - Custom middleware for JWT authentication and rate limiting - Comprehensive testing with testcontainers for integration tests ### TypeScript/SolidJS Patterns - Components use Gluestack UI with proper TypeScript typing - Custom hooks pattern for business logic (e.g., `useGameSession`) - Context + useReducer for state management - Comprehensive testing with Jest + Recommended UI Testing Library ### Authentication Flow - Zitadel provides OAuth 2.0/OIDC authentication - JWT tokens validated via shared auth middleware - User context stored in Fiber locals for request handling - Admin routes protected with role-based authorization ### Database Design - Domain-driven design with clear aggregate boundaries - Ent schemas with proper validation and indexes - Transaction management for multi-step operations - Separate read/write patterns for performance ### Security Considerations - JWT token validation on all protected endpoints - Rate limiting per user and IP address - Input validation and sanitization - CORS configuration for cross-origin requests - SQL injection prevention with Ent ORM - Secrets management via environment variables ## Application Design ### Core Services 1. **Game Service** (port 8080): Session management, scoring logic 2. **Question Service** (port 8081): CRUD operations for questions/themes 3. **User Service** (port 8082): Player registration and profiles 4. **Leaderboard Service** (port 8083): Score calculations and rankings 5. **Session Service** (port 8084): Timer management, session state 6. **Admin Service** (port 8085): Question/user management with OAuth 7. **Gateway Service** (port 8086): API routing, authentication, rate limiting ### Detailes 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/CDN’ed 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 ### 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); } ``` ## Testing Strategy ### Backend Testing - **Unit tests** with Go testing framework + testify - **Integration tests** with testcontainers (PostgreSQL) - **Service layer tests** with mocked dependencies - **API endpoint tests** with Fiber test utilities - **Integration Testing** with testcontainers for database testing ### Frontend Testing - **Unit tests** with Jest - **Component tests** with Jest + vitest + Recoummended Testing Library ### End to End Testing - **E2E Testing** with Playwright for complete user journeys - **Visual regression testing** for UI components ### Non functional requirements validation - **Performance Testing**: k6 for load and stress testing - **Security Testing**: Automated security scanning and penetration testing