1use std::sync::Arc;
2use std::time::Duration;
3
4use reqwest::header::{HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_TYPE, USER_AGENT};
5use reqwest::{Method, Response};
6use serde::de::DeserializeOwned;
7use serde::Serialize;
8
9use crate::error::{self, Error};
10use crate::resources::{
11 Account, Agentscan, AsnDirectory, Bulk, Crawlers, Edge, Email, Gate, Ip, Provenance, Sites,
12};
13
14pub const DEFAULT_BASE_URL: &str = "https://ipscanner.io";
16
17const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
18const DEFAULT_MAX_RETRIES: u32 = 2;
19const USER_AGENT_VALUE: &str = concat!("ipscanner-rust/", env!("CARGO_PKG_VERSION"));
20
21#[derive(Clone, Copy)]
22struct Opts<'a> {
23 accept: &'a str,
24 timeout: Option<Duration>,
25 auth: bool,
26}
27
28const JSON: Opts<'static> = Opts {
29 accept: "application/json",
30 timeout: None,
31 auth: true,
32};
33
34#[derive(Clone)]
36pub struct Client {
37 inner: Arc<Inner>,
38}
39
40struct Inner {
41 http: reqwest::Client,
42 base_url: String,
43 api_key: Option<String>,
44 timeout: Duration,
45 max_retries: u32,
46}
47
48impl std::fmt::Debug for Client {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 f.debug_struct("Client")
51 .field("base_url", &self.inner.base_url)
52 .field(
53 "api_key",
54 &self.inner.api_key.as_ref().map(|_| "[redacted]"),
55 )
56 .field("timeout", &self.inner.timeout)
57 .field("max_retries", &self.inner.max_retries)
58 .finish()
59 }
60}
61
62impl Client {
63 pub fn new(api_key: impl Into<String>) -> Self {
65 Self::builder()
66 .api_key(api_key)
67 .build()
68 .expect("failed to build HTTP client")
69 }
70
71 pub fn from_env() -> Self {
73 let mut b = Self::builder();
74 if let Ok(key) = std::env::var("IPSCANNER_API_KEY") {
75 b = b.api_key(key);
76 }
77 if let Ok(url) = std::env::var("IPSCANNER_API_URL") {
78 if !url.trim().is_empty() {
79 b = b.base_url(url);
80 }
81 }
82 b.build().expect("failed to build HTTP client")
83 }
84
85 pub fn builder() -> ClientBuilder {
87 ClientBuilder::default()
88 }
89
90 pub fn ip(&self) -> Ip<'_> {
92 Ip::new(self)
93 }
94
95 pub fn bulk(&self) -> Bulk<'_> {
97 Bulk::new(self)
98 }
99
100 pub fn agentscan(&self) -> Agentscan<'_> {
102 Agentscan::new(self)
103 }
104
105 pub fn provenance(&self) -> Provenance<'_> {
107 Provenance::new(self)
108 }
109
110 pub fn account(&self) -> Account<'_> {
112 Account::new(self)
113 }
114
115 pub fn asn_directory(&self) -> AsnDirectory<'_> {
117 AsnDirectory::new(self)
118 }
119
120 pub fn crawlers(&self) -> Crawlers<'_> {
122 Crawlers::new(self)
123 }
124
125 pub fn edge(&self) -> Edge<'_> {
127 Edge::new(self)
128 }
129
130 pub fn sites(&self) -> Sites<'_> {
132 Sites::new(self)
133 }
134
135 pub fn gate(&self) -> Gate<'_> {
137 Gate::new(self)
138 }
139
140 pub fn email(&self) -> Email<'_> {
142 Email::new(self)
143 }
144
145 pub(crate) async fn get<T: DeserializeOwned>(
146 &self,
147 path: &str,
148 query: &[(&str, String)],
149 ) -> Result<T, Error> {
150 let res = self.send(Method::GET, path, query, None, JSON).await?;
151 decode(res).await
152 }
153
154 pub(crate) async fn post<T: DeserializeOwned, B: Serialize + ?Sized>(
155 &self,
156 path: &str,
157 body: &B,
158 ) -> Result<T, Error> {
159 let res = self.post_raw(path, body, None).await?;
160 decode(res).await
161 }
162
163 pub(crate) async fn post_raw<B: Serialize + ?Sized>(
164 &self,
165 path: &str,
166 body: &B,
167 timeout: Option<Duration>,
168 ) -> Result<Response, Error> {
169 let body = serde_json::to_vec(body)?;
170 self.send(
171 Method::POST,
172 path,
173 &[],
174 Some(body),
175 Opts { timeout, ..JSON },
176 )
177 .await
178 }
179
180 pub(crate) async fn post_keyless<T: DeserializeOwned, B: Serialize + ?Sized>(
181 &self,
182 path: &str,
183 body: &B,
184 ) -> Result<T, Error> {
185 let body = serde_json::to_vec(body)?;
186 let opts = Opts {
187 auth: false,
188 ..JSON
189 };
190 let res = self.send(Method::POST, path, &[], Some(body), opts).await?;
191 decode(res).await
192 }
193
194 pub(crate) async fn get_text(
195 &self,
196 path: &str,
197 query: &[(&str, String)],
198 accept: &str,
199 ) -> Result<String, Error> {
200 let res = self
201 .send(Method::GET, path, query, None, Opts { accept, ..JSON })
202 .await?;
203 Ok(res.text().await?)
204 }
205
206 async fn send(
207 &self,
208 method: Method,
209 path: &str,
210 query: &[(&str, String)],
211 body: Option<Vec<u8>>,
212 opts: Opts<'_>,
213 ) -> Result<Response, Error> {
214 let inner = &self.inner;
215 let url = format!("{}/v1{}", inner.base_url, path);
216 let retries = if method == Method::GET {
217 inner.max_retries
218 } else {
219 0
220 };
221 let mut attempt = 0;
222 loop {
223 let mut req = inner
224 .http
225 .request(method.clone(), &url)
226 .timeout(opts.timeout.unwrap_or(inner.timeout))
227 .header(USER_AGENT, USER_AGENT_VALUE)
228 .header(ACCEPT, opts.accept);
229 if !query.is_empty() {
230 req = req.query(query);
231 }
232 if let Some(key) = inner.api_key.as_ref().filter(|_| opts.auth) {
233 req = req.header(AUTHORIZATION, format!("Bearer {key}"));
234 }
235 if let Some(b) = &body {
236 req = req
237 .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
238 .body(b.clone());
239 }
240
241 match req.send().await {
242 Ok(res) => {
243 let status = res.status();
244 if status.is_success() {
245 return Ok(res);
246 }
247 if attempt < retries && matches!(status.as_u16(), 502..=504) {
248 backoff(attempt).await;
249 attempt += 1;
250 continue;
251 }
252 let headers = res.headers().clone();
253 let text = res.text().await.unwrap_or_default();
254 return Err(error::from_response(status, &headers, text));
255 }
256 Err(e) => {
257 if attempt < retries && !e.is_builder() {
258 backoff(attempt).await;
259 attempt += 1;
260 continue;
261 }
262 return Err(e.into());
263 }
264 }
265 }
266 }
267}
268
269async fn backoff(attempt: u32) {
270 tokio::time::sleep(Duration::from_millis(500 << attempt)).await;
271}
272
273async fn decode<T: DeserializeOwned>(res: Response) -> Result<T, Error> {
274 let bytes = res.bytes().await?;
275 Ok(serde_json::from_slice(&bytes)?)
276}
277
278pub(crate) fn segment(s: &str) -> String {
280 let mut out = String::with_capacity(s.len());
281 for b in s.bytes() {
282 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
283 out.push(b as char);
284 } else {
285 out.push_str(&format!("%{b:02X}"));
286 }
287 }
288 out
289}
290
291#[derive(Default)]
293pub struct ClientBuilder {
294 api_key: Option<String>,
295 base_url: Option<String>,
296 timeout: Option<Duration>,
297 max_retries: Option<u32>,
298 http_client: Option<reqwest::Client>,
299}
300
301impl ClientBuilder {
302 pub fn api_key(mut self, key: impl Into<String>) -> Self {
304 self.api_key = Some(key.into());
305 self
306 }
307
308 pub fn base_url(mut self, url: impl Into<String>) -> Self {
310 self.base_url = Some(url.into());
311 self
312 }
313
314 pub fn timeout(mut self, timeout: Duration) -> Self {
316 self.timeout = Some(timeout);
317 self
318 }
319
320 pub fn max_retries(mut self, n: u32) -> Self {
322 self.max_retries = Some(n);
323 self
324 }
325
326 pub fn http_client(mut self, client: reqwest::Client) -> Self {
328 self.http_client = Some(client);
329 self
330 }
331
332 pub fn build(self) -> Result<Client, Error> {
334 let http = match self.http_client {
335 Some(c) => c,
336 None => reqwest::Client::builder().build()?,
337 };
338 let base_url = self
339 .base_url
340 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
341 .trim_end_matches('/')
342 .to_string();
343 let api_key = self
344 .api_key
345 .map(|k| k.trim().to_string())
346 .filter(|k| !k.is_empty());
347 Ok(Client {
348 inner: Arc::new(Inner {
349 http,
350 base_url,
351 api_key,
352 timeout: self.timeout.unwrap_or(DEFAULT_TIMEOUT),
353 max_retries: self.max_retries.unwrap_or(DEFAULT_MAX_RETRIES),
354 }),
355 })
356 }
357}
358
359#[cfg(test)]
360mod tests {
361 use super::segment;
362
363 #[test]
364 fn escapes_ipv6() {
365 assert_eq!(segment("2001:db8::1"), "2001%3Adb8%3A%3A1");
366 assert_eq!(segment("1.1.1.1"), "1.1.1.1");
367 assert_eq!(segment("a/b"), "a%2Fb");
368 }
369}