1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 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
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
#[allow(unused_imports)]
use crate::internal_prelude::*;
use crate::{
    types,
    resolver::AsyncHyperResolver,
    resolver::Resolver
};

use std::{
    net::{Ipv4Addr, Ipv6Addr},
    ops::Deref,
};

use serde::{Deserialize, Deserializer, de};

type Result<T> = types::Result<T>;

#[derive(Clone, Debug)]
pub struct CLevel(pub Level);

impl Deref for CLevel {
    type Target = Level;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'de> Deserialize<'de> for CLevel {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<CLevel, D::Error> {
        let s: String = Deserialize::deserialize(deserializer)?;
        Level::from_str(&s).map(CLevel).map_err(de::Error::custom)
    }
}

#[derive(Clone, Debug)]
pub struct CIP4Addr(pub Ipv4Addr);

impl Deref for CIP4Addr {
    type Target = Ipv4Addr;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'de> Deserialize<'de> for CIP4Addr {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<CIP4Addr, D::Error> {
        let s: String = Deserialize::deserialize(deserializer)?;
        let addr: Ipv4Addr = s.parse().map_err(de::Error::custom)?;
        Ok(CIP4Addr(addr))
    }
}

#[derive(Clone, Debug)]
pub struct CIP6Addr(pub Ipv6Addr);

impl Deref for CIP6Addr {
    type Target = Ipv6Addr;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'de> Deserialize<'de> for CIP6Addr {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<CIP6Addr, D::Error> {
        let s: String = Deserialize::deserialize(deserializer)?;
        let addr: Ipv6Addr = s.parse().map_err(de::Error::custom)?;
        Ok(CIP6Addr(addr))
    }
}

#[derive(Clone, Debug)]
pub struct CBytes(pub usize);

impl Deref for CBytes {
    type Target = usize;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'de> Deserialize<'de> for CBytes {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<CBytes, D::Error> {
        let s: String = Deserialize::deserialize(deserializer)?;
        let s = s.replace("_","");
        let v = s.parse::<humanize_rs::bytes::Bytes>();
        let r = v.map_err(de::Error::custom)?;
        Ok(CBytes(r.size()))
    }
}

#[derive(Clone, Debug)]
pub struct CDuration(Duration);

impl Deref for CDuration {
    type Target = Duration;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl CDuration {
    pub fn from_secs(secs: u64) -> Self {
        CDuration(Duration::from_secs(secs))
    }
    pub fn from_millis(millis: u64) -> Self { CDuration(Duration::from_millis(millis)) }
}

impl<'de> Deserialize<'de> for CDuration {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> std::result::Result<CDuration, D::Error> {
        let s: String = Deserialize::deserialize(deserializer)?;
        let s = s.replace("_","");
        let v = humanize_rs::duration::parse(&s);
        let r = v.map_err(de::Error::custom)?;
        Ok(CDuration(r))
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct ConcurrencyProfile {
    pub parser_concurrency: usize,
    pub domain_concurrency: usize,
}

impl Default for ConcurrencyProfile {
    fn default() -> Self {
        let physical_cores = num_cpus::get_physical();
        Self {
            parser_concurrency: physical_cores,
            domain_concurrency: physical_cores * 40,
        }
    }
}

impl ConcurrencyProfile {
    pub fn transit_buffer_size(&self) -> usize {
        self.domain_concurrency * 10
    }

    pub fn job_tx_buffer_size(&self) -> usize
    {
        self.domain_concurrency * 3
    }

    pub fn job_update_buffer_size(&self) -> usize {
        self.domain_concurrency * 3
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct NetworkingProfileValues {
    pub connect_timeout: Option<CDuration>,
    pub socket_read_buffer_size: Option<CBytes>,
    pub socket_write_buffer_size: Option<CBytes>,
    pub bind_local_ipv4: Option<CIP4Addr>,
    pub bind_local_ipv6: Option<CIP6Addr>,
}

impl Default for NetworkingProfileValues {
    fn default() -> Self {
        Self{
            connect_timeout: Some(CDuration::from_secs(5)),
            socket_write_buffer_size: Some(CBytes(32 * 1024)),
            socket_read_buffer_size: Some(CBytes(32 * 1024)),
            bind_local_ipv4: None,
            bind_local_ipv6: None,
        }
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct NetworkingProfile<R: Resolver = AsyncHyperResolver> {
    pub values: NetworkingProfileValues,

    #[serde(skip)]
    #[serde(default = "Option::default")]
    pub resolver: Option<Arc<R>>
}

impl Default for NetworkingProfile<AsyncHyperResolver> {
    fn default() -> Self {
        Self{
            values: NetworkingProfileValues::default(),
            resolver: None
        }
    }
}

impl<R: Resolver> NetworkingProfile<R> {
    pub fn resolve(self) -> Result<ResolvedNetworkingProfile<R>> {
        ResolvedNetworkingProfile::new(self)
    }
}

#[derive(Clone, Debug)]
pub struct ResolvedNetworkingProfile<R: Resolver = AsyncHyperResolver> {
    pub values: NetworkingProfileValues,

    pub resolver: Arc<R>
}

impl<R: Resolver> ResolvedNetworkingProfile<R> {
    fn new(p: NetworkingProfile<R>) -> Result<Self> {
        let mut resolver = p.resolver;
        if resolver.is_none() {
            resolver = Some(Arc::new(Resolver::new_default().context("cannot create default resolver")?));
        }
        let resolver = resolver.unwrap();
        Ok(Self {
            values: p.values,
            resolver
        })
    }
}

#[derive(Clone, Debug, Deserialize)]
pub struct CrawlingSettings {
    pub internal_read_buffer_size: CBytes,
    pub concurrency: usize,
    pub max_response_size: CBytes,
    pub delay: CDuration,
    pub delay_jitter: CDuration,
    pub load_timeout: CDuration,
    pub job_soft_timeout: CDuration,
    pub job_hard_timeout: CDuration,
    pub custom_headers: HashMap<String, Vec<String>>,
}

impl fmt::Display for CrawlingSettings {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "concurrency: {}, delay: {:?}, job hard timeout: {:?}, job soft timeout: {:?}, irbs: {:?}, load timeout: {:?}, max_response_size: {:?}, custom headers: {:?}",
            self.concurrency,
            self.delay,
            self.job_hard_timeout,
            self.job_soft_timeout,
            self.internal_read_buffer_size,
            self.load_timeout,
            self.max_response_size,
            self.custom_headers,
        )
    }
}

impl Default for CrawlingSettings {
    fn default() -> Self {
        Self {
            concurrency: 2,
            internal_read_buffer_size: CBytes(32 * 1024),
            delay: CDuration::from_secs(1),
            delay_jitter: CDuration::from_millis(1000),
            job_hard_timeout: CDuration::from_secs(60),
            job_soft_timeout: CDuration::from_secs(30),
            load_timeout: CDuration::from_secs(10),
            custom_headers: [
                (
                    http::header::USER_AGENT.to_string(),
                    vec!["Crusty-core Web Crawler".into()],
                ),
                (
                    http::header::ACCEPT.to_string(),
                    vec!["text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9".into()],
                ),
                (
                    http::header::ACCEPT_ENCODING.to_string(),
                    vec!["gzip, deflate".into()],
                )
            ]
                .iter()
                .cloned()
                .collect(),
            max_response_size: CBytes(1024 * 1024 * 2),
        }
    }
}