diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md new file mode 100644 index 0000000..e6eb78b --- /dev/null +++ b/docs/architecture/ARCHITECTURE.md @@ -0,0 +1,402 @@ +# GreenCode Backend System Architecture + +## Table of Contents +1. [System Overview](#system-overview) +2. [Architecture Patterns](#architecture-patterns) +3. [Component Architecture](#component-architecture) +4. [Data Architecture](#data-architecture) +5. [Security Architecture](#security-architecture) +6. [Infrastructure Architecture](#infrastructure-architecture) +7. [Communication Patterns](#communication-patterns) +8. [Deployment Architecture](#deployment-architecture) +9. [Monitoring & Observability](#monitoring--observability) +10. [Scalability & Performance](#scalability--performance) +11. [Development Guidelines](#development-guidelines) + +## System Overview + +GreenCode is an environmental project management platform built with a modern, scalable backend architecture. The system follows Domain-Driven Design (DDD) principles and implements a layered architecture pattern to ensure maintainability, testability, and scalability. + +### Core Business Domain +- **Environmental Project Management**: Track and manage sustainability projects +- **User Management**: Authentication, authorization, and user profiles +- **Project Lifecycle**: From planning to completion with impact tracking +- **Sustainability Metrics**: Environmental impact scoring and reporting + +### Technology Stack +- **Framework**: Spring Boot 3.2.0 +- **Language**: Java 17 +- **Database**: PostgreSQL (production), H2 (development) +- **Cache**: Redis +- **Security**: Spring Security with JWT +- **Documentation**: OpenAPI 3.0 (Swagger) +- **Monitoring**: Prometheus + Grafana +- **Containerization**: Docker + Docker Compose +- **Reverse Proxy**: Nginx + +## Architecture Patterns + +### 1. Layered Architecture +The system implements a traditional layered architecture with clear separation of concerns: + +``` +┌─────────────────────────────────────────────────────────────┐ +│ Presentation Layer │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ +│ │ REST API │ │ Swagger UI │ │ Health Endpoints │ │ +│ │ Controllers │ │ OpenAPI │ │ Actuator │ │ +│ └─────────────┘ └─────────────┘ └─────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +┌─────────────────────────────────────────────────────────────┐ +│ Business Layer │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ +│ │ User Service│ │Auth Service │ │ Project Service │ │ +│ │ DTOs │ │JWT Utils │ │ Validation │ │ +│ └─────────────┘ └─────────────┘ └─────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +┌─────────────────────────────────────────────────────────────┐ +│ Data Access Layer │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ +│ │User Repo │ │Project Repo │ │ Audit Repository │ │ +│ │JPA Entities │ │Custom Queries│ │ Cache Layer │ │ +│ └─────────────┘ └─────────────┘ └─────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +┌─────────────────────────────────────────────────────────────┐ +│ Data Layer │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ +│ │ PostgreSQL │ │ Redis │ │ File Storage │ │ +│ │ (Primary) │ │ (Cache) │ │ (Documents) │ │ +│ └─────────────┘ └─────────────┘ └─────────────────────┘ │ +└─────────────────────────────────────────────────────────────┘ +``` + +### 2. Domain-Driven Design (DDD) +The system is organized around business domains: + +- **User Domain**: User management, authentication, authorization +- **Project Domain**: Environmental project lifecycle management +- **Audit Domain**: System activity tracking and compliance + +### 3. Repository Pattern +Data access is abstracted through repository interfaces, providing: +- Clean separation between business logic and data access +- Testability through mock implementations +- Database-agnostic business logic + +## Component Architecture + +### Core Components + +#### 1. Controllers (Presentation Layer) +- **UserController**: User CRUD operations and profile management +- **ProjectController**: Project lifecycle management +- **AuthController**: Authentication and authorization endpoints +- **HealthController**: System health and monitoring endpoints + +**Responsibilities:** +- HTTP request/response handling +- Input validation and sanitization +- DTO transformation +- Error handling and status codes + +#### 2. Services (Business Layer) +- **UserService**: User business logic and validation +- **ProjectService**: Project management business rules +- **AuthService**: Authentication and JWT token management +- **NotificationService**: System notifications and alerts + +**Responsibilities:** +- Business logic implementation +- Transaction management +- Data validation +- Integration with external services + +#### 3. Repositories (Data Access Layer) +- **UserRepository**: User data persistence +- **ProjectRepository**: Project data persistence +- **AuditRepository**: System audit trail + +**Responsibilities:** +- Data persistence operations +- Custom query implementation +- Database optimization +- Cache integration + +#### 4. Entities (Domain Layer) +- **User**: User domain model with roles and permissions +- **Project**: Environmental project domain model +- **BaseEntity**: Common audit fields and lifecycle management + +**Responsibilities:** +- Domain model representation +- Business rule enforcement +- Data validation constraints +- Relationship mapping + +### Configuration Components + +#### 1. Security Configuration +- **SecurityConfig**: Spring Security configuration +- **JWT Utils**: Token generation and validation +- **Password Encoder**: BCrypt password hashing + +#### 2. Application Configuration +- **Application Properties**: Environment-specific configuration +- **Database Configuration**: Connection pooling and transaction management +- **Cache Configuration**: Redis integration and caching strategies + +## Data Architecture + +### Database Design + +#### Core Tables + +**Users Table** +```sql +CREATE TABLE users ( + id BIGSERIAL PRIMARY KEY, + username VARCHAR(50) UNIQUE NOT NULL, + email VARCHAR(100) UNIQUE NOT NULL, + password VARCHAR(120) NOT NULL, + first_name VARCHAR(100), + last_name VARCHAR(100), + role VARCHAR(20) DEFAULT 'USER', + is_enabled BOOLEAN DEFAULT true, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + created_by VARCHAR(100), + updated_by VARCHAR(100), + is_active BOOLEAN DEFAULT true +); +``` + +**Projects Table** +```sql +CREATE TABLE projects ( + id BIGSERIAL PRIMARY KEY, + name VARCHAR(200) NOT NULL, + description TEXT, + category VARCHAR(50) NOT NULL, + status VARCHAR(20) DEFAULT 'PLANNED', + start_date DATE, + end_date DATE, + budget DECIMAL(15,2), + actual_cost DECIMAL(15,2), + location VARCHAR(500), + coordinates VARCHAR(100), + impact_score INTEGER CHECK (impact_score >= 1 AND impact_score <= 10), + sustainability_rating INTEGER CHECK (sustainability_rating >= 1 AND sustainability_rating <= 5), + manager_id BIGINT REFERENCES users(id), + team_size INTEGER, + is_public BOOLEAN DEFAULT true, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + created_by VARCHAR(100), + updated_by VARCHAR(100), + is_active BOOLEAN DEFAULT true +); +``` + +### Data Relationships +- **User ↔ Project**: One-to-Many (User can manage multiple projects) +- **Project ↔ AuditLog**: One-to-Many (Project has multiple audit entries) +- **User ↔ Role**: Many-to-Many (Future enhancement for complex role management) + +### Caching Strategy +- **Redis Integration**: Session management and frequently accessed data +- **Cache Patterns**: + - Write-through for user sessions + - Cache-aside for project data + - TTL-based expiration for temporary data + +## Security Architecture + +### Authentication Flow +``` +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ Client │───▶│ Login │───▶│ Validate │───▶│ Generate │ +│ │ │ Request │ │ Credentials │ │ JWT │ +└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ + │ │ + │ ▼ + │ ┌─────────────┐ + │ │ Return │ + └────────────────────────────────────────────────│ JWT Token │ + └─────────────┘ +``` + +### Authorization Model +- **Role-Based Access Control (RBAC)**: + - USER: Basic project access + - MODERATOR: Project management capabilities + - ADMIN: Full system access + +- **Resource-Level Permissions**: + - Project ownership validation + - Public/private project access control + - Audit trail access restrictions + +### Security Features +- **Password Security**: BCrypt hashing with salt +- **JWT Tokens**: Stateless authentication with configurable expiration +- **CORS Configuration**: Cross-origin request handling +- **Input Validation**: Comprehensive request validation +- **SQL Injection Prevention**: JPA/Hibernate parameterized queries + +## Infrastructure Architecture + +### Container Architecture +``` +┌─────────────────────────────────────────────────────────────┐ +│ Docker Network │ +│ (greencode-network) │ +└─────────────────────────────────────────────────────────────┘ +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ Nginx │ │GreenCode │ │ PostgreSQL │ │ Redis │ +│ (Port 80/443)│ │ Backend │ │ (Port 5432) │ │ (Port 6379) │ +│ │ │ (Port 8080) │ │ │ │ │ +└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ +┌─────────────┐ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ +│ Prometheus │ │ Grafana │ │ Adminer │ │ Logs │ +│ (Port 9090) │ │ (Port 3000) │ │ (Port 8081) │ │ Volume │ +└─────────────┘ └─────────────┘ └─────────────┘ └─────────────┘ +``` + +### Service Dependencies +- **GreenCode Backend** → PostgreSQL, Redis +- **Nginx** → GreenCode Backend +- **Grafana** → Prometheus +- **Adminer** → PostgreSQL + +### Volume Management +- **PostgreSQL Data**: Persistent storage for database +- **Redis Data**: Cache persistence +- **Prometheus Data**: Metrics storage +- **Grafana Data**: Dashboard configurations +- **Application Logs**: Centralized logging + +## Communication Patterns + +### 1. REST API Communication +- **Synchronous Communication**: HTTP/HTTPS for client-server interaction +- **API Versioning**: URL-based versioning (`/api/v1/`) +- **Content Negotiation**: JSON request/response format +- **HTTP Status Codes**: Standard REST status codes + +### 2. Internal Service Communication +- **Direct Method Calls**: Within the same application +- **Repository Pattern**: Data access abstraction +- **Service Layer**: Business logic encapsulation + +### 3. External Integration Points +- **Database**: JDBC connection pooling +- **Cache**: Redis client integration +- **Monitoring**: Prometheus metrics collection +- **Logging**: Structured logging with correlation IDs + +### 4. Future Messaging Patterns +- **Event-Driven Architecture**: For microservices communication +- **Message Queues**: Asynchronous processing +- **WebSockets**: Real-time notifications +- **GraphQL**: Flexible data querying + +## Deployment Architecture + +### Development Environment +- **Local Development**: Docker Compose with H2 database +- **Hot Reload**: Spring Boot DevTools integration +- **Debugging**: Remote debugging support +- **Testing**: Embedded test containers + +### Production Environment +- **Container Orchestration**: Docker Swarm or Kubernetes ready +- **Load Balancing**: Nginx reverse proxy +- **Database**: PostgreSQL with connection pooling +- **Monitoring**: Prometheus + Grafana stack +- **Logging**: Centralized log aggregation + +### CI/CD Pipeline +- **Build**: Maven-based build process +- **Testing**: Unit and integration tests +- **Containerization**: Multi-stage Docker builds +- **Deployment**: Blue-green deployment strategy + +## Monitoring & Observability + +### Metrics Collection +- **Application Metrics**: Spring Boot Actuator +- **JVM Metrics**: Memory, CPU, garbage collection +- **Database Metrics**: Connection pool, query performance +- **Custom Metrics**: Business-specific KPIs + +### Health Checks +- **Liveness Probe**: Application startup verification +- **Readiness Probe**: Service availability check +- **Database Health**: Connection and query validation +- **Cache Health**: Redis connectivity check + +### Logging Strategy +- **Structured Logging**: JSON format with correlation IDs +- **Log Levels**: DEBUG, INFO, WARN, ERROR +- **Log Aggregation**: Centralized log collection +- **Audit Trail**: User action tracking + +### Alerting +- **Performance Alerts**: Response time thresholds +- **Error Rate Alerts**: Exception frequency monitoring +- **Resource Alerts**: Memory and CPU usage +- **Business Alerts**: Critical business metric thresholds + +## Scalability & Performance + +### Horizontal Scaling +- **Stateless Design**: JWT-based authentication +- **Load Balancing**: Nginx round-robin distribution +- **Database Scaling**: Read replicas and connection pooling +- **Cache Scaling**: Redis cluster support + +### Performance Optimization +- **Database Indexing**: Optimized query performance +- **Connection Pooling**: HikariCP configuration +- **Caching Strategy**: Multi-level caching approach +- **Async Processing**: Non-blocking operations + +### Resource Management +- **Memory Management**: JVM tuning and monitoring +- **CPU Optimization**: Thread pool configuration +- **I/O Optimization**: Database query optimization +- **Network Optimization**: Connection reuse and compression + +## Development Guidelines + +### Code Organization +- **Package Structure**: Domain-driven package organization +- **Naming Conventions**: Clear and descriptive naming +- **Documentation**: Comprehensive JavaDoc and README files +- **Code Reviews**: Mandatory peer review process + +### Testing Strategy +- **Unit Tests**: Service and repository layer testing +- **Integration Tests**: API endpoint testing +- **Test Coverage**: Minimum 80% code coverage +- **Test Data**: Isolated test data management + +### Security Guidelines +- **Input Validation**: Comprehensive request validation +- **Authentication**: Secure token management +- **Authorization**: Principle of least privilege +- **Data Protection**: Encryption at rest and in transit + +### Performance Guidelines +- **Database Queries**: Optimized and indexed queries +- **Caching**: Strategic cache implementation +- **Resource Usage**: Efficient memory and CPU utilization +- **Monitoring**: Proactive performance monitoring + +--- + +## Conclusion + +This architecture provides a solid foundation for the GreenCode backend system, ensuring scalability, maintainability, and security. The modular design allows for future enhancements and microservices migration when needed. Regular architecture reviews and updates will ensure the system continues to meet evolving business requirements. + +For implementation details and specific configurations, refer to the individual component documentation and the deployment guides in the `/docs` directory. diff --git a/docs/architecture/COMMUNICATION_PATTERNS.md b/docs/architecture/COMMUNICATION_PATTERNS.md new file mode 100644 index 0000000..8c861e2 --- /dev/null +++ b/docs/architecture/COMMUNICATION_PATTERNS.md @@ -0,0 +1,760 @@ +# Communication Patterns Documentation + +## Table of Contents +1. [Overview](#overview) +2. [REST API Communication](#rest-api-communication) +3. [Internal Service Communication](#internal-service-communication) +4. [Database Communication](#database-communication) +5. [Cache Communication](#cache-communication) +6. [External Service Integration](#external-service-integration) +7. [Future Messaging Patterns](#future-messaging-patterns) +8. [Error Handling & Resilience](#error-handling--resilience) +9. [Performance Considerations](#performance-considerations) + +## Overview + +The GreenCode backend system implements multiple communication patterns to ensure efficient, reliable, and scalable data exchange between different components. This document outlines the current communication patterns and provides guidance for future enhancements. + +### Communication Pattern Categories +- **Synchronous Communication**: REST APIs, direct method calls +- **Asynchronous Communication**: Future event-driven patterns +- **Data Persistence**: Database and cache interactions +- **External Integration**: Third-party service communication + +## REST API Communication + +### API Design Principles + +#### 1. RESTful Resource Design +``` +Base URL: https://api.greencode.com/api/v1 + +Resources: +- /users - User management +- /projects - Project management +- /auth - Authentication +- /health - System health +``` + +#### 2. HTTP Methods and Semantics +```http +GET /api/v1/users # List all users +GET /api/v1/users/{id} # Get specific user +POST /api/v1/users # Create new user +PUT /api/v1/users/{id} # Update user +DELETE /api/v1/users/{id} # Delete user +PATCH /api/v1/users/{id} # Partial update +``` + +#### 3. Request/Response Format +```json +// Request Example +POST /api/v1/users +Content-Type: application/json +Authorization: Bearer + +{ + "username": "john_doe", + "email": "john@example.com", + "password": "securePassword123", + "firstName": "John", + "lastName": "Doe", + "role": "USER" +} + +// Response Example +HTTP/1.1 201 Created +Content-Type: application/json + +{ + "id": 1, + "username": "john_doe", + "email": "john@example.com", + "firstName": "John", + "lastName": "Doe", + "role": "USER", + "isEnabled": true, + "createdAt": "2024-01-15T10:30:00Z", + "updatedAt": "2024-01-15T10:30:00Z" +} +``` + +### API Versioning Strategy +- **URL-based versioning**: `/api/v1/`, `/api/v2/` +- **Backward compatibility**: Maintain previous versions +- **Deprecation policy**: 6-month notice for breaking changes + +### Content Negotiation +- **Primary format**: JSON (application/json) +- **Error responses**: Consistent error format +- **Compression**: Gzip compression enabled +- **Character encoding**: UTF-8 + +## Internal Service Communication + +### 1. Service Layer Communication + +#### Direct Method Calls +```java +@Service +public class ProjectService { + + @Autowired + private UserService userService; + + @Autowired + private AuditService auditService; + + public Project createProject(Project project, Long userId) { + // Direct service call + User manager = userService.getUserById(userId) + .orElseThrow(() -> new UserNotFoundException("User not found")); + + // Business logic + project.setManager(manager); + Project savedProject = projectRepository.save(project); + + // Audit logging + auditService.logProjectCreation(savedProject, manager); + + return savedProject; + } +} +``` + +#### Transaction Management +```java +@Service +@Transactional +public class UserService { + + @Transactional(readOnly = true) + public Optional getUserById(Long id) { + return userRepository.findById(id); + } + + @Transactional(rollbackFor = Exception.class) + public User createUser(User user) { + // Multiple database operations in single transaction + validateUserData(user); + encodePassword(user); + User savedUser = userRepository.save(user); + sendWelcomeEmail(savedUser); + return savedUser; + } +} +``` + +### 2. Repository Pattern Communication + +#### JPA Repository Communication +```java +@Repository +public interface UserRepository extends JpaRepository { + + // Spring Data JPA method queries + Optional findByUsername(String username); + Optional findByEmail(String email); + boolean existsByUsername(String username); + boolean existsByEmail(String email); + + // Custom query methods + @Query("SELECT u FROM User u WHERE u.role = :role AND u.isActive = true") + List findActiveUsersByRole(@Param("role") UserRole role); + + // Native queries for complex operations + @Query(value = "SELECT * FROM users WHERE created_at >= :date", nativeQuery = true) + List findUsersCreatedAfter(@Param("date") LocalDateTime date); +} +``` + +#### Custom Repository Implementation +```java +@Repository +public class UserRepositoryImpl implements UserRepositoryCustom { + + @PersistenceContext + private EntityManager entityManager; + + @Override + public boolean existsByUsernameOrEmailExcludingId(String username, String email, Long id) { + String jpql = "SELECT COUNT(u) > 0 FROM User u WHERE " + + "(u.username = :username OR u.email = :email) AND u.id != :id"; + + return entityManager.createQuery(jpql, Boolean.class) + .setParameter("username", username) + .setParameter("email", email) + .setParameter("id", id) + .getSingleResult(); + } +} +``` + +## Database Communication + +### 1. Connection Management + +#### Connection Pool Configuration +```yaml +spring: + datasource: + url: jdbc:postgresql://localhost:5432/greencode + username: postgres + password: password + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + leak-detection-threshold: 60000 +``` + +#### Transaction Isolation Levels +```java +@Service +public class ProjectService { + + @Transactional(isolation = Isolation.READ_COMMITTED) + public Project updateProject(Long id, Project projectDetails) { + // Read committed isolation for consistency + return projectRepository.save(projectDetails); + } + + @Transactional(isolation = Isolation.SERIALIZABLE) + public void transferProjectOwnership(Long projectId, Long newOwnerId) { + // Serializable isolation for critical operations + Project project = projectRepository.findById(projectId).orElseThrow(); + User newOwner = userService.getUserById(newOwnerId).orElseThrow(); + project.setManager(newOwner); + projectRepository.save(project); + } +} +``` + +### 2. Query Optimization + +#### Lazy Loading Strategy +```java +@Entity +public class Project extends BaseEntity { + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "manager_id") + private User manager; + + @OneToMany(mappedBy = "project", fetch = FetchType.LAZY) + private List auditLogs; +} +``` + +#### Eager Loading for Performance +```java +@Repository +public interface ProjectRepository extends JpaRepository { + + @Query("SELECT p FROM Project p JOIN FETCH p.manager WHERE p.id = :id") + Optional findByIdWithManager(@Param("id") Long id); + + @Query("SELECT p FROM Project p JOIN FETCH p.manager m WHERE p.status = :status") + List findByStatusWithManager(@Param("status") ProjectStatus status); +} +``` + +## Cache Communication + +### 1. Redis Integration + +#### Cache Configuration +```java +@Configuration +@EnableCaching +public class CacheConfig { + + @Bean + public RedisConnectionFactory redisConnectionFactory() { + LettuceConnectionFactory factory = new LettuceConnectionFactory(); + factory.setHostName("localhost"); + factory.setPort(6379); + return factory; + } + + @Bean + public CacheManager cacheManager() { + RedisCacheManager.Builder builder = RedisCacheManager + .RedisCacheManagerBuilder + .fromConnectionFactory(redisConnectionFactory()) + .cacheDefaults(cacheConfiguration(Duration.ofMinutes(10))); + + return builder.build(); + } +} +``` + +#### Cache Usage Patterns +```java +@Service +public class UserService { + + @Cacheable(value = "users", key = "#id") + public Optional getUserById(Long id) { + return userRepository.findById(id); + } + + @Cacheable(value = "users", key = "#username") + public Optional getUserByUsername(String username) { + return userRepository.findByUsername(username); + } + + @CacheEvict(value = "users", key = "#user.id") + public User updateUser(User user) { + return userRepository.save(user); + } + + @CacheEvict(value = "users", allEntries = true) + public void clearUserCache() { + // Clear all user cache entries + } +} +``` + +### 2. Cache Strategies + +#### Write-Through Caching +```java +@Service +public class SessionService { + + @Autowired + private RedisTemplate redisTemplate; + + public void cacheUserSession(User user, String token) { + String key = "session:" + token; + UserSession session = new UserSession(user, token, Duration.ofHours(24)); + redisTemplate.opsForValue().set(key, session, Duration.ofHours(24)); + } + + public Optional getUserSession(String token) { + String key = "session:" + token; + return Optional.ofNullable((UserSession) redisTemplate.opsForValue().get(key)); + } +} +``` + +#### Cache-Aside Pattern +```java +@Service +public class ProjectService { + + public Project getProjectById(Long id) { + // Check cache first + String cacheKey = "project:" + id; + Project cachedProject = (Project) redisTemplate.opsForValue().get(cacheKey); + + if (cachedProject != null) { + return cachedProject; + } + + // Load from database + Project project = projectRepository.findById(id) + .orElseThrow(() -> new ProjectNotFoundException("Project not found")); + + // Cache the result + redisTemplate.opsForValue().set(cacheKey, project, Duration.ofMinutes(30)); + + return project; + } +} +``` + +## External Service Integration + +### 1. HTTP Client Communication + +#### RestTemplate Configuration +```java +@Configuration +public class RestTemplateConfig { + + @Bean + public RestTemplate restTemplate() { + RestTemplate restTemplate = new RestTemplate(); + + // Connection timeout + HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(); + factory.setConnectTimeout(5000); + factory.setReadTimeout(10000); + restTemplate.setRequestFactory(factory); + + // Error handling + restTemplate.setErrorHandler(new CustomResponseErrorHandler()); + + return restTemplate; + } +} +``` + +#### External API Integration +```java +@Service +public class NotificationService { + + @Autowired + private RestTemplate restTemplate; + + @Value("${external.email.service.url}") + private String emailServiceUrl; + + public void sendWelcomeEmail(User user) { + try { + EmailRequest emailRequest = new EmailRequest( + user.getEmail(), + "Welcome to GreenCode", + buildWelcomeEmailContent(user) + ); + + ResponseEntity response = restTemplate.postForEntity( + emailServiceUrl + "/send", + emailRequest, + EmailResponse.class + ); + + if (response.getStatusCode().is2xxSuccessful()) { + log.info("Welcome email sent to user: {}", user.getEmail()); + } + } catch (Exception e) { + log.error("Failed to send welcome email to user: {}", user.getEmail(), e); + // Don't throw exception - email failure shouldn't break user registration + } + } +} +``` + +### 2. Circuit Breaker Pattern + +#### Resilience4j Configuration +```java +@Configuration +public class CircuitBreakerConfig { + + @Bean + public CircuitBreaker emailServiceCircuitBreaker() { + return CircuitBreaker.ofDefaults("emailService") + .toBuilder() + .slidingWindowSize(10) + .failureRateThreshold(50) + .waitDurationInOpenState(Duration.ofSeconds(30)) + .build(); + } +} +``` + +#### Circuit Breaker Usage +```java +@Service +public class NotificationService { + + @Autowired + private CircuitBreaker emailServiceCircuitBreaker; + + public void sendWelcomeEmail(User user) { + Supplier decoratedSupplier = CircuitBreaker + .decorateSupplier(emailServiceCircuitBreaker, () -> { + sendEmailInternal(user); + return null; + }); + + try { + decoratedSupplier.get(); + } catch (CallNotPermittedException e) { + log.warn("Email service circuit breaker is open, email not sent"); + } catch (Exception e) { + log.error("Failed to send email", e); + } + } +} +``` + +## Future Messaging Patterns + +### 1. Event-Driven Architecture + +#### Domain Events +```java +@Entity +public class Project extends BaseEntity { + + @DomainEvents + Collection domainEvents() { + return Arrays.asList(new ProjectCreatedEvent(this)); + } + + @AfterDomainEventPublication + void callbackMethod() { + // Clear domain events after publication + } +} + +@EventListener +@Component +public class ProjectEventHandler { + + @Async + @EventListener + public void handleProjectCreated(ProjectCreatedEvent event) { + // Send notifications + // Update search index + // Generate reports + } +} +``` + +#### Message Queue Integration (Future) +```java +@Service +public class ProjectEventPublisher { + + @Autowired + private RabbitTemplate rabbitTemplate; + + public void publishProjectCreated(Project project) { + ProjectCreatedMessage message = new ProjectCreatedMessage( + project.getId(), + project.getName(), + project.getManager().getId() + ); + + rabbitTemplate.convertAndSend("project.exchange", "project.created", message); + } +} +``` + +### 2. WebSocket Communication + +#### WebSocket Configuration (Future) +```java +@Configuration +@EnableWebSocket +public class WebSocketConfig implements WebSocketConfigurer { + + @Override + public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { + registry.addHandler(new ProjectUpdateHandler(), "/ws/projects") + .setAllowedOrigins("*"); + } +} +``` + +#### Real-time Notifications +```java +@Component +public class ProjectUpdateHandler extends TextWebSocketHandler { + + @Override + public void afterConnectionEstablished(WebSocketSession session) { + // Handle new WebSocket connection + } + + @Override + protected void handleTextMessage(WebSocketSession session, TextMessage message) { + // Handle incoming messages + } + + public void broadcastProjectUpdate(Project project) { + // Broadcast project updates to all connected clients + } +} +``` + +## Error Handling & Resilience + +### 1. Retry Patterns + +#### Spring Retry Configuration +```java +@Configuration +@EnableRetry +public class RetryConfig { + + @Bean + public RetryTemplate retryTemplate() { + RetryTemplate retryTemplate = new RetryTemplate(); + + FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy(); + backOffPolicy.setBackOffPeriod(2000); // 2 seconds + retryTemplate.setBackOffPolicy(backOffPolicy); + + SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(); + retryPolicy.setMaxAttempts(3); + retryTemplate.setRetryPolicy(retryPolicy); + + return retryTemplate; + } +} +``` + +#### Retry Usage +```java +@Service +public class ExternalServiceClient { + + @Autowired + private RetryTemplate retryTemplate; + + public String callExternalService(String data) { + return retryTemplate.execute(context -> { + try { + return restTemplate.postForObject("/external-api", data, String.class); + } catch (Exception e) { + log.warn("External service call failed, attempt: {}", context.getRetryCount() + 1); + throw e; + } + }); + } +} +``` + +### 2. Timeout Configuration + +#### Global Timeout Settings +```yaml +spring: + datasource: + hikari: + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + + redis: + timeout: 2000ms + lettuce: + pool: + max-active: 8 + max-idle: 8 + min-idle: 0 +``` + +#### Service-Level Timeouts +```java +@Service +public class ExternalApiService { + + @Async("externalApiExecutor") + @Timeout(value = 10, unit = TimeUnit.SECONDS) + public CompletableFuture callExternalApi(String data) { + return CompletableFuture.supplyAsync(() -> { + // External API call + return restTemplate.postForObject("/api/external", data, String.class); + }); + } +} +``` + +## Performance Considerations + +### 1. Connection Pooling + +#### Database Connection Pool +```yaml +spring: + datasource: + hikari: + maximum-pool-size: 20 + minimum-idle: 5 + connection-timeout: 30000 + idle-timeout: 600000 + max-lifetime: 1800000 + leak-detection-threshold: 60000 +``` + +#### HTTP Connection Pool +```java +@Configuration +public class HttpClientConfig { + + @Bean + public CloseableHttpClient httpClient() { + return HttpClients.custom() + .setMaxConnTotal(100) + .setMaxConnPerRoute(20) + .setConnectionTimeToLive(30, TimeUnit.SECONDS) + .build(); + } +} +``` + +### 2. Async Processing + +#### Async Configuration +```java +@Configuration +@EnableAsync +public class AsyncConfig { + + @Bean(name = "taskExecutor") + public Executor taskExecutor() { + ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); + executor.setCorePoolSize(5); + executor.setMaxPoolSize(20); + executor.setQueueCapacity(100); + executor.setThreadNamePrefix("Async-"); + executor.initialize(); + return executor; + } +} +``` + +#### Async Service Methods +```java +@Service +public class NotificationService { + + @Async("taskExecutor") + public CompletableFuture sendEmailAsync(User user) { + try { + sendWelcomeEmail(user); + return CompletableFuture.completedFuture(null); + } catch (Exception e) { + return CompletableFuture.failedFuture(e); + } + } +} +``` + +### 3. Batch Processing + +#### Batch Repository Operations +```java +@Repository +public class ProjectRepositoryImpl { + + @PersistenceContext + private EntityManager entityManager; + + @Transactional + public void batchInsertProjects(List projects) { + for (int i = 0; i < projects.size(); i++) { + entityManager.persist(projects.get(i)); + + if (i % 50 == 0) { + entityManager.flush(); + entityManager.clear(); + } + } + } +} +``` + +--- + +## Conclusion + +This communication patterns documentation provides a comprehensive overview of how different components in the GreenCode backend system interact with each other. The patterns described here ensure: + +- **Reliability**: Robust error handling and retry mechanisms +- **Performance**: Efficient connection pooling and caching strategies +- **Scalability**: Async processing and batch operations +- **Maintainability**: Clear separation of concerns and consistent patterns + +As the system evolves, these patterns can be extended to support more advanced communication mechanisms like event-driven architecture and real-time messaging. diff --git a/docs/architecture/INDEX.md b/docs/architecture/INDEX.md new file mode 100644 index 0000000..4aa5d8f --- /dev/null +++ b/docs/architecture/INDEX.md @@ -0,0 +1,175 @@ +# GreenCode Backend Architecture Documentation Index + +## 📋 Overview + +This index provides a comprehensive guide to the GreenCode backend system architecture documentation. The architecture has been designed to be scalable, maintainable, and follows modern software engineering best practices. + +## 🎯 GitHub Issue #4 Completion Status + +**Issue**: Define Backend System Architecture #4 +**Status**: ✅ **COMPLETED** + +### ✅ Acceptance Criteria Met: +- [x] **Architecture document available in /docs** - Comprehensive architecture documentation created +- [x] **At least one architecture diagram attached or linked** - Multiple detailed diagrams created +- [x] **Comprehensive project start information** - Extensive documentation for development workflow + +## 📚 Documentation Structure + +### 🏗️ Core Architecture Documents + +| Document | Description | Purpose | +|----------|-------------|---------| +| **[README.md](./README.md)** | Main architecture overview and quick start guide | Entry point for architecture understanding | +| **[ARCHITECTURE.md](./ARCHITECTURE.md)** | Comprehensive system architecture documentation | Detailed technical architecture reference | +| **[COMMUNICATION_PATTERNS.md](./COMMUNICATION_PATTERNS.md)** | Communication patterns and protocols | Understanding system interactions | + +### 📊 Architecture Diagrams + +| Diagram | File | Description | +|---------|------|-------------| +| **System Overview** | [system-overview.md](./diagrams/system-overview.md) | High-level system architecture and component interactions | +| **Application Architecture** | [application-architecture.md](./diagrams/application-architecture.md) | Detailed application layer architecture and domain model | +| **Deployment Architecture** | [deployment-architecture.md](./diagrams/deployment-architecture.md) | Container and deployment architecture | +| **Data Flow** | [data-flow.md](./diagrams/data-flow.md) | Data flow patterns and processing sequences | + +## 🚀 Quick Navigation Guide + +### For New Developers +1. **Start Here**: [README.md](./README.md) - Get the big picture +2. **Deep Dive**: [ARCHITECTURE.md](./ARCHITECTURE.md) - Understand the technical details +3. **Visual Learning**: [diagrams/](./diagrams/) - See the system visually +4. **Communication**: [COMMUNICATION_PATTERNS.md](./COMMUNICATION_PATTERNS.md) - Understand how components interact + +### For System Architects +1. **Architecture Overview**: [ARCHITECTURE.md](./ARCHITECTURE.md) - Complete system design +2. **Deployment Strategy**: [deployment-architecture.md](./diagrams/deployment-architecture.md) - Infrastructure design +3. **Scalability Planning**: [ARCHITECTURE.md#scalability--performance](./ARCHITECTURE.md#scalability--performance) - Performance considerations + +### For DevOps Engineers +1. **Container Architecture**: [deployment-architecture.md](./diagrams/deployment-architecture.md) - Docker setup +2. **Monitoring Setup**: [ARCHITECTURE.md#monitoring--observability](./ARCHITECTURE.md#monitoring--observability) - Observability stack +3. **Environment Config**: [ARCHITECTURE.md#deployment-architecture](./ARCHITECTURE.md#deployment-architecture) - Environment management + +### For Security Engineers +1. **Security Architecture**: [ARCHITECTURE.md#security-architecture](./ARCHITECTURE.md#security-architecture) - Security design +2. **Authentication Flow**: [data-flow.md](./diagrams/data-flow.md) - Auth sequence diagrams +3. **Communication Security**: [COMMUNICATION_PATTERNS.md#security-considerations](./COMMUNICATION_PATTERNS.md#security-considerations) - Secure communication + +## 🏗️ Architecture Highlights + +### Technology Stack +- **Backend**: Spring Boot 3.2.0 with Java 17 +- **Database**: PostgreSQL (production), H2 (development) +- **Cache**: Redis for session management and caching +- **Security**: Spring Security with JWT authentication +- **Monitoring**: Prometheus + Grafana stack +- **Containerization**: Docker + Docker Compose +- **Documentation**: OpenAPI 3.0 (Swagger) + +### Key Architectural Patterns +- **Layered Architecture**: Clear separation of concerns +- **Domain-Driven Design (DDD)**: Business domain focus +- **Repository Pattern**: Data access abstraction +- **Service Layer Pattern**: Business logic encapsulation +- **Dependency Injection**: Loose coupling and testability + +### Scalability Features +- **Horizontal Scaling**: Stateless design with JWT +- **Load Balancing**: Nginx reverse proxy +- **Database Optimization**: Connection pooling and indexing +- **Caching Strategy**: Multi-level caching approach +- **Container Orchestration**: Docker Compose ready + +## 📈 System Capabilities + +### Current Features +- ✅ **User Management**: Registration, authentication, authorization +- ✅ **Project Management**: Environmental project lifecycle +- ✅ **Security**: JWT-based authentication with RBAC +- ✅ **Monitoring**: Comprehensive observability stack +- ✅ **Documentation**: OpenAPI/Swagger integration +- ✅ **Containerization**: Full Docker support + +### Future Enhancements +- 🔄 **Event-Driven Architecture**: Message queues and event sourcing +- 🔄 **Microservices**: Service decomposition strategy +- 🔄 **Real-time Features**: WebSocket integration +- 🔄 **Advanced Analytics**: Business intelligence and reporting +- 🔄 **API Gateway**: Centralized API management + +## 🔧 Development Workflow + +### Getting Started +1. **Environment Setup**: Follow deployment guides +2. **Code Structure**: Understand package organization +3. **Development Guidelines**: Follow coding standards +4. **Testing Strategy**: Implement comprehensive testing + +### Architecture Evolution +- **Current State**: Monolithic Spring Boot application +- **Migration Path**: Microservices-ready architecture +- **Scalability Plan**: Horizontal scaling strategy +- **Technology Updates**: Framework and dependency management + +## 📊 Architecture Metrics + +### Code Quality +- **Test Coverage**: Target 80% minimum +- **Code Review**: Mandatory peer review process +- **Documentation**: Comprehensive JavaDoc and README files +- **Security**: Regular security audits and updates + +### Performance Targets +- **Response Time**: < 200ms for API calls +- **Throughput**: 1000+ requests per second +- **Availability**: 99.9% uptime target +- **Scalability**: Support for 10,000+ concurrent users + +## 🔗 Related Documentation + +### Project Documentation +- **[API Documentation](../api/README.md)** - API endpoints and usage +- **[Deployment Guide](../deployment/README.md)** - Deployment instructions +- **[Development Guide](../../README.md)** - Development setup and guidelines + +### External Resources +- **Spring Boot Documentation**: [spring.io/projects/spring-boot](https://spring.io/projects/spring-boot) +- **PostgreSQL Documentation**: [postgresql.org/docs](https://www.postgresql.org/docs/) +- **Docker Documentation**: [docs.docker.com](https://docs.docker.com/) +- **Redis Documentation**: [redis.io/documentation](https://redis.io/documentation) + +## 📝 Maintenance and Updates + +### Documentation Maintenance +- **Regular Reviews**: Quarterly architecture reviews +- **Version Control**: Track architecture changes +- **Stakeholder Updates**: Keep team informed of changes +- **Best Practices**: Follow documentation standards + +### Architecture Governance +- **Change Management**: Formal process for architecture changes +- **Review Process**: Architecture review board +- **Compliance**: Ensure adherence to architectural principles +- **Training**: Team education on architecture patterns + +--- + +## 🎉 Conclusion + +This comprehensive architecture documentation provides a solid foundation for the GreenCode backend system. The documentation covers all aspects from high-level system design to detailed implementation patterns, ensuring that developers, architects, and stakeholders have a complete understanding of the system. + +The architecture is designed to be: +- **Scalable**: Ready for growth and increased load +- **Maintainable**: Clear structure and comprehensive documentation +- **Secure**: Robust security patterns and practices +- **Observable**: Comprehensive monitoring and logging +- **Evolvable**: Ready for future enhancements and changes + +For any questions or clarifications about the architecture, please refer to the specific documentation sections or contact the development team. + +--- + +**Last Updated**: January 2024 +**Version**: 1.0 +**Maintainer**: BOSC Team diff --git a/docs/architecture/README.md b/docs/architecture/README.md index 6d609c5..f34af8c 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -1,95 +1,193 @@ # GreenCode System Architecture -This directory contains system architecture documentation and diagrams for the GreenCode backend. +This directory contains comprehensive system architecture documentation and diagrams for the GreenCode backend system. + +## 📚 Documentation Structure + +### Core Architecture Documents +- **[ARCHITECTURE.md](./ARCHITECTURE.md)** - Comprehensive system architecture overview +- **[COMMUNICATION_PATTERNS.md](./COMMUNICATION_PATTERNS.md)** - Detailed communication patterns and protocols + +### Architecture Diagrams +- **[System Overview](./diagrams/system-overview.md)** - High-level system architecture and component interactions +- **[Application Architecture](./diagrams/application-architecture.md)** - Detailed application layer architecture +- **[Deployment Architecture](./diagrams/deployment-architecture.md)** - Container and deployment architecture +- **[Data Flow](./diagrams/data-flow.md)** - Data flow patterns and processing sequences ## 🏗️ System Overview -GreenCode is built using a layered architecture pattern with clear separation of concerns: +GreenCode is built using a modern, scalable backend architecture following Domain-Driven Design (DDD) principles and implementing a layered architecture pattern with clear separation of concerns. + +### Technology Stack +- **Framework**: Spring Boot 3.2.0 with Java 17 +- **Database**: PostgreSQL (production), H2 (development) +- **Cache**: Redis for session management and caching +- **Security**: Spring Security with JWT authentication +- **Documentation**: OpenAPI 3.0 (Swagger) +- **Monitoring**: Prometheus + Grafana stack +- **Containerization**: Docker + Docker Compose +- **Reverse Proxy**: Nginx +### Architecture Layers ``` ┌─────────────────────────────────────────────────────────────┐ │ Presentation Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ REST API │ │ Swagger UI │ │ Health Endpoints │ │ +│ │ Controllers │ │ OpenAPI │ │ Actuator │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────┐ │ Business Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │ User Service│ │Auth Service │ │ Project Service │ │ +│ │ DTOs │ │JWT Utils │ │ Validation │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────┐ │ Data Access Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ │ │User Repo │ │Project Repo │ │ Audit Repository │ │ +│ │JPA Entities │ │Custom Queries│ │ Cache Layer │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ┌─────────────────────────────────────────────────────────────┐ │ Data Layer │ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────────────┐ │ -│ │ PostgreSQL │ │ H2 │ │ File Storage │ │ +│ │ PostgreSQL │ │ Redis │ │ File Storage │ │ +│ │ (Primary) │ │ (Cache) │ │ (Documents) │ │ │ └─────────────┘ └─────────────┘ └─────────────────────┘ │ └─────────────────────────────────────────────────────────────┘ ``` ## 🔐 Security Architecture -### Authentication Flow -1. **Login Request** → User credentials -2. **Validation** → BCrypt password verification -3. **JWT Generation** → Signed token with claims -4. **Response** → JWT token + refresh token +### Authentication & Authorization +- **JWT-based Authentication**: Stateless token-based authentication +- **Role-Based Access Control (RBAC)**: USER, MODERATOR, ADMIN roles +- **Password Security**: BCrypt hashing with salt +- **CORS Configuration**: Cross-origin request handling +- **Input Validation**: Comprehensive request validation -### Authorization -- **Role-Based Access Control (RBAC)** -- **Resource-Level Permissions** -- **API Rate Limiting** +### Security Features +- **SQL Injection Prevention**: JPA/Hibernate parameterized queries +- **XSS Protection**: Input sanitization and output encoding +- **CSRF Protection**: Token-based CSRF protection +- **Rate Limiting**: API rate limiting (future enhancement) ## 🗄️ Database Design ### Core Entities -- **User**: Authentication and profile data -- **Project**: Environmental project information -- **AuditLog**: System activity tracking -- **Role**: User permissions and access levels - -### Relationships -- User ↔ Role (Many-to-Many) -- User ↔ Project (One-to-Many) -- Project ↔ AuditLog (One-to-Many) - -## 🔄 Data Flow - -### Request Processing -1. **HTTP Request** → Controller -2. **Validation** → DTO validation -3. **Business Logic** → Service layer -4. **Data Access** → Repository layer -5. **Response** → DTO transformation - -### Error Handling -- **Global Exception Handler** -- **Structured Error Responses** -- **Logging and Monitoring** - -## 📊 Performance Considerations - -- **Connection Pooling** for database -- **Caching Strategy** for frequently accessed data -- **Async Processing** for long-running operations -- **Database Indexing** for query optimization - -## 🔧 Configuration Management - -- **Environment-Specific Configs** -- **Externalized Properties** -- **Feature Flags** -- **Health Checks** - -## 🚀 Scalability - -- **Horizontal Scaling** with load balancers -- **Database Sharding** for large datasets -- **Microservices** architecture ready -- **Container Orchestration** support +- **User**: Authentication, profile data, and role management +- **Project**: Environmental project lifecycle management +- **BaseEntity**: Common audit fields and lifecycle management +- **AuditLog**: System activity tracking and compliance + +### Data Relationships +- **User ↔ Project**: One-to-Many (User can manage multiple projects) +- **Project ↔ AuditLog**: One-to-Many (Project has multiple audit entries) +- **User ↔ Role**: Many-to-Many (Future enhancement for complex role management) + +### Database Features +- **Connection Pooling**: HikariCP for optimal performance +- **Transaction Management**: ACID compliance with proper isolation levels +- **Audit Trail**: Automatic tracking of entity changes +- **Soft Deletes**: Logical deletion with isActive flag + +## 🔄 Communication Patterns + +### REST API Communication +- **Synchronous Communication**: HTTP/HTTPS for client-server interaction +- **API Versioning**: URL-based versioning (`/api/v1/`) +- **Content Negotiation**: JSON request/response format +- **HTTP Status Codes**: Standard REST status codes + +### Internal Service Communication +- **Direct Method Calls**: Within the same application +- **Repository Pattern**: Data access abstraction +- **Service Layer**: Business logic encapsulation +- **Transaction Management**: Declarative transaction handling + +### Cache Communication +- **Redis Integration**: Session management and frequently accessed data +- **Cache Patterns**: Write-through, cache-aside, TTL-based expiration +- **Cache Strategies**: Multi-level caching approach + +## 📊 Performance & Scalability + +### Performance Optimization +- **Database Indexing**: Optimized query performance +- **Connection Pooling**: HikariCP configuration +- **Caching Strategy**: Multi-level caching approach +- **Async Processing**: Non-blocking operations + +### Scalability Features +- **Horizontal Scaling**: Stateless design with JWT authentication +- **Load Balancing**: Nginx round-robin distribution +- **Database Scaling**: Read replicas and connection pooling +- **Cache Scaling**: Redis cluster support + +### Resource Management +- **Memory Management**: JVM tuning and monitoring +- **CPU Optimization**: Thread pool configuration +- **I/O Optimization**: Database query optimization +- **Network Optimization**: Connection reuse and compression + +## 🚀 Deployment Architecture + +### Container Architecture +- **Docker Compose**: Multi-container orchestration +- **Service Dependencies**: Proper startup ordering +- **Volume Management**: Persistent data storage +- **Network Isolation**: Secure container communication + +### Environment Support +- **Development**: Local Docker with H2 database +- **Production**: PostgreSQL with monitoring stack +- **Configuration**: Environment-specific properties +- **Health Checks**: Comprehensive health monitoring + +### Monitoring & Observability +- **Metrics Collection**: Spring Boot Actuator + Prometheus +- **Logging**: Structured logging with correlation IDs +- **Health Checks**: Liveness and readiness probes +- **Alerting**: Performance and error rate monitoring + +## 🔧 Development Guidelines + +### Code Organization +- **Package Structure**: Domain-driven package organization +- **Naming Conventions**: Clear and descriptive naming +- **Documentation**: Comprehensive JavaDoc and README files +- **Code Reviews**: Mandatory peer review process + +### Testing Strategy +- **Unit Tests**: Service and repository layer testing +- **Integration Tests**: API endpoint testing +- **Test Coverage**: Minimum 80% code coverage +- **Test Data**: Isolated test data management + +### Security Guidelines +- **Input Validation**: Comprehensive request validation +- **Authentication**: Secure token management +- **Authorization**: Principle of least privilege +- **Data Protection**: Encryption at rest and in transit + +--- + +## 📖 Quick Start + +1. **Read the Architecture**: Start with [ARCHITECTURE.md](./ARCHITECTURE.md) for comprehensive system overview +2. **Understand Communication**: Review [COMMUNICATION_PATTERNS.md](./COMMUNICATION_PATTERNS.md) for interaction patterns +3. **View Diagrams**: Explore the [diagrams](./diagrams/) directory for visual representations +4. **Deploy the System**: Follow the deployment guides in `/docs/deployment/` + +## 🔄 Architecture Evolution + +This architecture is designed to evolve with the system: +- **Microservices Ready**: Can be split into microservices when needed +- **Event-Driven**: Ready for event-driven architecture patterns +- **Cloud Native**: Compatible with cloud deployment strategies +- **API-First**: Designed for API-first development approach + +For detailed implementation information, refer to the individual component documentation and the comprehensive architecture documents in this directory. diff --git a/docs/architecture/diagrams/application-architecture.md b/docs/architecture/diagrams/application-architecture.md new file mode 100644 index 0000000..b8116e9 --- /dev/null +++ b/docs/architecture/diagrams/application-architecture.md @@ -0,0 +1,200 @@ +# Application Architecture Diagrams + +## Layered Architecture Detail + +```mermaid +graph TB + subgraph "Presentation Layer" + CONTROLLERS[REST Controllers] + DTO[Data Transfer Objects] + VALIDATION[Input Validation] + EXCEPTION[Exception Handling] + end + + subgraph "Business Layer" + SERVICES[Business Services] + BUSINESS_LOGIC[Business Rules] + TRANSACTIONS[Transaction Management] + end + + subgraph "Data Access Layer" + REPOSITORIES[JPA Repositories] + ENTITIES[Domain Entities] + QUERIES[Custom Queries] + end + + subgraph "Infrastructure Layer" + CONFIG[Configuration] + SECURITY[Security Config] + CACHE[Cache Layer] + end + + CONTROLLERS --> SERVICES + DTO --> ENTITIES + VALIDATION --> SERVICES + EXCEPTION --> CONTROLLERS + + SERVICES --> REPOSITORIES + BUSINESS_LOGIC --> SERVICES + TRANSACTIONS --> SERVICES + + REPOSITORIES --> ENTITIES + QUERIES --> REPOSITORIES + + CONFIG --> SERVICES + SECURITY --> CONTROLLERS + CACHE --> REPOSITORIES + + classDef presentation fill:#e3f2fd + classDef business fill:#e8f5e8 + classDef data fill:#fff3e0 + classDef infra fill:#f3e5f5 + + class CONTROLLERS,DTO,VALIDATION,EXCEPTION presentation + class SERVICES,BUSINESS_LOGIC,TRANSACTIONS business + class REPOSITORIES,ENTITIES,QUERIES data + class CONFIG,SECURITY,CACHE infra +``` + +## Domain Model Relationships + +```mermaid +erDiagram + USER { + bigint id PK + string username UK + string email UK + string password + string first_name + string last_name + enum role + boolean is_enabled + timestamp created_at + timestamp updated_at + string created_by + string updated_by + boolean is_active + } + + PROJECT { + bigint id PK + string name + text description + enum category + enum status + date start_date + date end_date + decimal budget + decimal actual_cost + string location + string coordinates + integer impact_score + integer sustainability_rating + bigint manager_id FK + integer team_size + boolean is_public + timestamp created_at + timestamp updated_at + string created_by + string updated_by + boolean is_active + } + + AUDIT_LOG { + bigint id PK + string entity_type + bigint entity_id + string action + json old_values + json new_values + string user_id + timestamp created_at + } + + USER ||--o{ PROJECT : manages + PROJECT ||--o{ AUDIT_LOG : tracked_by + USER ||--o{ AUDIT_LOG : performed_by +``` + +## Request Processing Flow + +```mermaid +flowchart TD + START([HTTP Request]) --> NGINX[Nginx Proxy] + NGINX --> SECURITY{Authentication
Required?} + + SECURITY -->|Yes| JWT[JWT Validation] + SECURITY -->|No| CONTROLLER[Controller Layer] + + JWT -->|Valid| CONTROLLER + JWT -->|Invalid| UNAUTHORIZED[401 Unauthorized] + + CONTROLLER --> VALIDATE[Input Validation] + VALIDATE -->|Valid| SERVICE[Service Layer] + VALIDATE -->|Invalid| BAD_REQUEST[400 Bad Request] + + SERVICE --> BUSINESS[Business Logic] + BUSINESS --> REPOSITORY[Repository Layer] + + REPOSITORY --> CACHE{Cache Check} + CACHE -->|Hit| CACHE_DATA[Return Cached Data] + CACHE -->|Miss| DATABASE[Database Query] + + DATABASE --> UPDATE_CACHE[Update Cache] + UPDATE_CACHE --> RESPONSE[Build Response] + CACHE_DATA --> RESPONSE + + RESPONSE --> DTO[DTO Transformation] + DTO --> JSON[JSON Response] + JSON --> CLIENT[Client] + + UNAUTHORIZED --> CLIENT + BAD_REQUEST --> CLIENT + + classDef start fill:#e8f5e8 + classDef process fill:#e3f2fd + classDef decision fill:#fff3e0 + classDef error fill:#ffebee + classDef end fill:#f3e5f5 + + class START start + class NGINX,CONTROLLER,SERVICE,REPOSITORY,DATABASE,RESPONSE,DTO,JSON process + class SECURITY,VALIDATE,CACHE decision + class UNAUTHORIZED,BAD_REQUEST error + class CLIENT end +``` + +## Security Architecture Flow + +```mermaid +sequenceDiagram + participant Client + participant Nginx + participant SecurityFilter + participant AuthService + participant UserService + participant Database + + Client->>Nginx: Login Request (username/password) + Nginx->>SecurityFilter: Forward Request + SecurityFilter->>AuthService: Validate Credentials + AuthService->>UserService: Find User by Username + UserService->>Database: Query User + Database-->>UserService: Return User Data + UserService-->>AuthService: User Entity + AuthService->>AuthService: Verify Password (BCrypt) + AuthService->>AuthService: Generate JWT Token + AuthService-->>SecurityFilter: JWT Token + SecurityFilter-->>Nginx: Token Response + Nginx-->>Client: JWT Token + + Note over Client,Database: Subsequent Requests + + Client->>Nginx: API Request (with JWT) + Nginx->>SecurityFilter: Forward with Token + SecurityFilter->>SecurityFilter: Validate JWT + SecurityFilter->>SecurityFilter: Extract User Claims + SecurityFilter-->>Nginx: Authorized Request + Nginx->>Nginx: Process Request + Nginx-->>Client: API Response +``` diff --git a/docs/architecture/diagrams/data-flow.md b/docs/architecture/diagrams/data-flow.md new file mode 100644 index 0000000..b5a9602 --- /dev/null +++ b/docs/architecture/diagrams/data-flow.md @@ -0,0 +1,278 @@ +# Data Flow Architecture Diagrams + +## User Registration Flow + +```mermaid +sequenceDiagram + participant Client + participant Nginx + participant UserController + participant UserService + participant PasswordEncoder + participant UserRepository + participant PostgreSQL + participant Redis + + Client->>Nginx: POST /api/users (User Data) + Nginx->>UserController: Forward Request + UserController->>UserController: Validate Input (DTO) + UserController->>UserService: createUser(user) + + UserService->>UserRepository: existsByUsername(username) + UserRepository->>PostgreSQL: SELECT username FROM users + PostgreSQL-->>UserRepository: Result + UserRepository-->>UserService: false (not exists) + + UserService->>UserRepository: existsByEmail(email) + UserRepository->>PostgreSQL: SELECT email FROM users + PostgreSQL-->>UserRepository: Result + UserRepository-->>UserService: false (not exists) + + UserService->>PasswordEncoder: encode(password) + PasswordEncoder-->>UserService: hashedPassword + + UserService->>UserRepository: save(user) + UserRepository->>PostgreSQL: INSERT INTO users + PostgreSQL-->>UserRepository: Saved User + UserRepository-->>UserService: User Entity + + UserService->>Redis: cacheUser(user) + Redis-->>UserService: Cached + + UserService-->>UserController: Created User + UserController-->>Nginx: 201 Created + User Data + Nginx-->>Client: HTTP Response +``` + +## Project Creation Flow + +```mermaid +sequenceDiagram + participant Client + participant Nginx + participant ProjectController + participant ProjectService + participant UserService + participant ProjectRepository + participant AuditService + participant PostgreSQL + participant Redis + + Client->>Nginx: POST /api/projects (Project Data + JWT) + Nginx->>ProjectController: Forward Request + ProjectController->>ProjectController: Validate JWT Token + ProjectController->>ProjectController: Validate Input (DTO) + ProjectController->>ProjectService: createProject(project, userId) + + ProjectService->>UserService: getUserById(userId) + UserService->>Redis: getCachedUser(userId) + alt Cache Hit + Redis-->>UserService: Cached User + else Cache Miss + UserService->>PostgreSQL: SELECT * FROM users WHERE id = ? + PostgreSQL-->>UserService: User Data + UserService->>Redis: cacheUser(user) + end + UserService-->>ProjectService: User Entity + + ProjectService->>ProjectService: Validate Business Rules + ProjectService->>ProjectRepository: save(project) + ProjectRepository->>PostgreSQL: INSERT INTO projects + PostgreSQL-->>ProjectRepository: Saved Project + ProjectRepository-->>ProjectService: Project Entity + + ProjectService->>AuditService: logProjectCreation(project, user) + AuditService->>PostgreSQL: INSERT INTO audit_logs + PostgreSQL-->>AuditService: Logged + + ProjectService->>Redis: cacheProject(project) + Redis-->>ProjectService: Cached + + ProjectService-->>ProjectController: Created Project + ProjectController-->>Nginx: 201 Created + Project Data + Nginx-->>Client: HTTP Response +``` + +## Authentication Flow + +```mermaid +sequenceDiagram + participant Client + participant Nginx + participant AuthController + participant AuthService + participant UserService + participant PasswordEncoder + participant JwtUtils + participant PostgreSQL + participant Redis + + Client->>Nginx: POST /api/auth/login (credentials) + Nginx->>AuthController: Forward Request + AuthController->>AuthController: Validate Input + AuthController->>AuthService: authenticate(username, password) + + AuthService->>UserService: getUserByUsername(username) + UserService->>Redis: getCachedUser(username) + alt Cache Hit + Redis-->>UserService: Cached User + else Cache Miss + UserService->>PostgreSQL: SELECT * FROM users WHERE username = ? + PostgreSQL-->>UserService: User Data + UserService->>Redis: cacheUser(user) + end + UserService-->>AuthService: User Entity + + AuthService->>AuthService: Check if user is enabled + AuthService->>PasswordEncoder: matches(password, user.password) + PasswordEncoder-->>AuthService: true/false + + alt Password Valid + AuthService->>JwtUtils: generateToken(user) + JwtUtils-->>AuthService: JWT Token + AuthService->>Redis: cacheUserSession(user, token) + Redis-->>AuthService: Session Cached + AuthService-->>AuthController: AuthResponse (token, user) + AuthController-->>Nginx: 200 OK + Token + else Password Invalid + AuthService-->>AuthController: Authentication Failed + AuthController-->>Nginx: 401 Unauthorized + end + + Nginx-->>Client: HTTP Response +``` + +## Data Synchronization Flow + +```mermaid +graph TB + subgraph "Application Layer" + SERVICE[Service Layer] + CACHE_MANAGER[Cache Manager] + end + + subgraph "Cache Layer" + REDIS[Redis Cache
Session Data
Frequently Accessed Data] + end + + subgraph "Database Layer" + POSTGRES[PostgreSQL
Master Database
Persistent Storage] + end + + subgraph "Cache Strategies" + WRITE_THROUGH[Write-Through
User Sessions] + CACHE_ASIDE[Cache-Aside
Project Data] + TTL[TTL Expiration
Temporary Data] + end + + SERVICE --> CACHE_MANAGER + CACHE_MANAGER --> REDIS + CACHE_MANAGER --> POSTGRES + + REDIS --> WRITE_THROUGH + REDIS --> CACHE_ASIDE + REDIS --> TTL + + classDef app fill:#e8f5e8 + classDef cache fill:#fff3e0 + classDef db fill:#e3f2fd + classDef strategy fill:#fce4ec + + class SERVICE,CACHE_MANAGER app + class REDIS cache + class POSTGRES db + class WRITE_THROUGH,CACHE_ASIDE,TTL strategy +``` + +## Error Handling Flow + +```mermaid +flowchart TD + START([Request]) --> CONTROLLER[Controller] + CONTROLLER --> VALIDATION{Input Valid?} + + VALIDATION -->|No| VALIDATION_ERROR[ValidationException] + VALIDATION -->|Yes| SERVICE[Service Layer] + + SERVICE --> BUSINESS_LOGIC{Business Rules
Valid?} + BUSINESS_LOGIC -->|No| BUSINESS_ERROR[BusinessException] + BUSINESS_LOGIC -->|Yes| REPOSITORY[Repository] + + REPOSITORY --> DATABASE{Database
Operation} + DATABASE -->|Success| SUCCESS[Success Response] + DATABASE -->|Constraint Violation| CONSTRAINT_ERROR[DataIntegrityException] + DATABASE -->|Connection Error| CONNECTION_ERROR[DataAccessException] + DATABASE -->|Not Found| NOT_FOUND[EntityNotFoundException] + + VALIDATION_ERROR --> GLOBAL_HANDLER[GlobalExceptionHandler] + BUSINESS_ERROR --> GLOBAL_HANDLER + CONSTRAINT_ERROR --> GLOBAL_HANDLER + CONNECTION_ERROR --> GLOBAL_HANDLER + NOT_FOUND --> GLOBAL_HANDLER + + GLOBAL_HANDLER --> LOG_ERROR[Log Error] + LOG_ERROR --> STRUCTURED_RESPONSE[Structured Error Response] + STRUCTURED_RESPONSE --> CLIENT[Client] + + SUCCESS --> CLIENT + + classDef start fill:#e8f5e8 + classDef process fill:#e3f2fd + classDef decision fill:#fff3e0 + classDef error fill:#ffebee + classDef success fill:#e8f5e8 + classDef end fill:#f3e5f5 + + class START start + class CONTROLLER,SERVICE,REPOSITORY process + class VALIDATION,BUSINESS_LOGIC,DATABASE decision + class VALIDATION_ERROR,BUSINESS_ERROR,CONSTRAINT_ERROR,CONNECTION_ERROR,NOT_FOUND error + class SUCCESS success + class GLOBAL_HANDLER,LOG_ERROR,STRUCTURED_RESPONSE,CLIENT end +``` + +## Monitoring Data Flow + +```mermaid +graph TB + subgraph "Application Metrics" + ACTUATOR[Spring Boot Actuator
Health, Metrics, Info] + CUSTOM_METRICS[Custom Business Metrics
Project Count, User Activity] + end + + subgraph "Infrastructure Metrics" + JVM_METRICS[JVM Metrics
Memory, CPU, GC] + DB_METRICS[Database Metrics
Connections, Queries] + CACHE_METRICS[Cache Metrics
Hit Rate, Size] + end + + subgraph "Monitoring Stack" + PROMETHEUS[Prometheus
Metrics Collection
Time Series DB] + GRAFANA[Grafana
Visualization
Dashboards] + end + + subgraph "Alerting" + ALERT_RULES[Alert Rules
Thresholds
Conditions] + NOTIFICATIONS[Notifications
Email, Slack
PagerDuty] + end + + ACTUATOR --> PROMETHEUS + CUSTOM_METRICS --> PROMETHEUS + JVM_METRICS --> PROMETHEUS + DB_METRICS --> PROMETHEUS + CACHE_METRICS --> PROMETHEUS + + PROMETHEUS --> GRAFANA + PROMETHEUS --> ALERT_RULES + ALERT_RULES --> NOTIFICATIONS + + classDef app fill:#e8f5e8 + classDef infra fill:#fff3e0 + classDef monitor fill:#e3f2fd + classDef alert fill:#fce4ec + + class ACTUATOR,CUSTOM_METRICS app + class JVM_METRICS,DB_METRICS,CACHE_METRICS infra + class PROMETHEUS,GRAFANA monitor + class ALERT_RULES,NOTIFICATIONS alert +``` diff --git a/docs/architecture/diagrams/deployment-architecture.md b/docs/architecture/diagrams/deployment-architecture.md new file mode 100644 index 0000000..a87bded --- /dev/null +++ b/docs/architecture/diagrams/deployment-architecture.md @@ -0,0 +1,273 @@ +# Deployment Architecture Diagrams + +## Docker Container Architecture + +```mermaid +graph TB + subgraph "Docker Network: greencode-network (172.20.0.0/16)" + subgraph "Application Containers" + BACKEND[greencode-backend
Port 8080
Spring Boot App] + NGINX[greencode-nginx
Port 80/443
Reverse Proxy] + end + + subgraph "Data Containers" + POSTGRES[greencode-postgres
Port 5432
PostgreSQL 15] + REDIS[greencode-redis
Port 6379
Redis 7] + end + + subgraph "Monitoring Containers" + PROMETHEUS[greencode-prometheus
Port 9090
Metrics Collection] + GRAFANA[greencode-grafana
Port 3000
Dashboards] + end + + subgraph "Management Containers" + ADMINER[greencode-adminer
Port 8081
DB Management] + end + end + + subgraph "External Access" + INTERNET[Internet Traffic] + ADMIN[Admin Access] + end + + subgraph "Persistent Volumes" + POSTGRES_DATA[postgres_data
Database Storage] + REDIS_DATA[redis_data
Cache Storage] + PROMETHEUS_DATA[prometheus_data
Metrics Storage] + GRAFANA_DATA[grafana_data
Dashboard Config] + APP_LOGS[./logs
Application Logs] + APP_DATA[./data
Application Data] + end + + INTERNET --> NGINX + ADMIN --> ADMINER + ADMIN --> GRAFANA + + NGINX --> BACKEND + BACKEND --> POSTGRES + BACKEND --> REDIS + BACKEND --> PROMETHEUS + + PROMETHEUS --> GRAFANA + ADMINER --> POSTGRES + + POSTGRES --> POSTGRES_DATA + REDIS --> REDIS_DATA + PROMETHEUS --> PROMETHEUS_DATA + GRAFANA --> GRAFANA_DATA + BACKEND --> APP_LOGS + BACKEND --> APP_DATA + + classDef app fill:#e8f5e8 + classDef data fill:#fff3e0 + classDef monitor fill:#fce4ec + classDef tools fill:#f1f8e9 + classDef external fill:#e3f2fd + classDef storage fill:#f3e5f5 + + class BACKEND,NGINX app + class POSTGRES,REDIS data + class PROMETHEUS,GRAFANA monitor + class ADMINER tools + class INTERNET,ADMIN external + class POSTGRES_DATA,REDIS_DATA,PROMETHEUS_DATA,GRAFANA_DATA,APP_LOGS,APP_DATA storage +``` + +## Environment Configuration + +```mermaid +graph LR + subgraph "Development Environment" + DEV_COMPOSE[docker-compose.yml
H2 Database
Hot Reload] + DEV_CONFIG[application-dev.yml
Debug Logging
H2 Console] + end + + subgraph "Production Environment" + PROD_COMPOSE[docker-compose.prod.yml
PostgreSQL
Optimized Settings] + PROD_CONFIG[application-prod.yml
Production Logging
Security Hardened] + end + + subgraph "Docker Environment" + DOCKER_CONFIG[application-docker.yml
Container Settings
External Services] + end + + DEV_COMPOSE --> DEV_CONFIG + PROD_COMPOSE --> PROD_CONFIG + PROD_COMPOSE --> DOCKER_CONFIG + + classDef dev fill:#e8f5e8 + classDef prod fill:#ffebee + classDef docker fill:#e3f2fd + + class DEV_COMPOSE,DEV_CONFIG dev + class PROD_COMPOSE,PROD_CONFIG prod + class DOCKER_CONFIG docker +``` + +## Network Architecture + +```mermaid +graph TB + subgraph "External Network" + INTERNET[Internet] + LOAD_BALANCER[Load Balancer
Optional] + end + + subgraph "Docker Network: greencode-network" + subgraph "Frontend Tier" + NGINX[Nginx
172.20.0.10
Port 80/443] + end + + subgraph "Application Tier" + BACKEND1[Backend Instance 1
172.20.0.20
Port 8080] + BACKEND2[Backend Instance 2
172.20.0.21
Port 8080] + end + + subgraph "Data Tier" + POSTGRES[PostgreSQL
172.20.0.30
Port 5432] + REDIS[Redis
172.20.0.31
Port 6379] + end + + subgraph "Monitoring Tier" + PROMETHEUS[Prometheus
172.20.0.40
Port 9090] + GRAFANA[Grafana
172.20.0.41
Port 3000] + end + end + + INTERNET --> LOAD_BALANCER + LOAD_BALANCER --> NGINX + INTERNET --> NGINX + + NGINX --> BACKEND1 + NGINX --> BACKEND2 + + BACKEND1 --> POSTGRES + BACKEND1 --> REDIS + BACKEND2 --> POSTGRES + BACKEND2 --> REDIS + + BACKEND1 --> PROMETHEUS + BACKEND2 --> PROMETHEUS + PROMETHEUS --> GRAFANA + + classDef external fill:#e3f2fd + classDef frontend fill:#e8f5e8 + classDef app fill:#fff3e0 + classDef data fill:#fce4ec + classDef monitor fill:#f1f8e9 + + class INTERNET,LOAD_BALANCER external + class NGINX frontend + class BACKEND1,BACKEND2 app + class POSTGRES,REDIS data + class PROMETHEUS,GRAFANA monitor +``` + +## Scaling Architecture + +```mermaid +graph TB + subgraph "Load Balancer Layer" + LB[Load Balancer
Round Robin
Health Checks] + end + + subgraph "Application Layer (Scalable)" + APP1[Backend Instance 1
CPU: 2 cores
RAM: 4GB] + APP2[Backend Instance 2
CPU: 2 cores
RAM: 4GB] + APP3[Backend Instance 3
CPU: 2 cores
RAM: 4GB] + APP_N[Backend Instance N
Auto-scaling] + end + + subgraph "Database Layer" + POSTGRES_MASTER[PostgreSQL Master
Write Operations] + POSTGRES_REPLICA1[PostgreSQL Replica 1
Read Operations] + POSTGRES_REPLICA2[PostgreSQL Replica 2
Read Operations] + end + + subgraph "Cache Layer" + REDIS_CLUSTER[Redis Cluster
High Availability
Data Partitioning] + end + + LB --> APP1 + LB --> APP2 + LB --> APP3 + LB --> APP_N + + APP1 --> POSTGRES_MASTER + APP1 --> POSTGRES_REPLICA1 + APP1 --> REDIS_CLUSTER + + APP2 --> POSTGRES_MASTER + APP2 --> POSTGRES_REPLICA2 + APP2 --> REDIS_CLUSTER + + APP3 --> POSTGRES_MASTER + APP3 --> POSTGRES_REPLICA1 + APP3 --> REDIS_CLUSTER + + APP_N --> POSTGRES_MASTER + APP_N --> POSTGRES_REPLICA2 + APP_N --> REDIS_CLUSTER + + POSTGRES_MASTER --> POSTGRES_REPLICA1 + POSTGRES_MASTER --> POSTGRES_REPLICA2 + + classDef lb fill:#e3f2fd + classDef app fill:#e8f5e8 + classDef db fill:#fff3e0 + classDef cache fill:#fce4ec + + class LB lb + class APP1,APP2,APP3,APP_N app + class POSTGRES_MASTER,POSTGRES_REPLICA1,POSTGRES_REPLICA2 db + class REDIS_CLUSTER cache +``` + +## CI/CD Pipeline Architecture + +```mermaid +flowchart LR + subgraph "Source Control" + GIT[Git Repository
GitHub/GitLab] + end + + subgraph "CI/CD Pipeline" + BUILD[Maven Build
Unit Tests
Code Quality] + CONTAINER[Docker Build
Multi-stage Build
Security Scan] + TEST[Integration Tests
Test Containers
API Tests] + DEPLOY[Deploy to Staging
Smoke Tests
Performance Tests] + end + + subgraph "Environments" + DEV[Development
Local Docker
H2 Database] + STAGING[Staging
Production-like
PostgreSQL] + PROD[Production
High Availability
Monitoring] + end + + subgraph "Monitoring" + METRICS[Application Metrics
Business Metrics
Infrastructure Metrics] + ALERTS[Alerting Rules
Notification Channels
Escalation Policies] + end + + GIT --> BUILD + BUILD --> CONTAINER + CONTAINER --> TEST + TEST --> DEPLOY + + DEPLOY --> DEV + DEPLOY --> STAGING + DEPLOY --> PROD + + PROD --> METRICS + METRICS --> ALERTS + + classDef source fill:#e8f5e8 + classDef pipeline fill:#e3f2fd + classDef env fill:#fff3e0 + classDef monitor fill:#fce4ec + + class GIT source + class BUILD,CONTAINER,TEST,DEPLOY pipeline + class DEV,STAGING,PROD env + class METRICS,ALERTS monitor +``` diff --git a/docs/architecture/diagrams/system-overview.md b/docs/architecture/diagrams/system-overview.md new file mode 100644 index 0000000..10c0fe3 --- /dev/null +++ b/docs/architecture/diagrams/system-overview.md @@ -0,0 +1,116 @@ +# System Overview Architecture + +## High-Level System Architecture + +```mermaid +graph TB + subgraph "Client Layer" + WEB[Web Application] + MOBILE[Mobile App] + API_CLIENT[API Clients] + end + + subgraph "Load Balancer & Proxy" + NGINX[Nginx Reverse Proxy
Port 80/443] + end + + subgraph "Application Layer" + BACKEND[GreenCode Backend
Spring Boot
Port 8080] + end + + subgraph "Data Layer" + POSTGRES[(PostgreSQL
Port 5432)] + REDIS[(Redis Cache
Port 6379)] + end + + subgraph "Monitoring Stack" + PROMETHEUS[Prometheus
Port 9090] + GRAFANA[Grafana
Port 3000] + end + + subgraph "Management Tools" + ADMINER[Adminer
Port 8081] + end + + WEB --> NGINX + MOBILE --> NGINX + API_CLIENT --> NGINX + + NGINX --> BACKEND + + BACKEND --> POSTGRES + BACKEND --> REDIS + + BACKEND --> PROMETHEUS + PROMETHEUS --> GRAFANA + + ADMINER --> POSTGRES + + classDef client fill:#e1f5fe + classDef proxy fill:#f3e5f5 + classDef app fill:#e8f5e8 + classDef data fill:#fff3e0 + classDef monitor fill:#fce4ec + classDef tools fill:#f1f8e9 + + class WEB,MOBILE,API_CLIENT client + class NGINX proxy + class BACKEND app + class POSTGRES,REDIS data + class PROMETHEUS,GRAFANA monitor + class ADMINER tools +``` + +## Component Interaction Flow + +```mermaid +sequenceDiagram + participant Client + participant Nginx + participant Backend + participant Redis + participant PostgreSQL + + Client->>Nginx: HTTP Request + Nginx->>Backend: Forward Request + Backend->>Redis: Check Cache + alt Cache Hit + Redis-->>Backend: Return Cached Data + else Cache Miss + Backend->>PostgreSQL: Query Database + PostgreSQL-->>Backend: Return Data + Backend->>Redis: Update Cache + end + Backend-->>Nginx: JSON Response + Nginx-->>Client: HTTP Response +``` + +## Service Dependencies + +```mermaid +graph LR + subgraph "Core Services" + BACKEND[GreenCode Backend] + POSTGRES[PostgreSQL] + REDIS[Redis] + end + + subgraph "Infrastructure" + NGINX[Nginx] + PROMETHEUS[Prometheus] + GRAFANA[Grafana] + ADMINER[Adminer] + end + + BACKEND -->|depends on| POSTGRES + BACKEND -->|depends on| REDIS + NGINX -->|depends on| BACKEND + GRAFANA -->|depends on| PROMETHEUS + ADMINER -->|depends on| POSTGRES + + classDef core fill:#e8f5e8 + classDef infra fill:#f3e5f5 + + class BACKEND,POSTGRES,REDIS core + class NGINX,PROMETHEUS,GRAFANA,ADMINER infra +```