diff --git a/docs/PACKAGES.md b/docs/PACKAGES.md new file mode 100644 index 0000000..8c30427 --- /dev/null +++ b/docs/PACKAGES.md @@ -0,0 +1,147 @@ +# Package Structure + +This document explains the organization and responsibilities of all packages in the Hash of Wisdom project. + +## Directory Structure + +``` +/ +├── cmd/ # Application entry points +│ ├── server/ # Server application +│ └── client/ # Client application +├── internal/ # Private application packages +│ ├── application/ # Application layer (message handling) +│ ├── config/ # Configuration management +│ ├── lib/ # Shared utilities +│ ├── metrics/ # Prometheus metrics +│ ├── pow/ # Proof-of-Work implementation +│ ├── protocol/ # Binary protocol codec +│ ├── quotes/ # Quote service +│ ├── server/ # TCP server implementation +│ └── service/ # Business logic layer +├── test/ # Integration tests +└── docs/ # Documentation +``` + +## Package Responsibilities + +### `cmd/server` +**Entry point for the TCP server application** +- Parses command-line flags and configuration +- Initializes all components with dependency injection +- Starts TCP server and metrics endpoints +- Handles graceful shutdown signals + +### `cmd/client` +**Entry point for the client application** +- Command-line interface for connecting to server +- Handles proof-of-work solving on client side +- Manages TCP connection lifecycle + +### `internal/config` +**Configuration management with cleanenv** +- Defines configuration structures with YAML/env tags +- Loads configuration from files and environment variables +- Provides sensible defaults for all settings +- Supports both development and production configurations + +### `internal/lib/sl` +**Shared logging utilities** +- Structured logging helpers for consistent log formatting +- Error attribute helpers for slog integration + +### `internal/metrics` +**Prometheus metrics collection** +- Defines application-specific metrics (requests, errors, duration) +- Provides simple counters and histograms for monitoring +- Integrated at the infrastructure layer (TCP server) + +### `internal/pow` +**Proof-of-Work implementation** + +#### `internal/pow/challenge` +- **Challenge Generation**: Creates HMAC-signed stateless challenges +- **Verification**: Validates solutions against original challenges +- **Security**: HMAC authentication prevents tampering +- **Configuration**: Difficulty scaling, TTL management, secrets + +#### `internal/pow/solver` +- **Solution Finding**: Brute-force nonce search with SHA-256 +- **Optimization**: Efficient bit counting for difficulty verification +- **Client-side**: Used by client to solve server challenges + +### `internal/protocol` +**Binary protocol codec** +- **Message Types**: Challenge requests/responses, solution requests/responses, errors +- **Encoding/Decoding**: JSON-based message serialization +- **Streaming**: MessageDecoder for reading from TCP connections +- **Validation**: Message structure and field validation +- See [Protocol Specification](PROTOCOL.md) for detailed message flow and format + +### `internal/quotes` +**Quote service implementation** +- **HTTP Client**: Fetches quotes from external APIs using resty +- **Interface**: Clean abstraction for quote retrieval +- **Error Handling**: Graceful degradation for network issues +- **Timeout Management**: Configurable request timeouts + +### `internal/server` +**TCP server implementation** + +#### `internal/server/tcp.go` +- **Connection Management**: Accept, handle, cleanup TCP connections +- **Protocol Integration**: Uses protocol package for message handling +- **Security**: Connection timeouts, slowloris protection +- **Metrics**: Request tracking at infrastructure layer +- **Lifecycle**: Graceful startup/shutdown with context + +#### `internal/server/config.go` +- **Server Configuration**: Network settings, timeouts +- **Functional Options**: Builder pattern for server customization + +### `internal/application` +**Application layer (message handling and coordination)** +- **WisdomApplication**: Protocol message handler and coordinator +- **Message Processing**: Handles challenge and solution requests from protocol layer +- **Response Generation**: Creates appropriate protocol responses +- **Service Coordination**: Orchestrates calls to business logic layer +- **Error Handling**: Converts service errors to protocol error responses + +### `internal/service` +**Business logic layer (core domain services)** +- **WisdomService**: Main business logic coordinator +- **Challenge Workflow**: Manages challenge generation and validation +- **Solution Workflow**: Handles solution verification and quote retrieval +- **Clean Architecture**: Pure business logic, no I/O dependencies +- **Testing**: Easily mockable interfaces for unit testing + +**Service Dependencies**: +- `ChallengeGenerator` - Creates new challenges +- `ChallengeVerifier` - Validates submitted solutions +- `QuoteService` - Retrieves quotes after successful validation + +### `test/integration` +**End-to-end integration tests** +- **Slowloris Protection**: Tests server resilience against slow attacks +- **Connection Timeouts**: Validates timeout configurations +- **Full Workflow**: Tests complete client-server interaction +- **Real Components**: Uses actual TCP connections and protocol + +## Dependency Flow + +``` +cmd/server + ↓ +internal/config → internal/server → internal/application → internal/service + ↓ ↓ ↓ + internal/protocol internal/protocol internal/pow + internal/metrics internal/quotes +``` + +## Architecture Benefits + +This package structure provides: +- **Clear Separation**: Each package has a single, well-defined responsibility +- **Testability**: Dependencies are injected, making testing straightforward +- **Maintainability**: Changes are isolated to specific layers +- **Scalability**: Clean interfaces allow for easy implementation swapping