use http::StatusCode;
use serde::{Deserialize, Serialize};
use std::env;
use std::fmt::Debug;
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WhiskError {
pub code: String,
pub error: String,
}
#[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,
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,
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
}
}
pub fn whisk_errors(code: StatusCode, message: String) -> String {
format!(": Error -> [ Status :{}, Message : {} ]", code, message)
}