Skip to main content

ProxyManager

Struct ProxyManager 

Source
pub struct ProxyManager { /* private fields */ }
Expand description

Unified proxy pool orchestrator.

Manage proxies via add_proxy and remove_proxy, acquire one via acquire_proxy, and start background health checking with start.

§Quick start

use std::sync::Arc;
use stygian_proxy::{ProxyManager, ProxyConfig, Proxy, ProxyType};
use stygian_proxy::storage::MemoryProxyStore;
use stygian_proxy::types::{IpClass, ProxyCapabilities, TargetVendorCompatibility};

let storage = Arc::new(MemoryProxyStore::default());
let mgr = ProxyManager::with_round_robin(storage, ProxyConfig::default())?;
let (token, _handle) = mgr.start();
let proxy = mgr.add_proxy(Proxy {
    url: "http://proxy.example.com:8080".into(),
    proxy_type: ProxyType::Http,
    username: None,
    password: None,
    weight: 1,
    tags: vec![],
    capabilities: ProxyCapabilities::default(),
    ip_class: IpClass::Unknown,
    target_compatibility: TargetVendorCompatibility::default(),
}).await?;
let handle = mgr.acquire_proxy().await?;
handle.mark_success();
token.cancel();

Implementations§

Source§

impl ProxyManager

Source

pub fn builder() -> ProxyManagerBuilder

Source

pub fn with_round_robin( storage: Arc<dyn ProxyStoragePort>, config: ProxyConfig, ) -> ProxyResult<Self>

Convenience: round-robin rotation (default).

§Errors

Returns ProxyError::ConfigError when no storage is supplied to the underlying builder.

Source

pub fn with_random( storage: Arc<dyn ProxyStoragePort>, config: ProxyConfig, ) -> ProxyResult<Self>

Convenience: random rotation.

§Errors

Returns ProxyError::ConfigError when no storage is supplied to the underlying builder.

Source

pub fn with_weighted( storage: Arc<dyn ProxyStoragePort>, config: ProxyConfig, ) -> ProxyResult<Self>

Convenience: weighted rotation.

§Errors

Returns ProxyError::ConfigError when no storage is supplied to the underlying builder.

Source

pub fn with_least_used( storage: Arc<dyn ProxyStoragePort>, config: ProxyConfig, ) -> ProxyResult<Self>

Convenience: least-used rotation.

§Errors

Returns ProxyError::ConfigError when no storage is supplied to the underlying builder.

Source

pub async fn add_proxy(&self, proxy: Proxy) -> ProxyResult<Uuid>

Add a proxy and register a circuit breaker for it. Returns the new ID.

The circuit_breakers write lock is held for the duration of the storage write. This is intentional: acquire_proxy holds a read lock on the same map while it inspects candidates, so it cannot proceed past that point until both the storage record and its CB entry exist. Without this ordering a concurrent acquire_proxy could select the new proxy before its CB was registered, breaking failure accounting.

§Errors

Returns ProxyError::StorageError when the underlying storage backend rejects the new proxy record, or ProxyError::InvalidGeoMetadata when the proxy’s geo-metadata fields fail ingest validation (e.g. asn = 0, city = "", postal_code = "").

Source

pub async fn remove_proxy(&self, id: Uuid) -> ProxyResult<()>

Remove a proxy from the pool and drop its circuit breaker.

§Errors

Returns ProxyError::StorageError when the underlying storage backend reports the proxy as missing or the remove call fails.

Source

pub async fn add_proxy_with_metadata( &self, url: &str, asn: Option<u32>, city: Option<&str>, postal_code: Option<&str>, ) -> ProxyResult<Uuid>

Add a proxy with explicit geo metadata (ASN, city, postal code).

Convenience constructor for operator-curated pools that target specific geographic or network ranges — the “Infatica-style city, ZIP, and ASN filter” cited by the 2026 guide (L2837). Constructs the Proxy and underlying crate::ProxyCapabilities for the caller, populates the geo fields, and runs the same ingest validation as add_proxy (so asn = 0, city = "", etc. are rejected with ProxyError::InvalidGeoMetadata before the record is stored).

The proxy_type, username, password, weight, tags, and remaining ProxyCapabilities fields take their Default::default() values; callers that need finer control over those should build a Proxy directly and call add_proxy instead.

§Example
use std::sync::Arc;
use stygian_proxy::{ProxyManager, ProxyConfig};
use stygian_proxy::storage::MemoryProxyStore;
use stygian_proxy::types::well_known::KNOWN_ASN_CLOUDFLARE;

let store = Arc::new(MemoryProxyStore::default());
let mgr = ProxyManager::with_round_robin(store, ProxyConfig::default())?;
let _id = mgr.add_proxy_with_metadata(
    "http://cf-exit.example.com:8080",
    Some(KNOWN_ASN_CLOUDFLARE),
    Some("San Francisco"),
    Some("94110"),
).await?;
§Errors

Returns ProxyError::InvalidProxyUrl when url is malformed, or ProxyError::InvalidGeoMetadata when any geo field fails the validation rules documented in crate::types::validate_asn, crate::types::validate_city, or crate::types::validate_postal_code. Storage failures surface as ProxyError::StorageError.

Source

pub fn start(&self) -> (CancellationToken, JoinHandle<()>)

Spawn the background health-check and session-purge tasks.

Returns a (CancellationToken, JoinHandle) pair. Cancel the token to trigger a graceful shutdown; await the handle to ensure it finishes.

Source

pub fn strategy_warmup_observe(&self, proxy_id: Uuid, success: bool)

Pre-warm the Bayesian observer with a synthetic outcome for a proxy.

This is the same call that ProxyHandle::mark_success and the Drop impl make at runtime, exposed publicly so callers can pre-seed the bandit from a known-good (or known-bad) prior before serving traffic. Most useful for tests and for warm-starting the pool from an external health-check feed.

Source

pub fn storage(&self) -> &Arc<dyn ProxyStoragePort>

Read-only view of the underlying proxy storage. Useful for tests, MCP introspection, and warm-up helpers that need to map url → id without traversing the public API surface.

Source

pub async fn acquire_proxy(&self) -> ProxyResult<ProxyHandle>

Acquire a proxy from the pool.

Builds ProxyCandidate entries from current storage, consulting the health map and each proxy’s circuit breaker to set the healthy flag. Delegates selection to the configured crate::strategy::RotationStrategy.

§Errors

Returns ProxyError::StorageError when the storage backend cannot list proxies, or ProxyError::NoCompatibleProxy when no healthy proxy is available.

Source

pub async fn acquire_with_capabilities( &self, req: &CapabilityRequirement, ) -> ProxyResult<ProxyHandle>

Acquire a proxy that satisfies req from the pool.

Filters the candidate list to healthy proxies whose ProxyCapabilities satisfy every flag in req, then delegates to the configured rotation strategy.

Returns ProxyError::NoCompatibleProxy when no healthy proxy meets the capability requirements.

§Example
use stygian_proxy::{ProxyManager, ProxyManagerBuilder, CapabilityRequirement};

async fn example(manager: &ProxyManager) {
    let req = CapabilityRequirement { require_https_connect: true, ..Default::default() };
    let handle = manager.acquire_with_capabilities(&req).await.unwrap();
    println!("url: {}", handle.proxy_url);
}
§Errors

Returns ProxyError::StorageError when the storage backend cannot list proxies, or ProxyError::NoCompatibleProxy when no healthy proxy satisfies the supplied CapabilityRequirement.

Source

pub async fn acquire_for_domain(&self, domain: &str) -> ProxyResult<ProxyHandle>

Acquire a proxy for domain, honouring the configured sticky-session policy.

  • When StickyPolicy::Disabled is active, behaves identically to acquire_proxy.
  • When StickyPolicy::Domain is active and a fresh session exists for domain, the same proxy is returned for the TTL duration.
  • If the bound proxy’s circuit breaker has tripped or the proxy has been removed, the stale session is invalidated and a fresh proxy is acquired and bound.

The returned ProxyHandle automatically invalidates the session on drop if not marked as successful.

§Errors

Returns ProxyError::StorageError when the storage backend fails, or ProxyError::NoCompatibleProxy when no healthy proxy is available (including when a sticky-bound proxy is unhealthy and the fallback also exhausts the pool).

Source

pub async fn pool_stats(&self) -> ProxyResult<PoolStats>

Return a health snapshot of the pool.

§Errors

Returns ProxyError::StorageError when the storage backend cannot list proxies, or when the internal lock is poisoned.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more