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, 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(crate) async fn get<T: DeserializeOwned>(
141 &self,
142 path: &str,
143 query: &[(&str, String)],
144 ) -> Result<T, Error> {
145 let res = self.send(Method::GET, path, query, None, JSON).await?;
146 decode(res).await
147 }
148
149 pub(crate) async fn post<T: DeserializeOwned, B: Serialize + ?Sized>(
150 &self,
151 path: &str,
152 body: &B,
153 ) -> Result<T, Error> {
154 let res = self.post_raw(path, body, None).await?;
155 decode(res).await
156 }
157
158 pub(crate) async fn post_raw<B: Serialize + ?Sized>(
159 &self,
160 path: &str,
161 body: &B,
162 timeout: Option<Duration>,
163 ) -> Result<Response, Error> {
164 let body = serde_json::to_vec(body)?;
165 self.send(
166 Method::POST,
167 path,
168 &[],
169 Some(body),
170 Opts { timeout, ..JSON },
171 )
172 .await
173 }
174
175 pub(crate) async fn post_keyless<T: DeserializeOwned, B: Serialize + ?Sized>(
176 &self,
177 path: &str,
178 body: &B,
179 ) -> Result<T, Error> {
180 let body = serde_json::to_vec(body)?;
181 let opts = Opts {
182 auth: false,
183 ..JSON
184 };
185 let res = self.send(Method::POST, path, &[], Some(body), opts).await?;
186 decode(res).await
187 }
188
189 pub(crate) async fn get_text(
190 &self,
191 path: &str,
192 query: &[(&str, String)],
193 accept: &str,
194 ) -> Result<String, Error> {
195 let res = self
196 .send(Method::GET, path, query, None, Opts { accept, ..JSON })
197 .await?;
198 Ok(res.text().await?)
199 }
200
201 async fn send(
202 &self,
203 method: Method,
204 path: &str,
205 query: &[(&str, String)],
206 body: Option<Vec<u8>>,
207 opts: Opts<'_>,
208 ) -> Result<Response, Error> {
209 let inner = &self.inner;
210 let url = format!("{}/v1{}", inner.base_url, path);
211 let retries = if method == Method::GET {
212 inner.max_retries
213 } else {
214 0
215 };
216 let mut attempt = 0;
217 loop {
218 let mut req = inner
219 .http
220 .request(method.clone(), &url)
221 .timeout(opts.timeout.unwrap_or(inner.timeout))
222 .header(USER_AGENT, USER_AGENT_VALUE)
223 .header(ACCEPT, opts.accept);
224 if !query.is_empty() {
225 req = req.query(query);
226 }
227 if let Some(key) = inner.api_key.as_ref().filter(|_| opts.auth) {
228 req = req.header(AUTHORIZATION, format!("Bearer {key}"));
229 }
230 if let Some(b) = &body {
231 req = req
232 .header(CONTENT_TYPE, HeaderValue::from_static("application/json"))
233 .body(b.clone());
234 }
235
236 match req.send().await {
237 Ok(res) => {
238 let status = res.status();
239 if status.is_success() {
240 return Ok(res);
241 }
242 if attempt < retries && matches!(status.as_u16(), 502..=504) {
243 backoff(attempt).await;
244 attempt += 1;
245 continue;
246 }
247 let headers = res.headers().clone();
248 let text = res.text().await.unwrap_or_default();
249 return Err(error::from_response(status, &headers, text));
250 }
251 Err(e) => {
252 if attempt < retries && !e.is_builder() {
253 backoff(attempt).await;
254 attempt += 1;
255 continue;
256 }
257 return Err(e.into());
258 }
259 }
260 }
261 }
262}
263
264async fn backoff(attempt: u32) {
265 tokio::time::sleep(Duration::from_millis(500 << attempt)).await;
266}
267
268async fn decode<T: DeserializeOwned>(res: Response) -> Result<T, Error> {
269 let bytes = res.bytes().await?;
270 Ok(serde_json::from_slice(&bytes)?)
271}
272
273pub(crate) fn segment(s: &str) -> String {
275 let mut out = String::with_capacity(s.len());
276 for b in s.bytes() {
277 if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'.' | b'_' | b'~') {
278 out.push(b as char);
279 } else {
280 out.push_str(&format!("%{b:02X}"));
281 }
282 }
283 out
284}
285
286#[derive(Default)]
288pub struct ClientBuilder {
289 api_key: Option<String>,
290 base_url: Option<String>,
291 timeout: Option<Duration>,
292 max_retries: Option<u32>,
293 http_client: Option<reqwest::Client>,
294}
295
296impl ClientBuilder {
297 pub fn api_key(mut self, key: impl Into<String>) -> Self {
299 self.api_key = Some(key.into());
300 self
301 }
302
303 pub fn base_url(mut self, url: impl Into<String>) -> Self {
305 self.base_url = Some(url.into());
306 self
307 }
308
309 pub fn timeout(mut self, timeout: Duration) -> Self {
311 self.timeout = Some(timeout);
312 self
313 }
314
315 pub fn max_retries(mut self, n: u32) -> Self {
317 self.max_retries = Some(n);
318 self
319 }
320
321 pub fn http_client(mut self, client: reqwest::Client) -> Self {
323 self.http_client = Some(client);
324 self
325 }
326
327 pub fn build(self) -> Result<Client, Error> {
329 let http = match self.http_client {
330 Some(c) => c,
331 None => reqwest::Client::builder().build()?,
332 };
333 let base_url = self
334 .base_url
335 .unwrap_or_else(|| DEFAULT_BASE_URL.to_string())
336 .trim_end_matches('/')
337 .to_string();
338 let api_key = self
339 .api_key
340 .map(|k| k.trim().to_string())
341 .filter(|k| !k.is_empty());
342 Ok(Client {
343 inner: Arc::new(Inner {
344 http,
345 base_url,
346 api_key,
347 timeout: self.timeout.unwrap_or(DEFAULT_TIMEOUT),
348 max_retries: self.max_retries.unwrap_or(DEFAULT_MAX_RETRIES),
349 }),
350 })
351 }
352}
353
354#[cfg(test)]
355mod tests {
356 use super::segment;
357
358 #[test]
359 fn escapes_ipv6() {
360 assert_eq!(segment("2001:db8::1"), "2001%3Adb8%3A%3A1");
361 assert_eq!(segment("1.1.1.1"), "1.1.1.1");
362 assert_eq!(segment("a/b"), "a%2Fb");
363 }
364}