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
//
// Wildland Project
//
// Copyright © 2022 Golem Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as published by
// the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use std::rc::Rc;

use serde::Serialize;
use serde_json::json;
use thiserror::Error;

#[cfg(target_os = "emscripten")]
mod emscripten_http_client;

#[cfg(target_os = "emscripten")]
pub use emscripten_http_client::EmscriptenHttpClient as CurrentPlatformClient;

#[cfg(not(target_os = "emscripten"))]
mod minreq_http_client;

#[cfg(not(target_os = "emscripten"))]
pub use minreq_http_client::MinreqHttpClient as CurrentPlatformClient;

#[derive(Error, Debug, Clone)]
#[repr(C)]
pub enum HttpError {
    #[error("User error: {0}")]
    User(Rc<anyhow::Error>),
    #[error("Io error: {0}")]
    Io(Rc<anyhow::Error>),
    #[error("Other error: {0}")]
    Other(Rc<anyhow::Error>),
}

impl HttpError {
    pub fn user<T>(err: T) -> Self
    where
        T: Into<anyhow::Error>,
    {
        Self::User(Rc::new(err.into()))
    }

    pub fn io<T>(err: T) -> Self
    where
        T: Into<anyhow::Error>,
    {
        Self::Io(Rc::new(err.into()))
    }

    pub fn other<T>(err: T) -> Self
    where
        T: Into<anyhow::Error>,
    {
        Self::Other(Rc::new(err.into()))
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Body {
    Json(serde_json::Value),
    Raw(Vec<u8>),
}

impl Body {
    pub fn json<T>(val: T) -> Self
    where
        T: Serialize,
    {
        Self::Json(json!(val))
    }

    pub fn raw(val: Vec<u8>) -> Self {
        Self::Raw(val)
    }

    pub fn empty() -> Self {
        Self::raw(Vec::new())
    }
}

pub type Request = http::Request<Body>;
pub type Response = http::Response<Vec<u8>>;

pub type HttpResult = Result<Response, HttpError>;

#[cfg_attr(test, mockall::automock)]
pub trait HttpClient {
    fn send(&self, request: Request) -> HttpResult;
}