Skip to main content

Source

Struct Source 

Source
pub struct Source {
    pub url: String,
    pub user_agent: String,
    pub regex_pattern: String,
    pub compiled_regex: Option<SerializableRegex>,
    pub last_used_at: Option<DateTime<Utc>>,
    pub use_count: usize,
    pub failure_count: usize,
    pub last_failure_reason: Option<String>,
    pub last_failure_code: Option<u16>,
    pub parameters: HashMap<String, String>,
    pub proxies_found: usize,
}
Expand description

Represents a source of proxy servers.

A source defines where and how to obtain proxy server information, including the URL to fetch from, the user agent to use in requests, and the regex pattern for extracting proxy information from the response.

The struct also tracks usage statistics such as success rates and failure counts to help evaluate source reliability over time.

§Examples

use gooty_proxy::definitions::source::Source;

let source = Source::new(
    "https://example.com/proxy-list".to_string(),
    "Mozilla/5.0 (compatible; Gooty/1.0)".to_string(),
    r"(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{2,5})".to_string(),
).unwrap();

assert_eq!(source.url, "https://example.com/proxy-list");
assert_eq!(source.success_rate(), 0.0); // New source with no usage yet

Fields§

§url: String

The URL of the proxy source.

§user_agent: String

The User-Agent string to use when making requests to the source.

§regex_pattern: String

The regex pattern to use for extracting proxy information from the source.

§compiled_regex: Option<SerializableRegex>

Compiled regex object for performance

§last_used_at: Option<DateTime<Utc>>

When the source was last used

§use_count: usize

Number of times the source has been used

§failure_count: usize

Number of times the source has failed

§last_failure_reason: Option<String>

Last failure reason

§last_failure_code: Option<u16>

Last failure HTTP status code if applicable

§parameters: HashMap<String, String>

Additional parameters for the source

§proxies_found: usize

Number of proxies found from this source

Implementations§

Source§

impl Source

Source

pub fn new( url: String, user_agent: String, regex_pattern: String, ) -> Result<Self, SourceError>

Creates a new proxy source with the required fields.

This constructor validates both the URL and regex pattern to ensure they’re well-formed before creating the source instance.

§Arguments
  • url - The URL where proxy information can be obtained
  • user_agent - The User-Agent string to use in HTTP requests
  • regex_pattern - A regular expression pattern that extracts proxy data from responses
§Returns

A new Source instance if validation succeeds

§Errors

This function will return an error if:

  • The URL is malformed or invalid
  • The regex pattern is invalid or cannot be compiled
Source

pub fn add_parameter(&mut self, key: String, value: String)

Adds a parameter to the source configuration.

Parameters will be appended to the source URL as query parameters when making HTTP requests.

§Arguments
  • key - The parameter name
  • value - The parameter value
§Examples
source.add_parameter("country".to_string(), "US".to_string());
source.add_parameter("type".to_string(), "https".to_string());

let url = source.get_full_url();
assert!(url.contains("country=US"));
assert!(url.contains("type=https"));
Source

pub fn remove_parameter(&mut self, key: &str) -> Option<String>

Removes a parameter from the source configuration.

§Arguments
  • key - The name of the parameter to remove
§Returns

The previous value of the parameter if it was set, or None if it wasn’t present

§Examples
source.add_parameter("country".to_string(), "US".to_string());

let value = source.remove_parameter("country");
assert_eq!(value, Some("US".to_string()));
Source

pub fn record_use(&mut self)

Records a successful use of the source.

This method updates usage statistics by incrementing the use count and recording the current time as the last used timestamp.

Source

pub fn record_failure(&mut self, reason: String, status_code: Option<u16>)

Records a failure when using the source.

This method updates failure statistics and records the reason and optional status code for the failure.

§Arguments
  • reason - A description of why the source failed
  • status_code - Optional HTTP status code if the failure was related to an HTTP response
Source

pub fn success_rate(&self) -> usize

Returns the success rate of using this source.

The success rate is calculated as the ratio of successful uses to total uses. If the source has never been used, returns 0.0.

§Returns

A float between 0.0 and 1.0 representing the success rate where 1.0 means 100% success.

Source

pub fn update_regex_pattern( &mut self, new_pattern: String, ) -> Result<(), SourceError>

Updates the regex pattern and recompiles it.

This is useful when the pattern needs to be adjusted based on changes to the source format.

§Arguments
  • new_pattern - The new regex pattern to use
§Returns

Ok(()) if the pattern was valid and updated successfully

§Errors

Returns an error if the new regex pattern is invalid

Source

pub fn validate(&self) -> Result<(), SourceError>

Validates the source configuration.

This method checks that the URL is well-formed and the regex pattern is valid.

§Returns

Ok(()) if the source is valid

§Errors

Returns an error if:

  • The URL is invalid
  • The regex pattern is invalid
Source

pub fn get_full_url(&self) -> String

Returns a constructed URL with parameters.

This method takes the base URL and appends any parameters that have been added to the source as query parameters.

§Returns

The complete URL including query parameters

§Examples
source.add_parameter("token".to_string(), "abc123".to_string());

let url = source.get_full_url();
assert_eq!(url, "https://example.com/api?token=abc123");
Source

pub async fn fetch_proxies( &self, requestor: &Requestor, ) -> SourceResult<Vec<Proxy>>

Fetches proxies from this source.

Makes an HTTP request to the source URL and extracts proxies from the response using the defined regex pattern.

§Arguments
  • requestor - The HTTP client to use for making requests
§Returns

A vector of Proxy objects extracted from the source

§Errors

This function will return an error if:

  • The HTTP request fails
  • The regex pattern isn’t compiled properly
  • The response can’t be parsed
Source

pub async fn fetch_proxies_with_response( &self, requestor: &Requestor, ) -> SourceResult<(Vec<Proxy>, String)>

Fetches proxies and returns both the proxies and raw response.

Similar to fetch_proxies but also returns the raw response text, which can be useful for debugging or further processing.

§Arguments
  • requestor - The HTTP client to use for making requests
§Returns

A tuple containing:

  • A vector of Proxy objects extracted from the source
  • The raw response text
§Errors

This function will return an error if:

  • The HTTP request fails
  • The regex pattern isn’t compiled properly
  • The response can’t be parsed
Source§

impl Source

Functions for serialization and deserialization

Source

pub fn to_json(&self) -> Result<String, Error>

Serializes the source to a JSON string.

§Returns

A JSON string representation of the Source if successful

§Errors

Returns a serde_json::Error if serialization fails

Source

pub fn from_json(json: &str) -> Result<Self, Error>

Deserializes a source from a JSON string.

This method also recompiles the regex pattern after deserialization.

§Arguments
  • json - A JSON string representation of a Source
§Returns

A Source object if deserialization succeeds

§Errors

Returns a serde_json::Error if deserialization fails

Trait Implementations§

Source§

impl Clone for Source

Source§

fn clone(&self) -> Source

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Source

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for Source

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Eq for Source

Source§

impl PartialEq for Source

Source§

fn eq(&self, other: &Source) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for Source

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for Source

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

Source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<(), Error>

Source§

fn do_erased_serialize( &self, serializer: &mut dyn Serializer, ) -> Result<(), ErrorImpl>

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

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