hosts-go/memory-bank/systemPatterns.md
phg d66ec51ebd feat: Initialize hosts-go project with foundational structure and core functionality
- Created activeContext.md and productContext.md to outline project goals and current focus.
- Established progress.md to track project milestones and tasks.
- Developed projectbrief.md detailing application overview, requirements, and directory structure.
- Documented systemPatterns.md to describe architecture and design patterns used.
- Compiled techContext.md to specify technologies and development setup.
- Implemented comprehensive unit tests in models_test.go for HostEntry and HostsFile functionalities.
2025-08-12 22:41:33 +02:00

161 lines
4.9 KiB
Markdown

# System Patterns: hosts-go
## Architecture Overview
The hosts-go application follows a **layered architecture** with clear separation of concerns:
```
┌─────────────────────┐
│ TUI Layer │ ← Bubble Tea models, views, styles
├─────────────────────┤
│ Business Logic │ ← Core domain logic, validation
├─────────────────────┤
│ System Interface │ ← File I/O, DNS, permissions
└─────────────────────┘
```
## Key Technical Decisions
### 1. **Bubble Tea Framework**
- **Why**: Provides mature TUI framework with event-driven architecture
- **Pattern**: Model-View-Update (MVU) pattern for state management
- **Components**: Main model orchestrates sub-components (list, detail, modal)
### 2. **Internal Package Structure**
```
internal/
├── tui/ # UI layer - Bubble Tea components
├── core/ # Business logic - domain models and operations
└── utils/ # Shared utilities - helpers and common functions
```
### 3. **Permission Model**
- **View mode default**: Read-only access, no sudo required
- **Edit mode explicit**: User must explicitly enter edit mode
- **Sudo on demand**: Only request elevated permissions when entering edit mode
- **Graceful fallback**: Handle permission denied gracefully
## Design Patterns in Use
### 1. **Model-View-Update (MVU)**
- **Model**: Application state (entries, selection, mode)
- **View**: Rendering logic (two-pane layout, styles)
- **Update**: State transitions based on user input
### 2. **Command Pattern**
- **Edit operations**: Encapsulate modifications as commands
- **Undo support**: Commands can be reversed
- **Validation**: Commands validate before execution
### 3. **Repository Pattern**
- **HostsRepository**: Abstract file operations
- **MockRepository**: In-memory implementation for testing
- **FileRepository**: Actual `/etc/hosts` file operations
### 4. **Observer Pattern**
- **DNS resolution**: Background updates to IP addresses
- **File watching**: Detect external changes to hosts file
- **Status updates**: Notify UI of operation progress
## Component Relationships
### TUI Components
```
MainModel
├── ListModel (left pane)
│ ├── Entry selection
│ ├── Sorting controls
│ └── Status indicators
├── DetailModel (right pane)
│ ├── Entry editing
│ ├── Form validation
│ └── DNS resolution
└── ModalModel (overlays)
├── Configuration
├── Confirmations
└── Error dialogs
```
### Core Business Logic
```
Manager
├── HostsParser (read/write hosts file)
├── DNSResolver (hostname to IP resolution)
├── Validator (entry validation)
└── ConfigManager (user preferences)
```
## Critical Implementation Paths
### 1. **File Operations**
```go
// Atomic file updates with backup
1. Read current /etc/hosts backup
2. Parse entries validate changes
3. Write to temporary file verify
4. Atomic move temp /etc/hosts
5. Remove backup on success
```
### 2. **State Management**
```go
// Bubble Tea update cycle
1. User input Command
2. Command State change
3. State change View update
4. View update Screen render
```
### 3. **DNS Resolution**
```go
// Background IP resolution
1. Extract hostnames from entries
2. Resolve in background goroutines
3. Compare resolved vs current IPs
4. Update UI with resolution status
5. User chooses whether to update
```
### 4. **Edit Mode Transition**
```go
// Permission elevation
1. User requests edit mode
2. Check current permissions
3. Request sudo if needed
4. Validate file write access
5. Enable editing controls
```
## Error Handling Strategy
### 1. **Graceful Degradation**
- **No sudo**: Continue in view-only mode
- **File locked**: Show warning, allow retry
- **DNS failure**: Show cached/manual IP options
### 2. **Validation Layers**
- **Input validation**: Real-time feedback on forms
- **Business rules**: Validate complete entries
- **System constraints**: Check file permissions, IP formats
### 3. **Recovery Mechanisms**
- **Backup restoration**: Automatic rollback on write failures
- **State recovery**: Restore UI state after errors
- **User guidance**: Clear error messages with suggested actions
## Testing Architecture
### 1. **Unit Tests**
- **Pure functions**: Parser, validator, DNS resolver
- **Mocked dependencies**: File system, network calls
- **Edge cases**: Malformed files, network errors
### 2. **Integration Tests**
- **TUI workflows**: Complete user interactions
- **File operations**: Real file system operations (in temp dirs)
- **Permission scenarios**: Test sudo/non-sudo paths
### 3. **Test Patterns**
- **Table-driven tests**: Multiple input scenarios
- **Mock interfaces**: Controllable external dependencies
- **Golden files**: Expected output comparisons