diff --git a/CLAUDE.md b/CLAUDE.md index ede4e59..a66fe04 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -3,198 +3,19 @@ This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. ## Project Overview - -Know Foolery is a cross-platform quiz game inspired by the French game "Déconnaissance". The project follows a microservices architecture with Go backend services and React/React Native frontends using Gluestack UI for consistent cross-platform design. - -## Architecture - -### Backend Structure -- **Microservices**: Go-based services using Fiber 3.0+ framework -- **Database ORM**: Ent (Facebook) for type-safe database operations -- **Communication**: gRPC for inter-service communication -- **Authentication**: JWT + Zitadel Integration (OAuth 2.0/OIDC) -- **Database**: PostgreSQL (production), SQLite (development/testing) -- **Cache**: Redis for sessions and rate limiting - -### Service Architecture -``` -backend/ -├── Domain/ # Domain logic (DDD patterns) -├── services/ # Microservices -│ ├── {service-name}/ -│ │ ├── cmd/main.go # Service entry point -│ │ ├── internal/ -│ │ │ ├── handlers/ # Fiber HTTP handlers -│ │ │ ├── app/ # Business logic -│ │ │ ├── middleware/ # Service-specific middleware -│ │ │ └── models/ # Ent models and schemas -│ │ ├── config/ # Configuration management -│ │ └── tests/ # Service-specific tests -│ └── shared/ # Shared packages -│ ├── auth/ # JWT & Zitadel integration -│ ├── database/ # Ent database client -│ ├── observability/ # Metrics and tracing -│ └── security/ # Security utilities -``` - -### 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 - -### Frontend Structure -``` -frontend/ -├── shared/ -│ ├── ui-components/ # Shared Gluestack UI components -│ ├── logic/ # Business logic -│ ├── types/ # TypeScript types -│ └── utils/ # Utility functions -└── apps/ - ├── web/ # React web app (Vite + TypeScript) - ├── mobile/ # React Native app (Expo) - └── desktop/ # Wails desktop app -``` - -## Development Commands - -### Backend Development -```bash -# Navigate to service directory first -cd backend/services/{service-name} - -# Start service in development mode with hot reload -go run cmd/main.go - -# Run tests for a specific service -go test ./... -v - -# Run tests with coverage -go test ./... -cover - -# Build service binary -go build -o bin/{service-name} cmd/main.go - -# Generate Ent schemas (from service root) -go generate ./... - -# Lint Go code -golangci-lint run - -# Format Go code -go fmt ./... -goimports -w . -``` - -### Development Environment -```bash -# Start development stack with Docker Compose -cd infrastructure/dev -docker-compose up -d - -# This starts: -# - PostgreSQL database (port 5432) -# - Redis cache (port 6379) -# - Zitadel auth server (port 8080) -``` - -### Frontend Development -```bash -# Web application -cd frontend/apps/web -npm install -npm run dev # Start development server -npm run build # Production build -npm run test # Run Jest tests -npm run lint # ESLint -npm run type-check # TypeScript checking - -# Mobile application -cd frontend/apps/mobile -npm install -npx expo start # Start Expo development -npx expo run:ios # Run on iOS simulator -npx expo run:android # Run on Android emulator - -# Desktop application -cd frontend/apps/desktop -npm install -npm run dev # Start Wails development -npm run build # Build desktop app -``` - -## Key Technical Patterns - -### 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/React 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 + React 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 - -## Game Logic - -### Core Gameplay Rules -- Players have exactly 3 attempts per question -- 30-minute maximum session time -- Scoring: 2 points (no hint), 1 point (with hint), 0 points (incorrect/timeout) -- Questions belong to themes (Geography, History, Science, etc.) -- Leaderboard shows top 10 scores - -### Session Management -- Active session checking prevents duplicate games -- Timer implemented with Redis-backed state -- Session timeout handling with proper cleanup -- Score calculation with attempt and hint tracking - -## 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 - -### Frontend Testing -- Component tests with Jest + React Testing Library -- Hook tests with @testing-library/react-hooks -- E2E tests with Playwright -- Visual regression testing for UI components - -## 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 +This repository contains the code for a project called *KnowFoolery*. +Project overview file: +@README.md ## Documentation Structure -The `docs/` directory contains comprehensive documentation: -- **Requirements**: Functional and non-functional specifications -- **Architecture**: Technical, security, and observability designs -- **Guidelines**: Development, security, and observability standards \ No newline at end of file +### Requirements +The `docs/1_requirements/` directory contains functional and non-functional specifications: +@docs/1_requirements/functional-requirements.md - Functional requirements for KnowFoolery +@docs/1_requirements/non-functional-requirements.md - Non functional requirements for KnowFoolery + +### Architecture +The `docs/2_architecture/` directory contains technical, security, and observability architectures: +@docs/2_architecture/application-architecture.md - Application Architecture for KnowFoolery +@docs/2_architecture/observability-architecture.md - Observability Architecture for KnowFoolery +@docs/2_architecture/security-architecture.md - Security Architecture for KnowFoolery diff --git a/docs/1_requirements/functional-requirements.md b/docs/1_requirements/functional-requirements.md index a8ccf4f..c0c8ec4 100644 --- a/docs/1_requirements/functional-requirements.md +++ b/docs/1_requirements/functional-requirements.md @@ -1,6 +1,13 @@ # Know Foolery - Functional requirements -## Core Game Flow +## Core Gameplay Logic +- Players have exactly 3 attempts per question +- 30-minute maximum session time +- Scoring: 2 points (no hint), 1 point (with hint), 0 points (incorrect/timeout) +- Questions belong to themes (Geography, History, Science, etc.) +- Leaderboard shows top 10 scores + +## Game Flow ### 1. Game Session Initialization ``` @@ -102,6 +109,12 @@ Player Input: Name → Session Creation → Question Selection → Game Start ## Time Management +### Session Management +- Active session checking prevents duplicate games +- Timer implemented with Redis-backed state +- Session timeout handling with proper cleanup +- Score calculation with attempt and hint tracking + ### Session Timer - **Duration**: 30 minutes maximum per session - **Display**: Real-time countdown timer diff --git a/docs/2_architecture/technical-architecture.md b/docs/2_architecture/application-architecture.md similarity index 51% rename from docs/2_architecture/technical-architecture.md rename to docs/2_architecture/application-architecture.md index 52fe94a..e99b3a0 100644 --- a/docs/2_architecture/technical-architecture.md +++ b/docs/2_architecture/application-architecture.md @@ -6,7 +6,7 @@ Know Foolery follows a microservices architecture with clear separation between ### Frontend Architecture - **Web Application**: Responsive web application -- **Mobile Applications**: Cross platform application for iOS and Android +- **Mobile Applications**: Cross platform application for iOS and Android. Packages the web application - **Desktop Applications**: Cross platform application for MacOS, Windows and Linux. Packages the web application ### Backend Architecture @@ -23,113 +23,6 @@ Know Foolery follows a microservices architecture with clear separation between - **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/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 - - ## System Architecture Diagram ``` @@ -137,7 +30,6 @@ Know Foolery follows a microservices architecture with clear separation between │ Client Layer │ │ ┌──────────────┐ ┌──────────────┐ ┌───────────────┐ ┌─────────────┐ │ │ │ Web App │ │ Mobile iOS │ │ Mobile Android│ │ Desktop │ │ -│ │ (React) │ │(React Native)│ │(React Native) │ │ (Wails) │ │ │ └──────────────┘ └──────────────┘ └───────────────┘ └─────────────┘ │ └────────────────────────────────────────────────────────────────────────────┘ │ @@ -158,50 +50,39 @@ Know Foolery follows a microservices architecture with clear separation between │ ┌─────────────────────────────────────────────────────────────────────────────┐ │ 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 │ │ -│ └─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ │ +│ ┌─────────────┐ ┌─────────────┐ ┌────────────────┐ ┌───────────────┐ │ +│ │ Primary │ │ Cache & │ │ Authentication │ │ Observability │ │ +│ │ Database │ │ Sessions │ │ Provider │ │ Stack │ │ +│ └─────────────┘ └─────────────┘ └────────────────┘ └───────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` ### Frontend Technologies ```yaml Web Application: - Framework: React 18.2+ + Framework: SolidJS 1.9.3+ 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 + UI Library: SUID (suid.io) + Testing: Jest + 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 + Framework: Tauri 2.9.5+ + Language: TypeScript + Package manager: yarn + UI Template: Solid Desktop Application: - Framework: Wails 2.10+ - Template: wails-vite-react-ts-tailwind-template + Framework: Tauri 2.9.5+ + Language: TypeScript + Package manager: yarn + UI Template: Solid ``` ### Backend Technologies @@ -229,7 +110,7 @@ Primary Database: Migrations: Ent migrations Backup: pg_dump + Object Storage -Cache Layer: +Cache and Session: Engine: Redis 7+ Use Cases: Sessions, Rate limiting, Cache Clustering: Redis Cluster (Production) @@ -258,8 +139,7 @@ Authentication: ``` ### Inter-Service Communication - -#### Service Mesh Architecture +Service Mesh Architecture ```yaml Communication Patterns: Synchronous: gRPC for real-time operations @@ -276,31 +156,6 @@ Circuit Breaker: 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 @@ -337,4 +192,94 @@ CI/CD: Testing: Automated test suites Security: SAST/DAST scanning Deployment: GitOps with ArgoCD -``` \ No newline at end of file +``` + +## Project Structure +``` +knowfoolery/ +├── docs/ # Project documentation +├── backend/ +│ ├── services/ # Microservices +│ │ ├── {service-name}/ +│ │ │ ├── cmd/ +│ │ │ │ └── main.go # Service entry point +│ │ │ ├── internal/ +│ │ │ │ ├── handlers/ # Fiber HTTP handlers +│ │ │ │ ├── app/ # Business logic (commands, queries, dto) +│ │ │ │ ├── domain/ # Domain logic (aggregates, value objects, repositories interfaces, services from Domain Driven Design) +│ │ │ │ ├── infra/ +│ │ │ │ │ ├── events/ +│ │ │ │ │ ├── grpc/ +│ │ │ │ │ └── ent/ # Ent models and schemas + repositories implementation +│ │ │ ├── api/ # API definitions (OpenAPI/gRPC) +│ │ │ ├── config/ # Configuration management +│ │ │ ├── tests/ # Service-specific tests +│ │ │ ├── Dockerfile # Container definition +│ │ │ └── go.mod # Go module +│ │ └── shared/ # Shared packages +│ │ │ ├── errors/ # Shared domain errors +│ │ │ ├── events/ # Domain events contracts +│ │ │ ├── types/ # Shared types +│ │ │ ├── valueobjects/ # Shared value objects +│ │ │ └── infra/ +│ │ │ ├── auth/ # JWT middleware & Zitadel integration +│ │ │ ├── observability/ # Metrics and tracing +│ │ │ ├── security/ # Security utilities +│ │ │ └── utils/ # Common utilities +├── frontend/ +│ ├── shared/ +│ │ ├── ui-components/ # Shared Gluestack UI components +│ │ ├── logic/ # Business logic +│ │ ├── types/ # TypeScript types +│ │ └── utils/ # Utility functions +│ └── apps/ +│ ├── web/ # React web app +│ ├── mobile/ # React Native app +│ └── desktop/ # Wails desktop app +└── infrastructure/ # DevOps and deployment + ├── dev/ # Development setup + │ ├── docker-compose.yml # dev stack (hot reload, mounts) + │ └── api.env # dev env vars + └── prod/ # Production setup +``` + +### Backend Directory Structure +``` +backend/ +├── Domain/ # Domain logic (DDD patterns) +├── services/ # Microservices +│ ├── {service-name}/ +│ │ ├── cmd/main.go # Service entry point +│ │ ├── internal/ +│ │ │ ├── handlers/ # Fiber HTTP handlers +│ │ │ ├── app/ # Business logic +│ │ │ ├── middleware/ # Service-specific middleware +│ │ │ └── models/ # Ent models and schemas +│ │ ├── config/ # Configuration management +│ │ └── tests/ # Service-specific tests +│ └── shared/ # Shared packages +│ ├── auth/ # JWT & Zitadel integration +│ ├── database/ # Ent database client +│ ├── observability/ # Metrics and tracing +│ └── security/ # Security utilities +``` + +### Frontend Structure +``` +frontend/ +├── shared/ +│ ├── ui-components/ # Shared Gluestack UI components +│ ├── logic/ # Business logic +│ ├── types/ # TypeScript types +│ └── utils/ # Utility functions +└── apps/ + ├── web/ # SolidJS web app (Vite + TypeScript) + └── cross-platform/ # Tauri app (embeds the SolidJS web app) +``` + +### Infrastructure Structure +``` +Infrastructure/ +├── dev/ # Scripts to setup and start development infrastructure +└── prod/ # Scripts to setup and start production infrastructure +``` diff --git a/docs/3_guidelines/design-guidelines.md b/docs/3_guidelines/design-guidelines.md new file mode 100644 index 0000000..fe313d3 --- /dev/null +++ b/docs/3_guidelines/design-guidelines.md @@ -0,0 +1,199 @@ + +# 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/React 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 + React 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 + React Testing Library +- **Hook tests** with @testing-library/react-hooks + +### 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 diff --git a/docs/3_guidelines/development-guidelines.md b/docs/3_guidelines/development-guidelines.md index f9dfed7..a8165b2 100644 --- a/docs/3_guidelines/development-guidelines.md +++ b/docs/3_guidelines/development-guidelines.md @@ -4,73 +4,83 @@ This document establishes coding standards, development practices, and guidelines for the Know Foolery project to ensure consistency, maintainability, and quality across the codebase. +## Code Quality Standards -## Quality Assurance - -### Testing Strategy -- **Unit Testing**: Go testing framework + Jest for frontend -- **Integration Testing**: testcontainers for database testing -- **E2E Testing**: Playwright for complete user journeys -- **Performance Testing**: k6 for load and stress testing -- **Security Testing**: Automated security scanning and penetration testing - -### Code Quality +### General Code Quality Orientations - **Type Safety**: TypeScript for frontend, Go's type system for backend - **Code Review**: Mandatory peer review for all changes - **Static Analysis**: Automated code quality checks - **Documentation**: Comprehensive API and component documentation +### Linting and Formatting +```yaml +# .golangci.yml +run: + timeout: 5m + tests: true -## Code Organization +linters: + enable: + - gofmt + - goimports + - govet + - errcheck + - staticcheck + - unused + - gosimple + - structcheck + - varcheck + - ineffassign + - deadcode + - typecheck + - gosec + - misspell + - lll + - unconvert + - dupl + - goconst + - gocyclo -### Project Structure Standards +linters-settings: + lll: + line-length: 120 + gocyclo: + min-complexity: 15 + dupl: + threshold: 150 +issues: + exclude-rules: + - path: _test\.go + linters: + - gocyclo + - errcheck + - dupl + - gosec ``` -knowfoolery/ -├── docs/ # Project documentation -├── backend/ -│ ├── services/ # Microservices -│ │ ├── {service-name}/ -│ │ │ ├── cmd/ -│ │ │ │ └── main.go # Service entry point -│ │ │ ├── internal/ -│ │ │ │ ├── handlers/ # Fiber HTTP handlers -│ │ │ │ ├── app/ # Business logic (commands, queries, dto) -│ │ │ │ ├── domain/ # Domain logic (aggregates, value objects, repositories interfaces, services from Domain Driven Design) -│ │ │ │ ├── infra/ -│ │ │ │ │ ├── events/ -│ │ │ │ │ ├── grpc/ -│ │ │ │ │ └── ent/ # Ent models and schemas + repositories implementation -│ │ │ ├── api/ # API definitions (OpenAPI/gRPC) -│ │ │ ├── config/ # Configuration management -│ │ │ ├── tests/ # Service-specific tests -│ │ │ ├── Dockerfile # Container definition -│ │ │ └── go.mod # Go module -│ │ └── shared/ # Shared packages -│ │ │ ├── errors/ # Shared domain errors -│ │ │ ├── events/ # Domain events contracts -│ │ │ ├── types/ # Shared types -│ │ │ ├── valueobjects/ # Shared value objects -│ │ │ └── infra/ -│ │ │ ├── auth/ # JWT middleware & Zitadel integration -│ │ │ ├── observability/ # Metrics and tracing -│ │ │ ├── security/ # Security utilities -│ │ │ └── utils/ # Common utilities -├── frontend/ -│ ├── shared/ -│ │ ├── ui-components/ # Shared Gluestack UI components -│ │ ├── logic/ # Business logic -│ │ ├── types/ # TypeScript types -│ │ └── utils/ # Utility functions -│ └── apps/ -│ ├── web/ # React web app -│ ├── mobile/ # React Native app -│ └── desktop/ # Wails desktop app -└── infrastructure/ # DevOps and deployment - ├── dev/ # Development setup - │ ├── docker-compose.yml # dev stack (hot reload, mounts) - │ └── api.env # dev env vars - └── prod/ # Production setup + +```json +// .eslintrc.json +{ + "extends": [ + "@react-native", + "@typescript-eslint/recommended", + "prettier" + ], + "parser": "@typescript-eslint/parser", + "plugins": ["@typescript-eslint", "react-hooks"], + "rules": { + "@typescript-eslint/explicit-function-return-type": "error", + "@typescript-eslint/no-unused-vars": "error", + "@typescript-eslint/prefer-const": "error", + "react-hooks/rules-of-hooks": "error", + "react-hooks/exhaustive-deps": "warn", + "prefer-const": "error", + "no-var": "error", + "object-shorthand": "error", + "prefer-template": "error" + } +} ``` ### Naming Conventions @@ -1331,81 +1341,7 @@ describe('useGameSession', () => { }) }) ``` - -## Code Quality Standards - -### Linting and Formatting -```yaml -# .golangci.yml -run: - timeout: 5m - tests: true - -linters: - enable: - - gofmt - - goimports - - govet - - errcheck - - staticcheck - - unused - - gosimple - - structcheck - - varcheck - - ineffassign - - deadcode - - typecheck - - gosec - - misspell - - lll - - unconvert - - dupl - - goconst - - gocyclo - -linters-settings: - lll: - line-length: 120 - gocyclo: - min-complexity: 15 - dupl: - threshold: 150 - -issues: - exclude-rules: - - path: _test\.go - linters: - - gocyclo - - errcheck - - dupl - - gosec -``` - -```json -// .eslintrc.json -{ - "extends": [ - "@react-native", - "@typescript-eslint/recommended", - "prettier" - ], - "parser": "@typescript-eslint/parser", - "plugins": ["@typescript-eslint", "react-hooks"], - "rules": { - "@typescript-eslint/explicit-function-return-type": "error", - "@typescript-eslint/no-unused-vars": "error", - "@typescript-eslint/prefer-const": "error", - "react-hooks/rules-of-hooks": "error", - "react-hooks/exhaustive-deps": "warn", - "prefer-const": "error", - "no-var": "error", - "object-shorthand": "error", - "prefer-template": "error" - } -} -``` - -### Git Workflow +## Git Workflow ```bash # Branch naming conventions feature/add-game-session-management @@ -1424,4 +1360,69 @@ docs(api): update authentication endpoint documentation test(services): add comprehensive game service tests ``` -This comprehensive development guidelines document ensures consistent, maintainable, and high-quality code across the Know Foolery project. \ No newline at end of file +## Development Commands + +### Backend Development +```bash +# Navigate to service directory first +cd backend/services/{service-name} + +# Start service in development mode with hot reload +go run cmd/main.go + +# Run tests for a specific service +go test ./... -v + +# Run tests with coverage +go test ./... -cover + +# Build service binary +go build -o bin/{service-name} cmd/main.go + +# Generate Ent schemas (from service root) +go generate ./... + +# Lint Go code +golangci-lint run + +# Format Go code +go fmt ./... +goimports -w . +``` + +### Development Environment +```bash +# Start development stack with Docker Compose +cd infrastructure/dev +docker-compose up -d + +# This starts: +# - PostgreSQL database (port 5432) +# - Redis cache (port 6379) +# - Zitadel auth server (port 8080) +``` + +### Frontend Development +```bash +# Web application +cd frontend/apps/web +npm install +npm run dev # Start development server +npm run build # Production build +npm run test # Run Jest tests +npm run lint # ESLint +npm run type-check # TypeScript checking + +# Mobile application +cd frontend/apps/mobile +npm install +npx expo start # Start Expo development +npx expo run:ios # Run on iOS simulator +npx expo run:android # Run on Android emulator + +# Desktop application +cd frontend/apps/desktop +npm install +npm run dev # Start Wails development +npm run build # Build desktop app +```