hydrafetch 0.1.0

Official Rust client for the Hydrafetch web data API. Turn any URL into clean Markdown and structured data.
Documentation
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
mod error;
mod types;

pub use error::{Error, Result};
pub use types::*;

use serde::Deserialize;
use serde_json::{json, Value};
use std::time::{Duration, Instant};

const DEFAULT_BASE_URL: &str = "https://api.hydrafetch.com";

#[derive(Deserialize)]
struct ApiError {
    code: Option<String>,
    message: Option<String>,
}

#[derive(Deserialize)]
struct Meta {
    #[serde(rename = "requestId")]
    request_id: Option<String>,
}

#[derive(Deserialize)]
struct Envelope {
    success: Option<bool>,
    data: Option<Value>,
    error: Option<ApiError>,
    meta: Option<Meta>,
}

pub struct ClientBuilder {
    api_key: Option<String>,
    base_url: String,
    timeout: Duration,
    max_retries: u32,
}

impl ClientBuilder {
    pub fn api_key(mut self, key: impl Into<String>) -> Self {
        self.api_key = Some(key.into());
        self
    }

    pub fn base_url(mut self, url: impl Into<String>) -> Self {
        self.base_url = url.into().trim_end_matches('/').to_string();
        self
    }

    pub fn timeout(mut self, d: Duration) -> Self {
        self.timeout = d;
        self
    }

    pub fn max_retries(mut self, n: u32) -> Self {
        self.max_retries = n;
        self
    }

    pub fn build(self) -> Result<Client> {
        let api_key = self
            .api_key
            .or_else(|| std::env::var("HYDRAFETCH_API_KEY").ok())
            .filter(|k| !k.is_empty())
            .ok_or(Error::MissingApiKey)?;

        let http = reqwest::Client::builder()
            .timeout(self.timeout)
            .build()
            .map_err(Error::Transport)?;

        Ok(Client {
            api_key,
            base_url: self.base_url,
            http,
            max_retries: self.max_retries,
        })
    }
}

#[derive(Clone, Debug)]
pub struct Client {
    api_key: String,
    base_url: String,
    http: reqwest::Client,
    max_retries: u32,
}

impl Client {
    pub fn builder() -> ClientBuilder {
        ClientBuilder {
            api_key: None,
            base_url: DEFAULT_BASE_URL.to_string(),
            timeout: Duration::from_secs(120),
            max_retries: 2,
        }
    }

    pub fn new(api_key: impl Into<String>) -> Result<Self> {
        Self::builder().api_key(api_key).build()
    }

    pub fn from_env() -> Result<Self> {
        Self::builder().build()
    }

    async fn request<T: for<'de> Deserialize<'de>>(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<Value>,
        query: &[(&str, String)],
    ) -> Result<T> {
        let url = format!("{}{}", self.base_url, path);
        let mut attempt = 0;

        loop {
            let mut req = self
                .http
                .request(method.clone(), &url)
                .header("X-API-Key", &self.api_key)
                .header("Accept", "application/json");

            if !query.is_empty() {
                req = req.query(query);
            }
            if let Some(ref payload) = body {
                req = req.json(payload);
            }

            let response = match req.send().await {
                Ok(r) => r,
                Err(e) if e.is_timeout() => {
                    return Err(Error::Timeout(format!(
                        "request to {path} timed out; raise the timeout, or use the crawl and batch job endpoints for long work"
                    )))
                }
                Err(e) => {
                    if attempt >= self.max_retries {
                        return Err(Error::Transport(e));
                    }
                    attempt += 1;
                    backoff(attempt).await;
                    continue;
                }
            };

            let status = response.status().as_u16();
            let text = response.text().await.map_err(Error::Transport)?;
            let envelope: Option<Envelope> = serde_json::from_str(&text).ok();

            let failed = status >= 400
                || envelope
                    .as_ref()
                    .and_then(|e| e.success)
                    .map(|ok| !ok)
                    .unwrap_or(false);

            if failed {
                let (code, message, request_id) = match envelope {
                    Some(env) => (
                        env.error.as_ref().and_then(|e| e.code.clone()),
                        env.error.as_ref().and_then(|e| e.message.clone()),
                        env.meta.and_then(|m| m.request_id),
                    ),
                    None => (None, None, None),
                };
                let err = Error::Api {
                    code: code.unwrap_or_else(|| format!("HTTP_{status}")),
                    message: message.unwrap_or_else(|| text.chars().take(300).collect()),
                    status,
                    request_id,
                };
                if !err.is_retryable() || attempt >= self.max_retries {
                    return Err(err);
                }
                attempt += 1;
                backoff(attempt).await;
                continue;
            }

            let payload = match envelope.and_then(|e| e.data) {
                Some(data) => data,
                None => serde_json::from_str(&text)?,
            };
            return Ok(serde_json::from_value(payload)?);
        }
    }

    fn merge(base: Value, extra: Option<impl serde::Serialize>) -> Value {
        let mut body = base;
        if let Some(options) = extra {
            if let Ok(Value::Object(fields)) = serde_json::to_value(options) {
                if let Value::Object(ref mut target) = body {
                    for (k, v) in fields {
                        target.insert(k, v);
                    }
                }
            }
        }
        body
    }

    pub async fn scrape(&self, url: &str, options: Option<ScrapeOptions>) -> Result<ScrapeResult> {
        let body = Self::merge(json!({ "url": url }), options);
        self.request(reqwest::Method::POST, "/v1/web/scrape", Some(body), &[])
            .await
    }

    pub async fn markdown(&self, url: &str) -> Result<String> {
        let page = self
            .scrape(
                url,
                Some(ScrapeOptions {
                    formats: Some(vec![Format::Markdown]),
                    ..Default::default()
                }),
            )
            .await?;
        Ok(page.markdown.unwrap_or_default())
    }

    pub async fn map(&self, url: &str, options: Option<MapOptions>) -> Result<MapResult> {
        let body = Self::merge(json!({ "url": url }), options);
        self.request(reqwest::Method::POST, "/v1/web/map", Some(body), &[])
            .await
    }

    pub async fn search(
        &self,
        query: &str,
        options: Option<SearchOptions>,
    ) -> Result<SearchResult> {
        let body = Self::merge(json!({ "query": query }), options);
        self.request(reqwest::Method::POST, "/v1/web/search", Some(body), &[])
            .await
    }

    pub async fn extract(
        &self,
        urls: &[&str],
        options: Option<ExtractOptions>,
    ) -> Result<ExtractResult> {
        let body = Self::merge(json!({ "urls": urls }), options);
        self.request(reqwest::Method::POST, "/v1/web/extract", Some(body), &[])
            .await
    }

    pub async fn brand(&self, domain: &str) -> Result<Value> {
        self.request(
            reqwest::Method::GET,
            "/v1/web/brand",
            None,
            &[("domain", domain.to_string())],
        )
        .await
    }

    pub async fn logo(&self, domain: &str, options: Option<LogoOptions>) -> Result<Value> {
        let mut query = vec![("domain", domain.to_string())];
        if let Some(opts) = options {
            if let Some(theme) = opts.theme {
                query.push(("theme", theme));
            }
            if let Some(kind) = opts.kind {
                query.push(("type", kind));
            }
        }
        self.request(reqwest::Method::GET, "/v1/web/brand/logo", None, &query)
            .await
    }

    pub async fn styleguide(&self, domain: &str) -> Result<Value> {
        self.request(
            reqwest::Method::GET,
            "/v1/web/styleguide",
            None,
            &[("domain", domain.to_string())],
        )
        .await
    }

    pub async fn screenshot(
        &self,
        url: &str,
        options: Option<ScreenshotOptions>,
    ) -> Result<ScreenshotResult> {
        let body = Self::merge(json!({ "url": url }), options);
        self.request(reqwest::Method::POST, "/v1/web/screenshot", Some(body), &[])
            .await
    }

    pub async fn images(&self, url: &str) -> Result<ImagesResult> {
        self.request(
            reqwest::Method::POST,
            "/v1/web/images",
            Some(json!({ "url": url })),
            &[],
        )
        .await
    }

    pub async fn start_crawl(&self, url: &str, options: Option<CrawlOptions>) -> Result<String> {
        let body = Self::merge(json!({ "url": url }), options);
        let payload: Value = self
            .request(reqwest::Method::POST, "/v1/web/crawl", Some(body), &[])
            .await?;
        job_id(&payload, "crawlId")
    }

    pub async fn start_batch(
        &self,
        urls: &[&str],
        options: Option<BatchOptions>,
    ) -> Result<String> {
        let body = Self::merge(json!({ "urls": urls }), options);
        let payload: Value = self
            .request(reqwest::Method::POST, "/v1/web/batch", Some(body), &[])
            .await?;
        job_id(&payload, "batchId")
    }

    pub async fn crawl_status(&self, id: &str) -> Result<Job> {
        self.request(
            reqwest::Method::GET,
            &format!("/v1/web/crawl/{id}"),
            None,
            &[],
        )
        .await
    }

    pub async fn batch_status(&self, id: &str) -> Result<Job> {
        self.request(
            reqwest::Method::GET,
            &format!("/v1/web/batch/{id}"),
            None,
            &[],
        )
        .await
    }

    pub async fn crawl(
        &self,
        url: &str,
        options: Option<CrawlOptions>,
        wait: Option<WaitOptions>,
    ) -> Result<Job> {
        let id = self.start_crawl(url, options).await?;
        self.poll(JobKind::Crawl, &id, wait.unwrap_or_default())
            .await
    }

    pub async fn batch(
        &self,
        urls: &[&str],
        options: Option<BatchOptions>,
        wait: Option<WaitOptions>,
    ) -> Result<Job> {
        let id = self.start_batch(urls, options).await?;
        self.poll(JobKind::Batch, &id, wait.unwrap_or_default())
            .await
    }

    async fn poll(&self, kind: JobKind, id: &str, wait: WaitOptions) -> Result<Job> {
        let deadline = Instant::now() + wait.timeout;
        loop {
            let job = match kind {
                JobKind::Crawl => self.crawl_status(id).await?,
                JobKind::Batch => self.batch_status(id).await?,
            };
            if job.is_done() {
                return Ok(job);
            }
            if Instant::now() + wait.poll_interval > deadline {
                return Err(Error::Timeout(format!(
                    "job did not finish within {:?}; it is still running server-side, so poll its status or pass a webhook",
                    wait.timeout
                )));
            }
            tokio::time::sleep(wait.poll_interval).await;
        }
    }
}

#[derive(Clone, Copy)]
enum JobKind {
    Crawl,
    Batch,
}

fn job_id(payload: &Value, key: &str) -> Result<String> {
    for candidate in [key, "id"] {
        if let Some(value) = payload.get(candidate).and_then(|v| v.as_str()) {
            if !value.is_empty() {
                return Ok(value.to_string());
            }
        }
    }
    Err(Error::Api {
        code: "NO_JOB_ID".into(),
        message: "job accepted but returned no id".into(),
        status: 502,
        request_id: None,
    })
}

async fn backoff(attempt: u32) {
    tokio::time::sleep(Duration::from_millis(250 * 2u64.pow(attempt.min(5)))).await;
}