use crate::http::{self, HeaderName, HeaderValue};
use serde::{Deserialize, Serialize};
use std::str::FromStr;
pub const HOOK_ON_REQUEST: i32 = 1;
pub const HOOK_ON_REQUEST_BODY: i32 = 2;
pub const HOOK_ON_RESPONSE: i32 = 3;
pub const HOOK_ON_RESPONSE_BODY: i32 = 4;
pub const HOOK_ON_LOGGING: i32 = 5;
#[derive(Serialize, Deserialize)]
pub struct WasmInput {
pub config: String,
pub head: Option<WasmHead>,
pub body: Option<Vec<u8>>,
pub request_id: Option<String>,
pub request_ts: Option<i64>,
}
#[derive(Serialize, Deserialize)]
pub struct WasmHead {
pub method: Option<String>,
pub uri: Option<String>,
pub status: Option<u16>,
pub headers: Vec<(String, String)>,
}
impl WasmHead {
pub fn from_request_parts(parts: &http::request::Parts) -> Self {
let headers = parts
.headers
.iter()
.filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
.collect();
Self {
method: Some(parts.method.to_string()),
uri: Some(parts.uri.to_string()),
status: None,
headers,
}
}
pub fn from_response_parts(parts: &http::response::Parts) -> Self {
let headers = parts
.headers
.iter()
.filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
.collect();
Self {
method: None,
uri: None,
status: Some(parts.status.as_u16()),
headers,
}
}
pub fn apply_to_request_parts(&self, parts: &mut http::request::Parts) {
if let Some(ref method) = self.method
&& let Ok(m) = method.parse()
{
parts.method = m;
}
if let Some(ref uri) = self.uri
&& let Ok(u) = uri.parse()
{
parts.uri = u;
}
apply_headers(&self.headers, &mut parts.headers);
}
pub fn apply_to_response_parts(&self, parts: &mut http::response::Parts) {
if let Some(status) = self.status && let Ok(s) = http::StatusCode::from_u16(status) {
parts.status = s;
}
apply_headers(&self.headers, &mut parts.headers);
}
}
fn apply_headers(wasm_headers: &[(String, String)], header_map: &mut http::HeaderMap) {
header_map.clear();
for (k, v) in wasm_headers {
if let (Ok(name), Ok(value)) = (HeaderName::from_str(k), HeaderValue::from_str(v)) {
header_map.insert(name, value);
}
}
}
#[derive(Serialize, Deserialize)]
pub struct WasmOutput {
pub head: Option<WasmHead>,
pub body: Option<Vec<u8>>,
}
#[derive(Serialize, Deserialize)]
pub struct WasmPluginInfo {
pub name: String,
pub version: String,
pub description: String,
pub default_config: String,
pub readme: Option<String>,
}