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
use derive_new::new;
use serde::{Deserialize, Serialize};
use std::env;
use std::fmt::Debug;

use crate::api::{HttpMethods, Service};
use http::StatusCode;
use reqwest::blocking::Client;
use serde_json::Value;

#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WskProperties {
    pub auth_token: String,
    pub host: String,
    #[serde(default = "default")]
    pub version: String,
    pub insecure: bool,
    pub namespace: String,
    #[serde(default = "bool::default")]
    pub verbose: bool,
    #[serde(default = "bool::default")]
    pub debug: bool,
}

fn default() -> String {
    "v1".to_string()
}
#[derive(Debug, Deserialize, Serialize, Clone, Default)]
pub struct Context {
    host: String,
    namespace: String,
    insecure: bool,
    username: String,
    password: String,
    version: String,
}

impl WskProperties {
    pub fn new(auth_token: String, host: String, insecure: bool, namespace: String) -> Self {
        Self {
            auth_token,
            host,
            insecure,
            namespace,
            version: default(),
            ..Default::default()
        }
    }

    pub fn set_verbose_debug_version(&self, debug: bool, verbose: bool, version: String) -> Self {
        Self {
            auth_token: self.auth_token.clone(),
            host: self.host.clone(),
            version,
            insecure: self.insecure.clone(),
            namespace: self.namespace.clone(),
            verbose,
            debug,
        }
    }
}

pub trait OpenWhisk {
    type Output;
    fn new_whisk_client(insecure: Option<bool>) -> Self::Output;
}

impl Context {
    pub fn new(wskprops: Option<&WskProperties>) -> Context {
        let api_key = if env::var("__OW_API_KEY").is_ok() {
            env::var("__OW_API_KEY").unwrap()
        } else {
            match wskprops {
                Some(wskprops) => wskprops.auth_token.clone(),
                None => "test:test".to_string(),
            }
        };
        let auth: Vec<&str> = api_key.split(":").collect();
        let host = if env::var("__OW_API_HOST").is_ok() {
            env::var("__OW_API_HOST").unwrap()
        } else {
            match wskprops {
                Some(wskprops) => wskprops.host.clone(),
                None => "host.docker.internal".to_string(),
            }
        };
        let namespace = if env::var("__OW_NAMESPACE").is_ok() {
            env::var("__OW_NAMESPACE").unwrap()
        } else {
            match wskprops {
                Some(wskprops) => wskprops.namespace.clone(),
                None => "guest".to_string(),
            }
        };

        let connectiontype = match wskprops {
            Some(config) => config.insecure.clone(),
            None => false,
        };

        let version = match wskprops {
            Some(config) => config.version.clone(),
            None => "v1".to_string(),
        };

        Context {
            host,
            namespace,
            insecure: connectiontype,
            username: auth[0].to_string(),
            password: auth[1].to_string(),
            version,
        }
    }

    pub fn namespace(&self) -> &str {
        &self.namespace
    }

    pub fn is_secure(&self) -> bool {
        self.insecure
    }

    pub fn auth(&self) -> (&str, &str) {
        (&self.username, &self.password)
    }

    pub fn host(&self) -> &str {
        &self.host
    }
}

#[derive(Debug, Default)]
pub struct NativeClient(Client);

impl OpenWhisk for NativeClient {
    type Output = NativeClient;
    fn new_whisk_client(insecure: Option<bool>) -> Self::Output {
        match insecure {
            Some(x) => match x {
                true => NativeClient(
                    reqwest::blocking::Client::builder()
                        .danger_accept_invalid_certs(x)
                        .timeout(None)
                        .build()
                        .unwrap(),
                ),
                false => NativeClient(
                    reqwest::blocking::Client::builder()
                        .timeout(None)
                        .build()
                        .unwrap(),
                ),
            },
            None => todo!(),
        }
    }
}

impl Service for NativeClient {
    type Output = reqwest::blocking::RequestBuilder;

    fn new_request(
        &self,
        method: HttpMethods,
        url: &str,
        use_auth: Option<(&str, &str)>,
        body: Option<Value>,
    ) -> Result<Self::Output, String> {
        let body = body.unwrap_or(serde_json::json!({}));

        match use_auth {
            Some(auth) => {
                let user = auth.0;
                let pass = auth.1;

                match method {
                    HttpMethods::GET => return Ok(self.0.get(url).basic_auth(user, Some(pass))),
                    HttpMethods::POST => {
                        return Ok(self.0.post(url).basic_auth(user, Some(pass)).json(&body))
                    }
                    HttpMethods::PUT => {
                        return Ok(self.0.put(url).basic_auth(user, Some(pass)).json(&body))
                    }
                    HttpMethods::DELETE => {
                        return Ok(self.0.delete(url).basic_auth(user, Some(pass)).json(&body))
                    }
                    _ => Err(format!("Falied to create request")),
                }
            }
            None => match method {
                HttpMethods::GET => return Ok(self.0.get(url)),
                HttpMethods::POST => return Ok(self.0.post(url).json(&body)),
                HttpMethods::PUT => return Ok(self.0.put(url).json(&body)),
                HttpMethods::DELETE => return Ok(self.0.delete(url).json(&body)),
                _ => Err(format!("Falied to create request")),
            },
        }
    }

    fn invoke_request(&self, request: Self::Output) -> Result<Value, String> {
        if let Ok(response) = request.send() {
            return match response.status() {
                StatusCode::OK => Ok(response.json().unwrap()),
                _ => Err(format!("failed to invoke request {}", response.status())),
            };
        };
        Err(format!("failed to invoke request"))
    }
}

impl Clone for NativeClient {
    fn clone(&self) -> Self {
        NativeClient(self.0.clone())
    }

    fn clone_from(&mut self, _source: &Self) {
        NativeClient(self.0.clone());
    }
}