proxywhirl.models.core¶
Data models for ProxyWhirl using Pydantic v2.
Classes¶
Configuration for the lazy bootstrap that runs on first request when the pool is empty. |
|
Configuration for circuit breaker behavior. |
|
Continuous health monitoring for proxy pools with auto-eviction. |
|
Proxy health status states. |
|
Summary of entire proxy pool. |
|
Represents a single proxy server with connection details and metadata. |
|
Represents a chain of proxies for tunneling requests. |
|
Global configuration settings for the proxy system. |
|
Secure credential storage for proxy authentication. |
|
Supported proxy list formats. |
|
Collection of proxies with management capabilities. |
|
Origin type of proxy. |
|
Configuration for a proxy list source. |
|
Status of a single proxy in the pool. |
|
Page rendering modes for fetching proxy lists. |
|
Result of HTTP request made through proxy. |
|
Context information for proxy selection decisions. |
|
Session tracking for sticky proxy assignments. |
|
Statistics for a proxy source. |
|
Protocol for proxy storage backends. |
|
Configuration for rotation strategies. |
|
Proxy validation strictness levels. |
Module Contents¶
- class proxywhirl.models.core.BootstrapConfig(/, **data)[source]¶
Bases:
pydantic.BaseModelConfiguration for the lazy bootstrap that runs on first request when the pool is empty.
- Parameters:
data (Any)
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- class proxywhirl.models.core.CircuitBreakerConfig(/, **data)[source]¶
Bases:
pydantic.BaseModelConfiguration for circuit breaker behavior.
- Parameters:
data (Any)
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- class proxywhirl.models.core.HealthMonitor(pool, check_interval=60, failure_threshold=3)[source]¶
Continuous health monitoring for proxy pools with auto-eviction.
Runs background health checks at configurable intervals and automatically evicts proxies that fail consecutive checks beyond a threshold.
Example
>>> pool = ProxyPool(name="my_pool") >>> pool.add_proxy(Proxy(url="http://proxy.com:8080")) >>> monitor = HealthMonitor(pool=pool, check_interval=60, failure_threshold=3) >>> await monitor.start() # Start background checks >>> # ... proxies are monitored continuously ... >>> await monitor.stop() # Stop monitoring
Initialize health monitor.
- Parameters:
- Raises:
ValueError – If check_interval or failure_threshold <= 0
- class proxywhirl.models.core.HealthStatus[source]¶
-
Proxy health status states.
Initialize self. See help(type(self)) for accurate signature.
- class proxywhirl.models.core.PoolSummary(/, **data)[source]¶
Bases:
pydantic.BaseModelSummary of entire proxy pool.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.Proxy(/, **data)[source]¶
Bases:
pydantic.BaseModelRepresents a single proxy server with connection details and metadata.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- complete_request(success, response_time_ms, alpha=None)[source]¶
Mark a request as complete and update metrics.
- Parameters:
- Return type:
None
This method decrements requests_active, increments requests_completed, updates EMA response time, and delegates to record_success/record_failure.
Thread-safe: Uses internal lock to prevent race conditions.
- extract_protocol_from_url()[source]¶
Extract protocol from URL if not explicitly provided.
- Return type:
- is_window_expired()[source]¶
Check if the current sliding window has expired.
- Returns:
True if window duration has elapsed since window_start
- Return type:
Thread-safe: Uses internal lock to prevent race conditions.
- record_failure(error=None)[source]¶
Record a failed request.
- Parameters:
error (str | None)
- Return type:
None
- reset_if_expired()[source]¶
Atomically check if window is expired and reset if needed.
This method prevents Time-of-Check to Time-of-Use (TOCTOU) race conditions by performing the expiration check and reset within a single lock acquisition.
- Returns:
True if window was expired and has been reset, False otherwise
- Return type:
Thread-safe: Uses internal lock to ensure atomic check-and-reset.
- reset_window()[source]¶
Reset the sliding window counters.
This is called when the window duration has elapsed, preventing counter staleness and unbounded memory growth.
Thread-safe: Uses internal lock to prevent race conditions.
- Return type:
None
- start_request()[source]¶
Mark a request as started (for tracking in-flight requests).
This should be called when a request is about to be made through this proxy. Increments both requests_started and requests_active counters.
Thread-safe: Uses internal lock to prevent race conditions.
- Return type:
None
- update_metrics(response_time_ms, alpha=None)[source]¶
Update EMA and average response time metrics.
This method centralizes all response time metric updates to ensure consistency across the codebase. Both average_response_time_ms and ema_response_time_ms use the same alpha value.
- Parameters:
response_time_ms (float) – Response time in milliseconds
alpha (float | None) – EMA smoothing factor (0-1). Higher values weight recent observations more heavily. If not provided, falls back to self.ema_alpha for backward compatibility. Strategies should pass their configured StrategyConfig.ema_alpha for consistent behavior, or use StrategyState for independent per-proxy metrics.
- Return type:
None
- validate_credentials()[source]¶
Ensure username and password are both present or both absent.
- Return type:
- validate_local_addresses()[source]¶
Reject localhost/internal IPs unless allow_local=True.
- Return type:
- classmethod validate_response_time_non_negative(v)[source]¶
Validate response time fields are non-negative.
- property credentials: ProxyCredentials | None[source]¶
Get credentials if present.
- Return type:
ProxyCredentials | None
- class proxywhirl.models.core.ProxyChain(/, **data)[source]¶
Bases:
pydantic.BaseModelRepresents a chain of proxies for tunneling requests.
A proxy chain allows requests to be routed through multiple proxies in sequence, where each proxy connects to the next one in the chain. This is useful for: - Enhanced anonymity through multi-hop routing - Geographic routing through specific locations - Bypassing network restrictions
Note: Full CONNECT tunneling implementation requires additional infrastructure. This model provides the data structure and basic support for chaining.
Example
>>> chain = ProxyChain( ... proxies=[ ... Proxy(url="http://proxy1.com:8080"), ... Proxy(url="http://proxy2.com:8080"), ... ], ... name="geo_chain", ... description="Route through US then UK" ... )
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.ProxyConfiguration(_case_sensitive=None, _nested_model_default_partial_update=None, _env_prefix=None, _env_file=ENV_FILE_SENTINEL, _env_file_encoding=None, _env_ignore_empty=None, _env_nested_delimiter=None, _env_nested_max_split=None, _env_parse_none_str=None, _env_parse_enums=None, _cli_prog_name=None, _cli_parse_args=None, _cli_settings_source=None, _cli_parse_none_str=None, _cli_hide_none_type=None, _cli_avoid_json=None, _cli_enforce_required=None, _cli_use_class_docs_for_groups=None, _cli_exit_on_error=None, _cli_prefix=None, _cli_flag_prefix_char=None, _cli_implicit_flags=None, _cli_ignore_unknown_args=None, _cli_kebab_case=None, _cli_shortcuts=None, _secrets_dir=None, **values)[source]¶
Bases:
pydantic_settings.BaseSettingsGlobal configuration settings for the proxy system.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
_case_sensitive (bool | None)
_nested_model_default_partial_update (bool | None)
_env_prefix (str | None)
_env_file (pydantic_settings.sources.DotenvType | None)
_env_file_encoding (str | None)
_env_ignore_empty (bool | None)
_env_nested_delimiter (str | None)
_env_nested_max_split (int | None)
_env_parse_none_str (str | None)
_env_parse_enums (bool | None)
_cli_prog_name (str | None)
_cli_parse_args (bool | list[str] | tuple[str, Ellipsis] | None)
_cli_settings_source (pydantic_settings.sources.CliSettingsSource[Any] | None)
_cli_parse_none_str (str | None)
_cli_hide_none_type (bool | None)
_cli_avoid_json (bool | None)
_cli_enforce_required (bool | None)
_cli_use_class_docs_for_groups (bool | None)
_cli_exit_on_error (bool | None)
_cli_prefix (str | None)
_cli_flag_prefix_char (str | None)
_cli_implicit_flags (bool | None)
_cli_ignore_unknown_args (bool | None)
_cli_kebab_case (bool | None)
_cli_shortcuts (collections.abc.Mapping[str, str | list[str]] | None)
_secrets_dir (pydantic_settings.sources.PathType | None)
values (Any)
- class proxywhirl.models.core.ProxyCredentials(/, **data)[source]¶
Bases:
pydantic.BaseModelSecure credential storage for proxy authentication.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.ProxyFormat[source]¶
-
Supported proxy list formats.
Initialize self. See help(type(self)) for accurate signature.
- class proxywhirl.models.core.ProxyPool(**data)[source]¶
Bases:
pydantic.BaseModelCollection of proxies with management capabilities.
Thread-safe proxy pool with RLock protection for concurrent access. All mutating operations are automatically protected by a reentrant lock.
Initialize ProxyPool with thread lock and ID index.
- Parameters:
data (Any)
- add_proxy(proxy)[source]¶
Add proxy to pool (thread-safe).
- Parameters:
proxy (Proxy)
- Return type:
None
- clear_expired()[source]¶
Remove all expired proxies, return count removed (thread-safe).
- Returns:
Number of expired proxies removed from the pool
- Return type:
- clear_unhealthy()[source]¶
Remove all unhealthy proxies, return count removed (thread-safe).
- Return type:
- filter_by_source(source)[source]¶
Get proxies from specific source (thread-safe).
- Parameters:
source (ProxySource)
- Return type:
- get_healthy_proxies()[source]¶
Get all healthy or unknown (not yet tested) proxies, excluding expired ones (thread-safe).
Returns only proxies that are: - Healthy, degraded, or unknown status - Not expired (if TTL is set)
- remove_proxy(proxy_id)[source]¶
Remove proxy from pool (thread-safe).
- Parameters:
proxy_id (uuid.UUID)
- Return type:
None
- model_config[source]¶
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- class proxywhirl.models.core.ProxySource[source]¶
-
Origin type of proxy.
Initialize self. See help(type(self)) for accurate signature.
- class proxywhirl.models.core.ProxySourceConfig(/, **data)[source]¶
Bases:
pydantic.BaseModelConfiguration for a proxy list source.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.ProxyStatus(/, **data)[source]¶
Bases:
pydantic.BaseModelStatus of a single proxy in the pool.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.RenderMode[source]¶
-
Page rendering modes for fetching proxy lists.
Initialize self. See help(type(self)) for accurate signature.
- class proxywhirl.models.core.RequestResult(/, **data)[source]¶
Bases:
pydantic.BaseModelResult of HTTP request made through proxy.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.SelectionContext(/, **data)[source]¶
Bases:
pydantic.BaseModelContext information for proxy selection decisions.
This model captures all the contextual information that might be relevant for intelligent proxy selection, including session tracking, target URL characteristics, and previous attempt history.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.Session(/, **data)[source]¶
Bases:
pydantic.BaseModelSession tracking for sticky proxy assignments.
This model maintains the relationship between a session and its assigned proxy, with TTL support and usage tracking.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.SourceStats(/, **data)[source]¶
Bases:
pydantic.BaseModelStatistics for a proxy source.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.StorageBackend[source]¶
Bases:
ProtocolProtocol for proxy storage backends.
This defines the interface that all storage backends must implement, allowing for file-based, database, or other storage mechanisms.
- async clear()[source]¶
Clear all proxies from storage.
- Raises:
IOError – If clear operation fails
- Return type:
None
- async load()[source]¶
Load proxies from storage.
- Returns:
List of proxies loaded from storage
- Raises:
FileNotFoundError – If storage doesn’t exist
ValueError – If data is corrupted or invalid
- Return type:
- class proxywhirl.models.core.StrategyConfig(/, **data)[source]¶
Bases:
pydantic.BaseModelConfiguration for rotation strategies.
This model provides flexible configuration options for all rotation strategies, allowing customization of weights, EMA parameters, session settings, and geo-targeting constraints.
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
- Parameters:
data (Any)
- class proxywhirl.models.core.ValidationLevel[source]¶
-
Proxy validation strictness levels.
BASIC: Format + TCP connectivity validation (fast, ~100ms) STANDARD: BASIC + HTTP request test (medium, ~500ms) FULL: STANDARD + Anonymity check (comprehensive, ~2s)
Initialize self. See help(type(self)) for accurate signature.