init bootstrap
This commit is contained in:
423
docs/ARCHITECTURE.md
Normal file
423
docs/ARCHITECTURE.md
Normal file
@@ -0,0 +1,423 @@
|
||||
# Architecture Documentation
|
||||
|
||||
## Overview
|
||||
|
||||
This document describes the architecture of the Bootstrap App, which follows clean architecture principles with clear separation of concerns, dependency injection, and modern security practices.
|
||||
|
||||
## Architecture Principles
|
||||
|
||||
### Clean Architecture
|
||||
The application follows Uncle Bob's Clean Architecture principles:
|
||||
- **Independence of Frameworks**: The architecture doesn't depend on specific frameworks
|
||||
- **Testability**: Business rules can be tested without UI, database, or external services
|
||||
- **Independence of UI**: The UI can change without changing the business rules
|
||||
- **Independence of Database**: Business rules are not bound to the database
|
||||
- **Independence of External Services**: Business rules know nothing about the outside world
|
||||
|
||||
### SOLID Principles
|
||||
- **Single Responsibility**: Each class/module has one reason to change
|
||||
- **Open/Closed**: Open for extension, closed for modification
|
||||
- **Liskov Substitution**: Objects should be replaceable with instances of their subtypes
|
||||
- **Interface Segregation**: Many client-specific interfaces are better than one general-purpose interface
|
||||
- **Dependency Inversion**: Depend on abstractions, not concretions
|
||||
|
||||
## Layer Architecture
|
||||
|
||||
### 1. Presentation Layer (`controller/`)
|
||||
**Responsibility**: Handle HTTP requests and responses
|
||||
- Input validation and sanitization
|
||||
- Request/response mapping
|
||||
- Error handling and status codes
|
||||
- Authentication and authorization checks
|
||||
|
||||
**Components**:
|
||||
- Controllers for each domain
|
||||
- Middleware for cross-cutting concerns
|
||||
- Request/response DTOs
|
||||
|
||||
**Dependencies**: Service Layer
|
||||
|
||||
### 2. Business Logic Layer (`service/`)
|
||||
**Responsibility**: Implement business rules and orchestrate operations
|
||||
- Business rule validation
|
||||
- Transaction management
|
||||
- Cross-domain operations
|
||||
- Business logic orchestration
|
||||
|
||||
**Components**:
|
||||
- Service classes for each domain
|
||||
- Business rule validators
|
||||
- Transaction coordinators
|
||||
|
||||
**Dependencies**: Repository Layer, External Services
|
||||
|
||||
### 3. Data Access Layer (`repository/`)
|
||||
**Responsibility**: Data persistence and retrieval
|
||||
- Database operations
|
||||
- Query optimization
|
||||
- Data mapping
|
||||
- Cache management
|
||||
|
||||
**Components**:
|
||||
- Repository interfaces and implementations
|
||||
- Database models
|
||||
- Query builders
|
||||
|
||||
**Dependencies**: Database, Cache
|
||||
|
||||
### 4. Domain Layer (`model/`)
|
||||
**Responsibility**: Core business entities and rules
|
||||
- Domain entities
|
||||
- Value objects
|
||||
- Domain services
|
||||
- Business rule definitions
|
||||
|
||||
**Components**:
|
||||
- Entity models
|
||||
- Validation rules
|
||||
- Domain constants
|
||||
- Business exceptions
|
||||
|
||||
**Dependencies**: None (should be isolated)
|
||||
|
||||
### 5. Infrastructure Layer (`utl/`)
|
||||
**Responsibility**: External concerns and utilities
|
||||
- Database configuration
|
||||
- Logging
|
||||
- Security utilities
|
||||
- Configuration management
|
||||
- External service integrations
|
||||
|
||||
**Components**:
|
||||
- Database connection and migration
|
||||
- Logging infrastructure
|
||||
- Security middleware
|
||||
- Configuration loaders
|
||||
- Utility functions
|
||||
|
||||
## Component Interaction Flow
|
||||
|
||||
```
|
||||
HTTP Request
|
||||
↓
|
||||
[Middleware Stack] ← Security, Logging, CORS
|
||||
↓
|
||||
[Controller] ← Request handling, validation
|
||||
↓
|
||||
[Service] ← Business logic, orchestration
|
||||
↓
|
||||
[Repository] ← Data access, persistence
|
||||
↓
|
||||
[Database/Cache] ← Data storage
|
||||
```
|
||||
|
||||
## Dependency Injection
|
||||
|
||||
The application uses Uber Dig for dependency injection, providing:
|
||||
- **Loose Coupling**: Components depend on interfaces, not implementations
|
||||
- **Testability**: Easy to mock dependencies for testing
|
||||
- **Configuration**: Centralized dependency configuration
|
||||
- **Lifecycle Management**: Automatic instance management
|
||||
|
||||
### DI Container Structure
|
||||
```go
|
||||
// Database and core services
|
||||
di.Provide(func() *gorm.DB { ... })
|
||||
di.Provide(NewCache)
|
||||
|
||||
// Repositories
|
||||
di.Provide(NewUserRepository)
|
||||
di.Provide(NewRoleRepository)
|
||||
// ...
|
||||
|
||||
// Services
|
||||
di.Provide(NewUserService)
|
||||
di.Provide(NewAuthService)
|
||||
// ...
|
||||
|
||||
// Controllers
|
||||
di.Invoke(NewUserController)
|
||||
di.Invoke(NewAuthController)
|
||||
// ...
|
||||
```
|
||||
|
||||
## Security Architecture
|
||||
|
||||
### Authentication Flow
|
||||
```
|
||||
Client Request
|
||||
↓
|
||||
[CORS Middleware] ← Cross-origin validation
|
||||
↓
|
||||
[Security Headers] ← Security headers injection
|
||||
↓
|
||||
[Rate Limiting] ← Request rate validation
|
||||
↓
|
||||
[JWT Validation] ← Token verification
|
||||
↓
|
||||
[Permission Check] ← Authorization validation
|
||||
↓
|
||||
[Controller] ← Authorized request processing
|
||||
```
|
||||
|
||||
### Security Layers
|
||||
1. **Network Security**: CORS, security headers, HTTPS
|
||||
2. **Authentication**: JWT token validation
|
||||
3. **Authorization**: Role-based access control
|
||||
4. **Input Security**: Sanitization, validation, size limits
|
||||
5. **Audit Security**: Logging, monitoring, alerting
|
||||
|
||||
## Database Architecture
|
||||
|
||||
### Entity Relationships
|
||||
```
|
||||
Users
|
||||
├── UserRoles (Many-to-Many with Roles)
|
||||
├── AuditLogs (One-to-Many)
|
||||
└── SecurityEvents (One-to-Many)
|
||||
|
||||
Roles
|
||||
├── UserRoles (Many-to-Many with Users)
|
||||
└── RolePermissions (Many-to-Many with Permissions)
|
||||
|
||||
Permissions
|
||||
└── RolePermissions (Many-to-Many with Roles)
|
||||
|
||||
SystemConfig (Standalone)
|
||||
```
|
||||
|
||||
### Base Model Pattern
|
||||
All entities inherit from `BaseModel`:
|
||||
```go
|
||||
type BaseModel struct {
|
||||
ID string `json:"id" gorm:"primary_key"`
|
||||
DateCreated time.Time `json:"dateCreated"`
|
||||
DateUpdated time.Time `json:"dateUpdated"`
|
||||
}
|
||||
```
|
||||
|
||||
Benefits:
|
||||
- Consistent ID generation (UUID)
|
||||
- Automatic timestamp management
|
||||
- Uniform audit trail
|
||||
- Simplified queries
|
||||
|
||||
## API Architecture
|
||||
|
||||
### RESTful Design
|
||||
- **Resource-based URLs**: `/api/v1/users/{id}`
|
||||
- **HTTP Methods**: GET, POST, PUT, DELETE, PATCH
|
||||
- **Status Codes**: Appropriate HTTP status codes
|
||||
- **Content Negotiation**: JSON request/response format
|
||||
|
||||
### API Versioning
|
||||
- **URL Versioning**: `/api/v1/`
|
||||
- **Backward Compatibility**: Maintain older versions
|
||||
- **Migration Path**: Clear upgrade documentation
|
||||
|
||||
### Response Format
|
||||
```go
|
||||
type APIResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Data interface{} `json:"data,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
Code int `json:"code,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
### Pagination
|
||||
```go
|
||||
type PaginatedResponse struct {
|
||||
APIResponse
|
||||
Pagination PaginationResponse `json:"pagination"`
|
||||
}
|
||||
```
|
||||
|
||||
## Middleware Architecture
|
||||
|
||||
### Middleware Stack (Order Matters)
|
||||
1. **Recovery**: Panic recovery and logging
|
||||
2. **Security Headers**: OWASP security headers
|
||||
3. **CORS**: Cross-origin resource sharing
|
||||
4. **Rate Limiting**: Request rate limiting
|
||||
5. **Request Logging**: HTTP request/response logging
|
||||
6. **Authentication**: JWT token validation
|
||||
7. **Authorization**: Permission validation
|
||||
8. **Input Validation**: Request sanitization
|
||||
|
||||
### Security Middleware Components
|
||||
- **Rate Limiter**: Token bucket algorithm with IP-based limits
|
||||
- **Input Sanitizer**: XSS protection, SQL injection prevention
|
||||
- **Content Validator**: Content-type and size validation
|
||||
- **User Agent Validator**: Bot detection and blocking
|
||||
|
||||
## Configuration Architecture
|
||||
|
||||
### Configuration Layers
|
||||
1. **Environment Variables**: Runtime configuration
|
||||
2. **Database Config**: Dynamic configuration storage
|
||||
3. **Default Values**: Fallback configuration
|
||||
4. **Validation**: Configuration validation rules
|
||||
|
||||
### Configuration Categories
|
||||
- **Security**: JWT secrets, encryption keys, password policies
|
||||
- **Database**: Connection settings, migration options
|
||||
- **API**: Rate limits, timeouts, CORS settings
|
||||
- **Logging**: Log levels, retention policies
|
||||
- **Features**: Feature flags, service toggles
|
||||
|
||||
## Error Handling Architecture
|
||||
|
||||
### Error Types
|
||||
1. **Business Errors**: Domain rule violations
|
||||
2. **Validation Errors**: Input validation failures
|
||||
3. **System Errors**: Infrastructure failures
|
||||
4. **Security Errors**: Authentication/authorization failures
|
||||
|
||||
### Error Propagation
|
||||
```
|
||||
Controller → Service → Repository
|
||||
↓ ↓ ↓
|
||||
HTTP Business Data
|
||||
Error Error Error
|
||||
```
|
||||
|
||||
### Error Response Format
|
||||
```go
|
||||
type HTTPError struct {
|
||||
Code int `json:"code"`
|
||||
Message string `json:"message"`
|
||||
Details map[string]interface{} `json:"details,omitempty"`
|
||||
}
|
||||
```
|
||||
|
||||
## Logging Architecture
|
||||
|
||||
### Log Levels
|
||||
- **DEBUG**: Detailed information for debugging
|
||||
- **INFO**: General information about application flow
|
||||
- **WARN**: Warning messages for potential issues
|
||||
- **ERROR**: Error messages for failures
|
||||
- **PANIC**: Critical errors that cause application termination
|
||||
|
||||
### Log Categories
|
||||
1. **Application Logs**: General application flow
|
||||
2. **HTTP Logs**: Request/response logging
|
||||
3. **Security Logs**: Authentication, authorization events
|
||||
4. **Audit Logs**: User actions and system changes
|
||||
5. **Performance Logs**: Response times, resource usage
|
||||
|
||||
### Log Format
|
||||
```
|
||||
[TIMESTAMP] LEVEL [CALLER] MESSAGE
|
||||
[2024-01-01 12:00:00] INFO [main.go:42] Starting application
|
||||
```
|
||||
|
||||
## Caching Architecture
|
||||
|
||||
### Cache Layers
|
||||
1. **Application Cache**: In-memory cache for frequently accessed data
|
||||
2. **Database Cache**: GORM query result caching
|
||||
3. **HTTP Cache**: Response caching for static content
|
||||
|
||||
### Cache Strategies
|
||||
- **TTL-based**: Time-to-live expiration
|
||||
- **LRU**: Least recently used eviction
|
||||
- **Size-based**: Memory usage limits
|
||||
- **Manual**: Explicit cache invalidation
|
||||
|
||||
## Testing Architecture
|
||||
|
||||
### Test Layers
|
||||
1. **Unit Tests**: Individual component testing
|
||||
2. **Integration Tests**: Component interaction testing
|
||||
3. **API Tests**: End-to-end API testing
|
||||
4. **Security Tests**: Security vulnerability testing
|
||||
|
||||
### Test Structure
|
||||
```
|
||||
test/
|
||||
├── unit/ # Unit tests
|
||||
├── integration/ # Integration tests
|
||||
├── api/ # API tests
|
||||
├── fixtures/ # Test data
|
||||
└── helpers/ # Test utilities
|
||||
```
|
||||
|
||||
### Mock Strategy
|
||||
- **Interface Mocking**: Mock external dependencies
|
||||
- **Database Mocking**: In-memory database for tests
|
||||
- **HTTP Mocking**: Mock external API calls
|
||||
|
||||
## Scalability Considerations
|
||||
|
||||
### Horizontal Scaling
|
||||
- **Stateless Design**: No server-side session storage
|
||||
- **Database Connection Pooling**: Efficient connection management
|
||||
- **Load Balancer Friendly**: Health checks and graceful shutdown
|
||||
|
||||
### Performance Optimization
|
||||
- **Database Indexing**: Optimized query performance
|
||||
- **Pagination**: Limit result set sizes
|
||||
- **Caching**: Reduce database load
|
||||
- **Compression**: Reduce bandwidth usage
|
||||
|
||||
### Monitoring Points
|
||||
- **Health Endpoints**: Application health status
|
||||
- **Metrics Collection**: Performance metrics
|
||||
- **Log Aggregation**: Centralized logging
|
||||
- **Alert Configuration**: Automated alerting
|
||||
|
||||
## Deployment Architecture
|
||||
|
||||
### Build Process
|
||||
1. **Dependency Resolution**: `go mod download`
|
||||
2. **Code Generation**: Swagger documentation
|
||||
3. **Compilation**: Static binary creation
|
||||
4. **Testing**: Automated test execution
|
||||
5. **Packaging**: Container image creation
|
||||
|
||||
### Deployment Strategies
|
||||
- **Blue-Green**: Zero-downtime deployments
|
||||
- **Rolling**: Gradual instance replacement
|
||||
- **Canary**: Phased traffic migration
|
||||
- **Feature Flags**: Runtime feature control
|
||||
|
||||
### Environment Configuration
|
||||
- **Development**: Local development setup
|
||||
- **Staging**: Production-like testing environment
|
||||
- **Production**: Live application environment
|
||||
- **DR**: Disaster recovery environment
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Threat Model
|
||||
1. **Authentication Bypass**: JWT validation, rate limiting
|
||||
2. **Authorization Escalation**: RBAC, permission validation
|
||||
3. **Data Injection**: Input sanitization, parameterized queries
|
||||
4. **Data Exposure**: Access logging, encryption at rest
|
||||
5. **DoS Attacks**: Rate limiting, request size limits
|
||||
|
||||
### Security Controls
|
||||
- **Input Validation**: All user inputs validated
|
||||
- **Output Encoding**: XSS prevention
|
||||
- **Access Control**: Role-based permissions
|
||||
- **Audit Logging**: All actions logged
|
||||
- **Encryption**: Sensitive data encrypted
|
||||
|
||||
## Future Considerations
|
||||
|
||||
### Planned Enhancements
|
||||
- **Microservices**: Service decomposition
|
||||
- **Event Sourcing**: Event-driven architecture
|
||||
- **CQRS**: Command query responsibility segregation
|
||||
- **GraphQL**: Alternative API interface
|
||||
- **Real-time**: WebSocket support
|
||||
|
||||
### Technology Evolution
|
||||
- **Database**: PostgreSQL migration path
|
||||
- **Cache**: Redis integration
|
||||
- **Messaging**: Event bus implementation
|
||||
- **Search**: Full-text search capabilities
|
||||
- **Analytics**: Business intelligence integration
|
||||
Reference in New Issue
Block a user