File size: 10,207 Bytes
bf9e111 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | # Clean Architecture Refactoring Plan
## Current State Analysis
### API Handlers (`internal/api/handlers/management/`)
The current handlers have several issues:
1. **Tight coupling**: Handlers directly manipulate config, auth, and logging
2. **Mixed concerns**: Business logic mixed with HTTP transport (Gin)
3. **Inconsistent error handling**: Uses `gin.H{"error": ...}` directly
4. **No clear separation**: Domain logic embedded in HTTP handlers
5. **Large files**: `auth_files.go` is ~2200 lines with multiple responsibilities
### Auth Module (`internal/auth/`)
1. **Minimal interface**: Only `TokenStorage` interface defined
2. **Provider-specific logic**: Each provider has its own auth implementation
3. **No unified error types**: Each provider handles errors differently
### Logging Module (`internal/logging/`)
1. **Good interfaces**: `RequestLogger` and `StreamingLogWriter` already defined
2. **Mixed transport concerns**: Some Gin-specific code in logging
3. **Correlation IDs**: Basic request ID support exists but could be enhanced
## Proposed Clean Architecture
### Layer Structure
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Transport Layer β
β (Gin handlers, middleware, routing) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Application Layer β
β (Use cases, DTOs, request/response mapping) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Domain Layer β
β (Domain services, entities, business rules, interfaces) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β Infrastructure Layer β
β (Config persistence, auth storage, file system, HTTP) β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### New Directory Structure
```
internal/
βββ api/
β βββ handlers/ # HTTP transport (thin layer)
β β βββ management/
β β βββ handler.go
β β βββ config_handler.go
β β βββ auth_handler.go
β β βββ logs_handler.go
β βββ middleware/ # HTTP middleware
β βββ auth.go
β βββ logging.go
β βββ error_handler.go
βββ application/ # Application layer (NEW)
β βββ dto/ # Data transfer objects
β β βββ config_dto.go
β β βββ auth_dto.go
β β βββ response_dto.go
β βββ mapper/ # DTO <-> Domain mapping
β β βββ config_mapper.go
β β βββ auth_mapper.go
β βββ usecase/ # Use cases
β βββ config_usecase.go
β βββ auth_usecase.go
β βββ logs_usecase.go
βββ domain/ # Domain layer (NEW)
β βββ entity/ # Domain entities
β β βββ config.go
β β βββ auth.go
β β βββ log_entry.go
β βββ service/ # Domain services (business logic)
β β βββ config_service.go
β β βββ auth_service.go
β β βββ log_service.go
β βββ repository/ # Repository interfaces
β β βββ config_repository.go
β β βββ auth_repository.go
β βββ error/ # Domain errors
β βββ errors.go
βββ infrastructure/ # Infrastructure layer (NEW)
β βββ persistence/ # Repository implementations
β β βββ config_repository.go
β β βββ auth_repository.go
β βββ auth/ # Auth provider implementations
β β βββ provider.go
β β βββ factory.go
β βββ logging/ # Logging infrastructure
β βββ file_logger.go
β βββ structured_logger.go
βββ interfaces/ # Existing - shared interfaces
βββ types.go
```
## Key Components
### 1. Domain Errors (`internal/domain/error/errors.go`)
Standardized error types for the entire application:
```go
package error
type DomainError struct {
Code string
Message string
Cause error
}
func (e *DomainError) Error() string { ... }
// Specific error types
var (
ErrNotFound = &DomainError{Code: "NOT_FOUND", ...}
ErrUnauthorized = &DomainError{Code: "UNAUTHORIZED", ...}
ErrInvalidInput = &DomainError{Code: "INVALID_INPUT", ...}
ErrInternal = &DomainError{Code: "INTERNAL_ERROR", ...}
)
```
### 2. Domain Services
Domain services contain pure business logic, no HTTP concerns:
```go
// internal/domain/service/config_service.go
type ConfigService interface {
GetConfig(ctx context.Context) (*entity.Config, error)
UpdateConfig(ctx context.Context, cfg *entity.Config) error
UpdateField(ctx context.Context, field string, value any) error
ValidateConfig(ctx context.Context, cfg *entity.Config) error
}
// internal/domain/service/auth_service.go
type AuthService interface {
ListAuthFiles(ctx context.Context) ([]*entity.AuthFile, error)
UploadAuthFile(ctx context.Context, file *entity.AuthFile) error
DeleteAuthFile(ctx context.Context, id string) error
RefreshToken(ctx context.Context, id string) (*entity.AuthToken, error)
}
```
### 3. Repository Interfaces
```go
// internal/domain/repository/config_repository.go
type ConfigRepository interface {
Load(ctx context.Context) (*entity.Config, error)
Save(ctx context.Context, cfg *entity.Config) error
Validate(ctx context.Context, cfg *entity.Config) error
}
// internal/domain/repository/auth_repository.go
type AuthRepository interface {
List(ctx context.Context) ([]*entity.AuthFile, error)
GetByID(ctx context.Context, id string) (*entity.AuthFile, error)
Save(ctx context.Context, file *entity.AuthFile) error
Delete(ctx context.Context, id string) error
}
```
### 4. Application Use Cases
Use cases orchestrate domain services for specific operations:
```go
// internal/application/usecase/config_usecase.go
type ConfigUseCase struct {
configService domain.ConfigService
logger logging.Logger
}
func (uc *ConfigUseCase) GetConfig(ctx context.Context) (*dto.ConfigResponse, error) {
cfg, err := uc.configService.GetConfig(ctx)
if err != nil {
uc.logger.Error("failed to get config", err)
return nil, err
}
return mapper.ToConfigResponse(cfg), nil
}
```
### 5. Structured Logging with Correlation IDs
```go
// internal/infrastructure/logging/structured_logger.go
type StructuredLogger struct {
logger *logrus.Logger
}
type LogEntry struct {
Timestamp time.Time
Level string
Message string
CorrelationID string
Service string
Operation string
Fields map[string]interface{}
}
func (l *StructuredLogger) WithCorrelationID(ctx context.Context) *logrus.Entry {
correlationID := logging.GetRequestID(ctx)
return l.logger.WithField("correlation_id", correlationID)
}
```
### 6. HTTP Handlers (Thin Layer)
Handlers only deal with HTTP concerns:
```go
// internal/api/handlers/management/config_handler.go
type ConfigHandler struct {
useCase *usecase.ConfigUseCase
}
func (h *ConfigHandler) GetConfig(c *gin.Context) {
ctx := c.Request.Context()
response, err := h.useCase.GetConfig(ctx)
if err != nil {
h.handleError(c, err)
return
}
c.JSON(http.StatusOK, response)
}
func (h *ConfigHandler) handleError(c *gin.Context, err error) {
// Map domain errors to HTTP responses
var domainErr *domainerror.DomainError
if errors.As(err, &domainErr) {
status := h.mapErrorCodeToStatus(domainErr.Code)
c.JSON(status, gin.H{
"error": domainErr.Code,
"message": domainErr.Message,
})
return
}
c.JSON(http.StatusInternalServerError, gin.H{
"error": "INTERNAL_ERROR",
"message": "An unexpected error occurred",
})
}
```
## Migration Strategy
### Phase 1: Foundation
1. Create domain error types
2. Define repository interfaces
3. Create domain service interfaces
4. Set up structured logging infrastructure
### Phase 2: Extract Domain Logic
1. Move business logic from handlers to domain services
2. Implement repository interfaces
3. Create use cases
4. Add comprehensive unit tests
### Phase 3: Refactor Handlers
1. Make handlers thin - delegate to use cases
2. Standardize error handling
3. Add correlation ID middleware
### Phase 4: Cleanup
1. Remove old code
2. Verify backward compatibility
3. Update documentation
## Backward Compatibility
- All existing API endpoints remain unchanged
- Response formats preserved
- Configuration file format unchanged
- Auth file format unchanged
## Testing Strategy
1. **Unit tests**: Domain services with mocked repositories
2. **Integration tests**: Use cases with real repositories
3. **E2E tests**: Full HTTP request/response cycle
4. **Mock implementations**: For all external dependencies
## Benefits
1. **Testability**: Domain logic can be tested without HTTP layer
2. **Maintainability**: Clear separation of concerns
3. **Flexibility**: Easy to swap implementations (e.g., different storage)
4. **Observability**: Structured logging with correlation IDs
5. **Scalability**: Clear boundaries for future extensions
|