SSF Tools - HTTP Client Service Architecture¶
Overview¶
The HTTP Client Service provides a unified, protocol-based approach to HTTP operations across all SSF Tools commands. This architecture enables consistent network handling while maintaining loose coupling through dependency injection patterns and supporting various HTTP operations including requests, file downloads, retry logic, caching, and error recovery with beautiful terminal feedback.
Architectural Principles¶
1. Protocol-Based Design¶
All HTTP client services implement well-defined protocols, enabling:
- Dependency injection: Services receive HTTP client interfaces, not concrete implementations
- Testability: Easy mocking and stubbing for unit tests
- Flexibility: Swappable implementations (different HTTP libraries, mock clients)
- Type safety: MyPy-compliant interfaces with clear contracts
- Composability: Small, focused protocols that can be combined
2. Separation of Concerns¶
Each HTTP operation is handled through a dedicated interface:
- Request Handling: GET, POST, PUT, DELETE, HEAD, PATCH operations
- File Downloads: Progress tracking and streaming downloads
- Retry Logic: Configurable retry strategies with backoff algorithms
- Caching: Response caching with TTL-based expiration
- Error Recovery: Graceful degradation and comprehensive error handling
- Progress Feedback: Rich terminal output integration for user experience
3. Robust Error Handling¶
All HTTP services implement graceful error handling:
- Network errors: Connection timeouts, DNS failures, SSL issues
- HTTP errors: 4xx client errors, 5xx server errors with context
- Retry strategies: Automatic retry with exponential backoff
- Type safety: Clear exception hierarchy for different error types
Architecture Overview¶
The HTTP Client Service follows a layered architecture with clear separation of concerns:
Service Composition¶
Core Protocols¶
Implementation Architecture¶
Dependency Injection¶
HTTP Client Workflow¶
The HTTP client service orchestrates network operations with comprehensive error handling and progress feedback:
Core Components¶
kp_ssf_tools.core.services.http_client.service.HttpClientService
¶
HTTP client service implementing HttpClientProtocol.
Source code in src\kp_ssf_tools\core\services\http_client\service.py
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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 | |
Attributes¶
client
property
¶
Get or create HTTP client.
Functions¶
__enter__()
¶
__exit__(exc_type, exc_val, exc_tb)
¶
Context manager exit with cleanup.
Source code in src\kp_ssf_tools\core\services\http_client\service.py
__init__(config=None, output=None)
¶
Initialize HTTP client service.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
HttpConfig | None
|
HTTP client configuration |
None
|
output
|
RichOutputProtocol | None
|
Rich output service for logging and user feedback |
None
|
Source code in src\kp_ssf_tools\core\services\http_client\service.py
clear_cache()
¶
download_file(url, file_path, progress_callback=None)
¶
Download file with optional progress tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
File URL to download |
required |
file_path
|
Path
|
Destination file path |
required |
progress_callback
|
Callable[[int, int], None] | None
|
Optional progress callback function |
None
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When download fails |
Source code in src\kp_ssf_tools\core\services\http_client\service.py
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 | |
get(url, headers=None, params=None, **kwargs)
¶
Execute GET request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Target URL |
required |
headers
|
dict[str, str] | None
|
Optional request headers |
None
|
params
|
dict[str, str] | None
|
Optional query parameters |
None
|
**kwargs
|
object
|
Additional request options |
{}
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When request fails |
Source code in src\kp_ssf_tools\core\services\http_client\service.py
head(url, headers=None, **kwargs)
¶
Execute HEAD request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Target URL |
required |
headers
|
dict[str, str] | None
|
Optional request headers |
None
|
**kwargs
|
object
|
Additional request options |
{}
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When request fails |
Source code in src\kp_ssf_tools\core\services\http_client\service.py
is_url_accessible(url)
¶
Check if URL is accessible without downloading content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if URL is accessible, False otherwise |
Source code in src\kp_ssf_tools\core\services\http_client\service.py
post(url, data=None, json=None, headers=None, **kwargs)
¶
Execute POST request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Target URL |
required |
data
|
bytes | str | dict[str, object] | None
|
Request body data |
None
|
json
|
dict[str, object] | None
|
JSON data to send |
None
|
headers
|
dict[str, str] | None
|
Optional request headers |
None
|
**kwargs
|
object
|
Additional request options |
{}
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When request fails |
Source code in src\kp_ssf_tools\core\services\http_client\service.py
session()
¶
Context manager for persistent session.
Yields:
| Type | Description |
|---|---|
Generator[Client]
|
HTTP client session |
Source code in src\kp_ssf_tools\core\services\http_client\service.py
HTTP Configuration¶
kp_ssf_tools.core.services.http_client.models.HttpConfig
dataclass
¶
HTTP client configuration.
Source code in src\kp_ssf_tools\core\services\http_client\models.py
kp_ssf_tools.core.services.http_client.models.HttpResponse
dataclass
¶
HTTP response wrapper.
Source code in src\kp_ssf_tools\core\services\http_client\models.py
HTTP Client Interface¶
kp_ssf_tools.core.services.http_client.interfaces.HttpClientProtocol
¶
Bases: Protocol
Protocol defining the HTTP client interface for dependency injection.
Source code in src\kp_ssf_tools\core\services\http_client\interfaces.py
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 | |
Functions¶
clear_cache()
abstractmethod
¶
download_file(url, file_path, progress_callback=None)
abstractmethod
¶
Download file with optional progress tracking.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
File URL to download |
required |
file_path
|
Path
|
Destination file path |
required |
progress_callback
|
Callable[[int, int], None] | None
|
Optional progress callback function |
None
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When download fails |
Source code in src\kp_ssf_tools\core\services\http_client\interfaces.py
get(url, headers=None, params=None, **kwargs)
abstractmethod
¶
Execute GET request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Target URL |
required |
headers
|
dict[str, str] | None
|
Optional request headers |
None
|
params
|
dict[str, str] | None
|
Optional query parameters |
None
|
**kwargs
|
object
|
Additional request options |
{}
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When request fails |
Source code in src\kp_ssf_tools\core\services\http_client\interfaces.py
head(url, headers=None, **kwargs)
abstractmethod
¶
Execute HEAD request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Target URL |
required |
headers
|
dict[str, str] | None
|
Optional request headers |
None
|
**kwargs
|
object
|
Additional request options |
{}
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When request fails |
Source code in src\kp_ssf_tools\core\services\http_client\interfaces.py
is_url_accessible(url)
abstractmethod
¶
Check if URL is accessible without downloading content.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
URL to check |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if URL is accessible, False otherwise |
Source code in src\kp_ssf_tools\core\services\http_client\interfaces.py
post(url, data=None, json=None, headers=None, **kwargs)
abstractmethod
¶
Execute POST request.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
url
|
str
|
Target URL |
required |
data
|
bytes | str | dict[str, object] | None
|
Request body data |
None
|
json
|
dict[str, object] | None
|
JSON data to send |
None
|
headers
|
dict[str, str] | None
|
Optional request headers |
None
|
**kwargs
|
object
|
Additional request options |
{}
|
Returns:
| Type | Description |
|---|---|
HttpResponse
|
HTTP response wrapper |
Raises:
| Type | Description |
|---|---|
NetworkError
|
When request fails |
Source code in src\kp_ssf_tools\core\services\http_client\interfaces.py
session()
abstractmethod
¶
Context manager for persistent session.
Yields:
| Type | Description |
|---|---|
Generator[object]
|
HTTP client session |
Error Handling¶
kp_ssf_tools.core.services.http_client.models.NetworkError
¶
Bases: Exception
Base exception for network-related errors.
Source code in src\kp_ssf_tools\core\services\http_client\models.py
kp_ssf_tools.core.services.http_client.models.HttpTimeoutError
¶
Bases: NetworkError
Request timeout error.
Source code in src\kp_ssf_tools\core\services\http_client\models.py
kp_ssf_tools.core.services.http_client.models.HttpConnectionError
¶
Bases: NetworkError
Connection-related error.
Source code in src\kp_ssf_tools\core\services\http_client\models.py
kp_ssf_tools.core.services.http_client.models.HttpError
¶
Bases: NetworkError
HTTP protocol error.
Source code in src\kp_ssf_tools\core\services\http_client\models.py
Usage Patterns¶
Basic Dependency Injection Pattern¶
The HTTP Client Service follows standard dependency injection patterns:
class DataProcessor:
def __init__(self, http_client: HttpClientProtocol):
self._http_client = http_client
def fetch_external_data(self, url: str) -> ProcessResult:
response = self._http_client.get(url)
# Process response...
return ProcessResult(data=response.text)
Configuration-Driven Behavior¶
The service supports flexible configuration through the container system:
# Container configuration example
http_config = HttpConfig(
timeout_seconds=30.0,
max_retries=5,
retry_strategy=RetryStrategy.EXPONENTIAL_BACKOFF,
cache_enabled=True
)
Error Handling Strategy¶
All HTTP operations use consistent error handling:
try:
response = http_client.get(url)
return response.text
except NetworkError as e:
# Handle network-level errors
logger.error(f"Network operation failed: {e}")
except HttpError as e:
# Handle HTTP protocol errors
logger.error(f"HTTP error {e.status_code}: {e}")
Container Configuration¶
The HTTP Client Service integrates with the core container system for dependency injection:
Service Registration¶
class CoreContainer(containers.DeclarativeContainer):
# Configuration
http_config = providers.Configuration()
# Services
http_client = providers.Singleton(
HttpClientService,
config=http_config,
rich_output=rich_output_service
)
# Dependent services
data_processor = providers.Factory(
DataProcessor,
http_client=http_client
)
Configuration Structure¶
# ssf-tools-config.yaml
http:
timeout_seconds: 30.0
max_retries: 5
retry_strategy: "exponential_backoff"
cache_enabled: true
cache_ttl_seconds: 3600
user_agent: "SSF-Tools/1.0"
Performance Considerations¶
Connection Management¶
- Connection pooling: Reuses connections across requests
- Resource cleanup: Automatic cleanup of network resources
- Timeout handling: Configurable timeouts prevent hanging operations
Caching Strategy¶
- Response caching: Reduces redundant network requests
- TTL-based expiration: Ensures data freshness
- Memory efficiency: Bounded cache size prevents memory leaks
Retry Logic¶
- Exponential backoff: Prevents server overload during retries
- Transient error detection: Distinguishes retry-able from permanent failures
- Configurable strategies: Supports different retry patterns per use case
The HTTP Client Service provides a robust, configurable foundation for network operations across SSF Tools, emphasizing consistency, testability, and performance through proper architectural patterns.