Documentation
¶
Index ¶
- Variables
- func IsSupportedScheme(scheme string) bool
- func TransportFor(proxyURL string, timeout time.Duration) (*http.Transport, error)
- type BanFilter
- type CacheSource
- type Config
- type DemandStat
- type FailReason
- type LaneStats
- type Mode
- type NetSnapshot
- type NetState
- type ParsedEndpoint
- type PoolEvent
- type PoolStats
- type ProxyFilter
- type ProxyInfo
- type ProxyPool
- func (p *ProxyPool) ForceForeground() int
- func (p *ProxyPool) GetMetadata(url string) map[string]string
- func (p *ProxyPool) ListProxies(filter ProxyFilter) []ProxyInfo
- func (p *ProxyPool) MarkDead(url, reason string) bool
- func (p *ProxyPool) Mode() Mode
- func (p *ProxyPool) NetHealth() NetSnapshot
- func (p *ProxyPool) RecheckBanned(f BanFilter) int
- func (p *ProxyPool) Refresh()
- func (p *ProxyPool) RegisterProxySource(source ProxySource)
- func (p *ProxyPool) RegisterReporter(reporter Reporter)
- func (p *ProxyPool) RequestIngest()
- func (p *ProxyPool) Require(ctx context.Context, opts RequireOptions) (RequireResult, error)
- func (p *ProxyPool) Reset()
- func (p *ProxyPool) SetLimits(min, initial, max int)
- func (p *ProxyPool) SetTimeout(c TimeoutConfig)
- func (p *ProxyPool) Snapshot() PoolStats
- func (p *ProxyPool) Start(ctx context.Context)
- func (p *ProxyPool) Starved() bool
- func (p *ProxyPool) Stop()
- func (p *ProxyPool) Suspect(url string, reason FailReason) bool
- func (p *ProxyPool) UpdateMetadata(url string, update func(map[string]string))
- type ProxyReport
- type ProxySource
- type ProxyState
- type Reporter
- type RequireOptions
- type RequireResult
- type SourceStats
- type TaggedSource
- type TaggedURL
- type TimeoutConfig
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidCountry reports a country that is not a two-letter ISO code. ErrInvalidCountry = errors.New("invalid country code") // ErrDemandLimit reports that every demand slot is held by a demand with waiters. ErrDemandLimit = errors.New("too many active proxy demands") )
Functions ¶
func IsSupportedScheme ¶ added in v1.0.5
IsSupportedScheme reports whether scheme names a probed protocol, canonicalizing case and the socks4a alias.
func TransportFor ¶ added in v1.0.4
TransportFor builds an HTTP transport routing through the given proxy URL. Supported schemes: http, https, socks4 (socks4a canonicalizes to socks4), socks5. Credentials embedded as userinfo apply to every scheme.
Every network phase is bounded by timeout: TCP connect (Dialer.Timeout), TLS handshake (TLSHandshakeTimeout), first response byte (ResponseHeaderTimeout), and the SOCKS greeting/CONNECT exchange (absolute conn deadline in dialContext). This closes the hang where a proxy accepts TCP then stalls forever — previously severing the host network (WireGuard flap) was the only thing that unblocked parked workers.
Types ¶
type BanFilter ¶ added in v1.0.6
type BanFilter struct {
Reason FailReason
Source string
}
ProxyFilter defines search criteria used when querying the pool. All fields are optional pointers; nil allows all values. BanFilter selects banned proxies for manual revival checks. Empty fields match any value.
type CacheSource ¶
type CacheSource interface {
Get(url string) (ProxyState, bool)
Set(state ProxyState)
All() []ProxyState
Delete(url string)
Clear()
}
CacheSource defines passive storage for proxy states. Implementations must not alter or mutate incoming data.
func NewMemoryCache ¶ added in v1.2.0
func NewMemoryCache() CacheSource
NewMemoryCache returns the default thread-safe in-memory CacheSource. Pass it to NewPool when no custom storage backend is needed.
type Config ¶ added in v1.0.6
type Config struct {
MinLimit int
InitialLimit int
MaxLimit int
LowWater int
HighWater int
LivenessInterval time.Duration
IngestInterval time.Duration
StatsInterval time.Duration
SoftBanBase time.Duration
SoftBanMax time.Duration
NetProbeInterval time.Duration
NetDegradedRTT time.Duration
SourceGCAge time.Duration
// RequireTimeout is the default overall deadline of one Require call.
RequireTimeout time.Duration
// DemandTTL is how long a country demand stays registered after its last use.
DemandTTL time.Duration
// MaxDemands caps the number of distinct registered demands.
MaxDemands int
// CountryTarget is the default number of alive proxies the pool keeps for a demanded country set.
CountryTarget int
// ReplenishTTL is how long a country target is maintained after the last Require call for it.
ReplenishTTL time.Duration
}
Config controls scheduler cadence, queue thresholds, and verification limits.
func DefaultConfig ¶ added in v1.0.6
func DefaultConfig() Config
DefaultConfig returns the scheduler defaults defined by the rollout plan.
type DemandStat ¶ added in v1.0.6
type DemandStat struct {
Countries []string // Sorted ISO codes; empty means any country
Waiters int
Served int64 // Proxies handed out through this demand
Target int // Alive proxies the pool maintains for this country set
Alive int // Alive proxies currently matching; set by Snapshot only
State string // "waiting", "hunting", "replenishing" or "satisfied"; set by Snapshot only
CreatedAt time.Time
ExpiresAt time.Time // End of the hunting window while nothing matches
ReplenishUntil time.Time // End of target maintenance and of the registration
LastSatisfiedAt time.Time
}
DemandStat reports one registered country demand.
type FailReason ¶ added in v1.0.6
type FailReason string
FailReason classifies a failed proxy check.
const ( FailNone FailReason = "" FailTimeout FailReason = "timeout" FailRefused FailReason = "refused" FailRejected FailReason = "rejected" // CONNECT reply non-2xx, SOCKS reply != success FailEOF FailReason = "eof_reset" FailDNS FailReason = "dns" FailTLS FailReason = "tls" FailBadStatus FailReason = "bad_status" // Probe HTTP status outside 200..399 FailLocalNet FailReason = "local_net" FailOther FailReason = "other" )
func (FailReason) Soft ¶ added in v1.0.6
func (r FailReason) Soft() bool
Soft reports whether the reason is a transient local or upstream condition that must not hard-ban the proxy.
func (FailReason) Valid ¶ added in v1.0.6
func (r FailReason) Valid() bool
Valid reports whether the reason is a known non-empty constant.
type Mode ¶ added in v1.0.6
type Mode string // "foreground", "background"
Mode is the pool scheduling mode.
type NetSnapshot ¶ added in v1.0.6
type NetSnapshot struct {
State NetState // "good", "degraded", "down"
RTT time.Duration // Median of the last 3 successful samples, 0 if none
UpdatedAt time.Time // UTC timestamp of the last sample
}
NetSnapshot is the last published network health sample. Defined here because PoolStats references it; the publishing prober lives in nethealth.go.
type NetState ¶ added in v1.0.6
type NetState string // "good", "degraded", "down"
NetState is the state of the local network connection of the host.
type ParsedEndpoint ¶ added in v1.0.5
type ParsedEndpoint struct {
Canonical string // e.g. "socks5://user:pass@1.2.3.4:1080"
Host string // target IP or hostname
Port int // target port
}
ParsedEndpoint is a normalized proxy endpoint: canonical URL plus the dial-relevant host and port.
type PoolEvent ¶ added in v1.0.6
type PoolEvent struct {
Time time.Time // UTC timestamp of the event
Kind string // "mode_change", "net_change", "limit_change", "ingest_done", "breaker_open", "breaker_close", "demand_created", "demand_satisfied", "demand_expired", "require_timeout"
Fields map[string]string // Stringified details, e.g. {"from":"foreground","to":"background"}
}
PoolEvent records a pool state transition.
type PoolStats ¶ added in v1.0.6
type PoolStats struct {
Time time.Time
Mode Mode
Net NetSnapshot
Limit int
Inflight int
Alive int
Suspect int
Banned int
Queued int // Candidate queue length
Lanes []LaneStats
Sources []SourceStats // Sorted by Source
BanReasons map[FailReason]int
LastIngestAt time.Time
Demands []DemandStat // Registered country demands, sorted by key
// ForcedForeground reports that ForceForeground is active: the candidate
// queue is processed by the foreground lane regardless of Mode.
ForcedForeground bool
}
PoolStats is a point-in-time pool snapshot reported on StatsInterval.
type ProxyFilter ¶
type ProxyInfo ¶
type ProxyInfo struct {
URL string `json:"url"`
IP string `json:"ip"`
Port int `json:"port"`
Location string `json:"location"`
Latency time.Duration `json:"latency"`
Score float64 `json:"score"`
LastChecked time.Time `json:"last_checked"`
}
ProxyInfo represents a validated, consumer-ready proxy returned by ListProxies.
type ProxyPool ¶
type ProxyPool struct {
// contains filtered or unexported fields
}
ProxyPool coordinates proxy discovery, lifecycle health, scheduling, and consumer queries.
func NewPool ¶
func NewPool(cache CacheSource) (*ProxyPool, error)
NewPool initializes a pool with the given storage backend and no-op reporting. The cache argument is required; a nil cache returns an error.
func (*ProxyPool) ForceForeground ¶ added in v1.3.0
ForceForeground makes the foreground lane work through the candidate queue at full speed regardless of the pool mode. In background mode candidates are otherwise checked slowly (a fifth of the limit, rate-limited).
The override ends by itself once the candidate queue is empty and no candidate check is in flight. Candidates added by a later ingest are not covered. It returns the number of candidates waiting at the call; zero means there is nothing to force and no override is set.
func (*ProxyPool) GetMetadata ¶
GetMetadata returns a detached copy of custom metadata for the given proxy URL.
func (*ProxyPool) ListProxies ¶
func (p *ProxyPool) ListProxies(filter ProxyFilter) []ProxyInfo
ListProxies reads only the in-memory alive index.
func (*ProxyPool) MarkDead ¶ added in v1.0.3
MarkDead excludes the proxy with the given canonical URL until an escalating ban expires.
func (*ProxyPool) NetHealth ¶ added in v1.0.6
func (p *ProxyPool) NetHealth() NetSnapshot
func (*ProxyPool) RecheckBanned ¶ added in v1.0.6
RecheckBanned queues banned proxies for the revival lane without changing their ban schedule.
func (*ProxyPool) Refresh ¶
func (p *ProxyPool) Refresh()
Refresh performs one blocking scheduler drain without starting background goroutines. It ingests all sources, then checks candidates and due cached proxies using the same queues, limiter, and checkOneForced implementation used by Start. It returns when candQ is empty and no live or banned items are due at the current time.
func (*ProxyPool) RegisterProxySource ¶
func (p *ProxyPool) RegisterProxySource(source ProxySource)
RegisterProxySource adds an upstream proxy feed provider.
func (*ProxyPool) RegisterReporter ¶
RegisterReporter registers a structured telemetry handler.
func (*ProxyPool) RequestIngest ¶ added in v1.0.6
func (p *ProxyPool) RequestIngest()
RequestIngest schedules an asynchronous source ingest when the pool is running.
func (*ProxyPool) Require ¶ added in v1.0.6
func (p *ProxyPool) Require(ctx context.Context, opts RequireOptions) (RequireResult, error)
Require returns alive proxies matching the options. When none match, it registers a country demand and waits until a match becomes alive, the timeout elapses, or ctx is done.
Cancelling ctx stops only this caller. The demand stays registered until its TTL expires so the pool keeps working on it. On timeout Require returns TimedOut=true with a nil error; the caller decides the fallback policy.
func (*ProxyPool) Reset ¶ added in v1.3.0
func (p *ProxyPool) Reset()
Reset drops every in-memory structure derived from the cache: the alive index, the candidate and revival queues and the force override. Call it after the cache was cleared externally. The pool must be stopped; a running scheduler would keep working on tasks it already holds.
func (*ProxyPool) SetLimits ¶ added in v1.0.6
SetLimits sets the dynamic concurrency range and current initial limit.
func (*ProxyPool) SetTimeout ¶
func (p *ProxyPool) SetTimeout(c TimeoutConfig)
SetTimeout replaces the network budgets for handshakes and latency probes.
func (*ProxyPool) Snapshot ¶ added in v1.0.6
Snapshot returns the current pool state without performing network I/O.
func (*ProxyPool) Start ¶ added in v1.0.6
Start initializes persisted scheduler state and starts background ingest and dispatch. The method is non-blocking and is idempotent.
func (*ProxyPool) Stop ¶ added in v1.0.6
func (p *ProxyPool) Stop()
Stop cancels all background scheduler goroutines and waits for them to exit.
type ProxyReport ¶
type ProxyReport struct {
Timestamp time.Time // UTC timestamp of the event
URL string // Normalized proxy URL
Source string // Name of the source that first reported the proxy
Location string // Discovered ISO country code
FailReason FailReason // Classification of the failed check; empty on success
Lane string // Scheduler lane that ran the check; empty before the lane scheduler
IsDead bool // Operational status after check
Score float64 // Reputation score [0.0 - 10.0]
Penalty float64 // Current backoff penalty weight
ReviveAt time.Time // Scheduled revival timestamp if dead
Latency time.Duration // Measured latency during check (0 if failed/skipped)
Died bool // True if transitioned from Alive -> Dead
Revived bool // True if transitioned from Dead -> Probed/Alive
}
ProxyReport contains telemetry for a single proxy evaluated during a cycle.
type ProxySource ¶
type ProxySource interface {
Name() string // Unique identifier for logging/metrics
FetchList() []string // Returns raw proxy URLs; empty slice means no changes (e.g., 304)
}
ProxySource provides raw proxy URLs from any upstream feed. Upstream rate-limiting, ETag/Last-Modified caching, and format decoding belong entirely inside the source implementation.
type ProxyState ¶
type ProxyState struct {
URL string // Canonical proxy URL (e.g., "http://1.2.3.4:8080", "socks5://user:pass@1.2.3.4:1080")
IP string // Target IP or hostname
Port int // Target port
Location string // 2-letter ISO country code discovered via Cloudflare trace (e.g., "DE")
IsDead bool // Operational status
// Source is the name of the first source that reported this proxy.
Source string
// FailReason classifies the last failed check; empty when the last check passed.
FailReason FailReason
// SoftFails counts consecutive soft failures; reset on success.
SoftFails int
// Suspect excludes the proxy from listings and queues an immediate recheck.
Suspect bool
// LastSeenInSource is the last time any source reported this URL.
LastSeenInSource time.Time
Penalty float64 // Accumulated backoff penalty weight
Score float64 // Reputation credit [0.0 - 10.0]
ReviveAt time.Time // Timestamp when dead proxy can be re-tested
LastCheckedAt time.Time // Timestamp of last probe (used for delta normalization)
Latency time.Duration // Last measured round-trip time
Metadata map[string]string // Optional user-attached custom metadata (nil = none)
}
ProxyState holds internal lifecycle, scoring, and operational metadata. Stored inside CacheSource and managed solely by ProxyPool.
type Reporter ¶ added in v1.0.6
type Reporter interface {
ReportProxy(ProxyReport) // One call per finished check
ReportStats(PoolStats) // Every Config.StatsInterval
ReportEvent(PoolEvent) // State transitions
}
Reporter receives structured pool telemetry.
type RequireOptions ¶ added in v1.0.6
type RequireOptions struct {
// Countries is an OR list of ISO country codes. Empty accepts any country.
Countries []string
// Exclude lists proxy URLs that must not be returned to this caller.
Exclude []string
// Limit is the maximum number of distinct proxies returned. Values below 1 mean 1.
Limit int
// Timeout is the overall deadline of the call. Zero uses Config.RequireTimeout.
Timeout time.Duration
// Want is the number of alive proxies the pool should keep for Countries after
// this call. Zero uses Config.CountryTarget. It has no effect without Countries.
Want int
}
RequireOptions describes one Require call.
type RequireResult ¶ added in v1.0.6
RequireResult is the outcome of Require. Proxies is empty when TimedOut is true.
type SourceStats ¶ added in v1.0.6
type SourceStats struct {
Source string
Alive int
Suspect int
Banned int
Queued int // Candidates of this source still in the candidate queue
BanReasons map[FailReason]int // Among banned
}
SourceStats aggregates pool composition per source.
type TaggedSource ¶ added in v1.0.6
type TaggedSource interface {
FetchTagged() []TaggedURL
}
TaggedSource optionally supplies per-URL source tags during ingest.
type TaggedURL ¶ added in v1.0.6
type TaggedURL struct {
URL string
Source string
// Country is an optional two-letter hint from the source. It only orders
// candidates; the real location is confirmed by the probe.
Country string
}
TaggedURL associates one source identity with a raw URL.
type TimeoutConfig ¶ added in v1.0.5
TimeoutConfig bounds the two probe phases independently. It is the single source of truth for network budgets.
func DefaultTimeoutConfig ¶ added in v1.0.5
func DefaultTimeoutConfig() TimeoutConfig
DefaultTimeoutConfig returns the default handshake and probe budgets.
func (TimeoutConfig) Resolve ¶ added in v1.0.5
func (c TimeoutConfig) Resolve() TimeoutConfig
Resolve fills non-positive timeout fields with defaults.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
proxy_lab
command
|
|
|
proxypoold
command
Command proxypoold is the bundled sidecar for opencode's proxy pool.
|
Command proxypoold is the bundled sidecar for opencode's proxy pool. |