smop 0.2.1

Batteries-included scripting utilities for Rust
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
//! HTTP client utilities.
//!
//! Simple synchronous HTTP client wrapper around ureq.
//! This module is only available with the `http` feature.

use std::path::Path;

use anyhow::{Context, Result, anyhow};
use serde::{Serialize, de::DeserializeOwned};

/// Performs a GET request and returns the response body as a string.
///
/// # Errors
///
/// Returns an error if the request fails or returns a non-2xx status.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
///
/// let body = http::get("https://httpbin.org/get")?;
/// println!("{}", body);
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn get(url: &str) -> Result<String> {
    let response = ureq::get(url)
        .call()
        .map_err(|e| handle_ureq_error(e, url))?;

    response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))
}

/// Performs a GET request and deserializes the JSON response.
///
/// # Errors
///
/// Returns an error if the request fails, returns a non-2xx status,
/// or if the response body is not valid JSON.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Response {
///     origin: String,
/// }
///
/// let response: Response = http::get_json("https://httpbin.org/get")?;
/// println!("Origin: {}", response.origin);
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn get_json<T: DeserializeOwned>(url: &str) -> Result<T> {
    let body = get(url)?;
    serde_json::from_str(&body)
        .with_context(|| format!("Failed to parse JSON response from: {url}"))
}

/// Performs a POST request with a string body.
///
/// # Errors
///
/// Returns an error if the request fails or returns a non-2xx status.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
///
/// let response = http::post("https://httpbin.org/post", "Hello, world!")?;
/// println!("{}", response);
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn post(url: &str, body: &str) -> Result<String> {
    let response = ureq::post(url)
        .header("Content-Type", "text/plain")
        .send(body.as_bytes())
        .map_err(|e| handle_ureq_error(e, url))?;

    response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))
}

/// Performs a POST request with a JSON body and deserializes the JSON response.
///
/// # Errors
///
/// Returns an error if the request fails, returns a non-2xx status,
/// or if the response body is not valid JSON.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize, Deserialize)]
/// struct Request {
///     name: String,
/// }
///
/// #[derive(Deserialize)]
/// struct Response {
///     json: Request,
/// }
///
/// let request = Request { name: "test".into() };
/// let response: Response = http::post_json("https://httpbin.org/post", &request)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn post_json<T: Serialize, R: DeserializeOwned>(url: &str, body: &T) -> Result<R> {
    let json_body = serde_json::to_string(body)
        .with_context(|| format!("Failed to serialize request body for: {url}"))?;

    let response = ureq::post(url)
        .header("Content-Type", "application/json")
        .send(json_body.as_bytes())
        .map_err(|e| handle_ureq_error(e, url))?;

    let response_body = response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))?;

    serde_json::from_str(&response_body)
        .with_context(|| format!("Failed to parse JSON response from: {url}"))
}

/// Downloads a file from a URL to the specified path.
///
/// # Errors
///
/// Returns an error if the request fails or the file cannot be written.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
///
/// http::download("https://example.com/file.zip", "local.zip")?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn download<P: AsRef<Path>>(url: &str, path: P) -> Result<()> {
    let path = path.as_ref();
    let response = ureq::get(url)
        .call()
        .map_err(|e| handle_ureq_error(e, url))?;

    let mut file = std::fs::File::create(path)
        .with_context(|| format!("Failed to create file: {}", path.display()))?;

    std::io::copy(&mut response.into_body().as_reader(), &mut file)
        .with_context(|| format!("Failed to download {url} to {}", path.display()))?;

    Ok(())
}

/// Performs a PUT request with a string body.
///
/// # Errors
///
/// Returns an error if the request fails or returns a non-2xx status.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
///
/// let response = http::put("https://httpbin.org/put", "data")?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn put(url: &str, body: &str) -> Result<String> {
    let response = ureq::put(url)
        .header("Content-Type", "text/plain")
        .send(body.as_bytes())
        .map_err(|e| handle_ureq_error(e, url))?;

    response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))
}

/// Performs a DELETE request.
///
/// # Errors
///
/// Returns an error if the request fails or returns a non-2xx status.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
///
/// let response = http::delete("https://httpbin.org/delete")?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn delete(url: &str) -> Result<String> {
    let response = ureq::delete(url)
        .call()
        .map_err(|e| handle_ureq_error(e, url))?;

    response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))
}

/// Performs a PATCH request with a string body.
///
/// # Errors
///
/// Returns an error if the request fails or returns a non-2xx status.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
///
/// let response = http::patch("https://httpbin.org/patch", "data")?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn patch(url: &str, body: &str) -> Result<String> {
    let response = ureq::patch(url)
        .header("Content-Type", "text/plain")
        .send(body.as_bytes())
        .map_err(|e| handle_ureq_error(e, url))?;

    response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))
}

/// Performs a PUT request with a JSON body and deserializes the JSON response.
///
/// # Errors
///
/// Returns an error if the request fails or the response is not valid JSON.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize)]
/// struct Request { value: i32 }
///
/// #[derive(Deserialize)]
/// struct Response { value: i32 }
///
/// let req = Request { value: 42 };
/// let res: Response = http::put_json("https://httpbin.org/put", &req)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn put_json<T: Serialize, R: DeserializeOwned>(url: &str, body: &T) -> Result<R> {
    let json_body = serde_json::to_string(body)
        .with_context(|| format!("Failed to serialize request body for: {url}"))?;

    let response = ureq::put(url)
        .header("Content-Type", "application/json")
        .send(json_body.as_bytes())
        .map_err(|e| handle_ureq_error(e, url))?;

    let response_body = response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))?;

    serde_json::from_str(&response_body)
        .with_context(|| format!("Failed to parse JSON response from: {url}"))
}

/// Performs a DELETE request and deserializes the JSON response.
///
/// # Errors
///
/// Returns an error if the request fails or the response is not valid JSON.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Response { deleted: bool }
///
/// let res: Response = http::delete_json("https://httpbin.org/delete")?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn delete_json<R: DeserializeOwned>(url: &str) -> Result<R> {
    let body = delete(url)?;
    serde_json::from_str(&body)
        .with_context(|| format!("Failed to parse JSON response from: {url}"))
}

/// Performs a PATCH request with a JSON body and deserializes the JSON response.
///
/// # Errors
///
/// Returns an error if the request fails or the response is not valid JSON.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Serialize)]
/// struct Request { field: String }
///
/// #[derive(Deserialize)]
/// struct Response { field: String }
///
/// let req = Request { field: "updated".into() };
/// let res: Response = http::patch_json("https://httpbin.org/patch", &req)?;
/// # Ok::<(), anyhow::Error>(())
/// ```
pub fn patch_json<T: Serialize, R: DeserializeOwned>(url: &str, body: &T) -> Result<R> {
    let json_body = serde_json::to_string(body)
        .with_context(|| format!("Failed to serialize request body for: {url}"))?;

    let response = ureq::patch(url)
        .header("Content-Type", "application/json")
        .send(json_body.as_bytes())
        .map_err(|e| handle_ureq_error(e, url))?;

    let response_body = response
        .into_body()
        .read_to_string()
        .with_context(|| format!("Failed to read response body from: {url}"))?;

    serde_json::from_str(&response_body)
        .with_context(|| format!("Failed to parse JSON response from: {url}"))
}

/// Configurable HTTP client with builder pattern.
///
/// # Examples
///
/// ```no_run
/// use smop::http;
///
/// let client = http::Client::new()
///     .timeout(30)
///     .header("X-Api-Key", "secret");
///
/// let response = client.get("https://api.example.com/data")?;
/// # Ok::<(), anyhow::Error>(())
/// ```
#[must_use]
pub struct Client {
    agent: ureq::Agent,
    headers: Vec<(String, String)>,
}

impl Client {
    /// Creates a new HTTP client with default settings.
    pub fn new() -> Self {
        Self {
            agent: ureq::Agent::new_with_defaults(),
            headers: Vec::new(),
        }
    }

    /// Sets the request timeout in seconds.
    pub fn timeout(mut self, seconds: u64) -> Self {
        let config = ureq::config::Config::builder()
            .timeout_global(Some(std::time::Duration::from_secs(seconds)))
            .build();
        self.agent = ureq::Agent::new_with_config(config);
        self
    }

    /// Sets basic authentication credentials.
    pub fn auth(mut self, username: &str, password: &str) -> Self {
        // Note: ureq 3.x handles auth differently - we store as custom header
        // In a real implementation, you'd use the agent's built-in auth methods
        let credentials = format!("{username}:{password}");
        self.headers
            .push(("Authorization".to_string(), format!("Basic {credentials}")));
        self
    }

    /// Adds a custom header to all requests.
    pub fn header(mut self, key: &str, value: &str) -> Self {
        self.headers.push((key.to_string(), value.to_string()));
        self
    }

    /// Performs a GET request.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub fn get(&self, url: &str) -> Result<String> {
        let mut request = self.agent.get(url);
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request.call().map_err(|e| handle_ureq_error(e, url))?;

        response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))
    }

    /// Performs a POST request.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub fn post(&self, url: &str, body: &str) -> Result<String> {
        let mut request = self.agent.post(url).header("Content-Type", "text/plain");
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request
            .send(body.as_bytes())
            .map_err(|e| handle_ureq_error(e, url))?;

        response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))
    }

    /// Performs a GET request and deserializes JSON.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response is not valid JSON.
    pub fn get_json<T: DeserializeOwned>(&self, url: &str) -> Result<T> {
        let body = self.get(url)?;
        serde_json::from_str(&body)
            .with_context(|| format!("Failed to parse JSON response from: {url}"))
    }

    /// Performs a POST request with JSON body and deserializes JSON response.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response is not valid JSON.
    pub fn post_json<T: Serialize, R: DeserializeOwned>(&self, url: &str, body: &T) -> Result<R> {
        let json_body = serde_json::to_string(body)
            .with_context(|| format!("Failed to serialize request body for: {url}"))?;

        let mut request = self
            .agent
            .post(url)
            .header("Content-Type", "application/json");
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request
            .send(json_body.as_bytes())
            .map_err(|e| handle_ureq_error(e, url))?;

        let response_body = response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))?;

        serde_json::from_str(&response_body)
            .with_context(|| format!("Failed to parse JSON response from: {url}"))
    }

    /// Performs a PUT request.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub fn put(&self, url: &str, body: &str) -> Result<String> {
        let mut request = self.agent.put(url).header("Content-Type", "text/plain");
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request
            .send(body.as_bytes())
            .map_err(|e| handle_ureq_error(e, url))?;

        response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))
    }

    /// Performs a DELETE request.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub fn delete(&self, url: &str) -> Result<String> {
        let mut request = self.agent.delete(url);
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request.call().map_err(|e| handle_ureq_error(e, url))?;

        response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))
    }

    /// Performs a PATCH request.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails.
    pub fn patch(&self, url: &str, body: &str) -> Result<String> {
        let mut request = self.agent.patch(url).header("Content-Type", "text/plain");
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request
            .send(body.as_bytes())
            .map_err(|e| handle_ureq_error(e, url))?;

        response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))
    }

    /// Performs a PUT request with JSON body and deserializes JSON response.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response is not valid JSON.
    pub fn put_json<T: Serialize, R: DeserializeOwned>(&self, url: &str, body: &T) -> Result<R> {
        let json_body = serde_json::to_string(body)
            .with_context(|| format!("Failed to serialize request body for: {url}"))?;

        let mut request = self
            .agent
            .put(url)
            .header("Content-Type", "application/json");
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request
            .send(json_body.as_bytes())
            .map_err(|e| handle_ureq_error(e, url))?;

        let response_body = response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))?;

        serde_json::from_str(&response_body)
            .with_context(|| format!("Failed to parse JSON response from: {url}"))
    }

    /// Performs a DELETE request and deserializes JSON response.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response is not valid JSON.
    pub fn delete_json<R: DeserializeOwned>(&self, url: &str) -> Result<R> {
        let body = self.delete(url)?;
        serde_json::from_str(&body)
            .with_context(|| format!("Failed to parse JSON response from: {url}"))
    }

    /// Performs a PATCH request with JSON body and deserializes JSON response.
    ///
    /// # Errors
    ///
    /// Returns an error if the request fails or response is not valid JSON.
    pub fn patch_json<T: Serialize, R: DeserializeOwned>(&self, url: &str, body: &T) -> Result<R> {
        let json_body = serde_json::to_string(body)
            .with_context(|| format!("Failed to serialize request body for: {url}"))?;

        let mut request = self
            .agent
            .patch(url)
            .header("Content-Type", "application/json");
        for (key, value) in &self.headers {
            request = request.header(key, value);
        }

        let response = request
            .send(json_body.as_bytes())
            .map_err(|e| handle_ureq_error(e, url))?;

        let response_body = response
            .into_body()
            .read_to_string()
            .with_context(|| format!("Failed to read response body from: {url}"))?;

        serde_json::from_str(&response_body)
            .with_context(|| format!("Failed to parse JSON response from: {url}"))
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new()
    }
}

/// Handles ureq errors and converts them to anyhow errors.
fn handle_ureq_error(error: ureq::Error, url: &str) -> anyhow::Error {
    match error {
        ureq::Error::StatusCode(code) => {
            anyhow!("HTTP request to {url} failed with status {code}")
        }
        ureq::Error::Timeout(kind) => {
            anyhow!("HTTP request to {url} timed out: {kind:?}")
        }
        ureq::Error::HostNotFound => {
            anyhow!("Host not found for URL: {url}")
        }
        ureq::Error::Io(e) => {
            anyhow!("IO error during HTTP request to {url}: {e}")
        }
        _ => {
            anyhow!("HTTP request to {url} failed: {error}")
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Note: These tests require mockito for proper testing.
    // In a real test environment, you'd use:
    // let server = mockito::Server::new();
    // let url = server.url();
    // let _mock = server.mock("GET", "/").with_body("test").create();

    #[test]
    fn get_returns_error_for_invalid_url() {
        let result = get("http://invalid.local.host.that.does.not.exist.12345/");
        assert!(result.is_err());
    }

    #[test]
    fn get_json_returns_error_for_invalid_url() {
        let result: Result<serde_json::Value> =
            get_json("http://invalid.local.host.that.does.not.exist.12345/");
        assert!(result.is_err());
    }

    #[test]
    fn post_returns_error_for_invalid_url() {
        let result = post(
            "http://invalid.local.host.that.does.not.exist.12345/",
            "body",
        );
        assert!(result.is_err());
    }

    #[test]
    fn post_json_returns_error_for_invalid_url() {
        #[derive(serde::Serialize)]
        struct TestBody {
            key: String,
        }
        let body = TestBody {
            key: "value".to_string(),
        };
        let result: Result<serde_json::Value> = post_json(
            "http://invalid.local.host.that.does.not.exist.12345/",
            &body,
        );
        assert!(result.is_err());
    }

    // Integration tests with mockito would look like:
    // #[test]
    // fn get_fetches_url() {
    //     let mut server = mockito::Server::new();
    //     let mock = server.mock("GET", "/")
    //         .with_status(200)
    //         .with_body("Hello, World!")
    //         .create();
    //
    //     let result = get(&server.url()).unwrap();
    //     assert_eq!(result, "Hello, World!");
    //     mock.assert();
    // }
}