aiway_plugin/
wasm_types.rs1use crate::http::{self, HeaderName, HeaderValue};
7use serde::{Deserialize, Serialize};
8use std::str::FromStr;
9use std::sync::Arc;
10
11pub const HOOK_ON_REQUEST: i32 = 1;
13pub const HOOK_ON_REQUEST_BODY: i32 = 2;
14pub const HOOK_ON_RESPONSE: i32 = 3;
15pub const HOOK_ON_RESPONSE_BODY: i32 = 4;
16pub const HOOK_ON_LOGGING: i32 = 5;
17
18#[derive(Serialize, Deserialize)]
20pub struct WasmInput {
21 pub config: Arc<str>,
23 pub head: Option<WasmHead>,
25 pub body: Option<Vec<u8>>,
27 pub request_id: Option<String>,
29 pub request_ts: Option<i64>,
31}
32
33#[derive(Serialize, Deserialize)]
35pub struct WasmHead {
36 pub method: Option<String>,
38 pub uri: Option<String>,
40 pub status: Option<u16>,
42 pub headers: Vec<(String, String)>,
44}
45
46impl WasmHead {
47 pub fn from_request_parts(parts: &http::request::Parts) -> Self {
49 let headers = parts
50 .headers
51 .iter()
52 .filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
53 .collect();
54
55 Self {
56 method: Some(parts.method.to_string()),
57 uri: Some(parts.uri.to_string()),
58 status: None,
59 headers,
60 }
61 }
62
63 pub fn from_response_parts(parts: &http::response::Parts) -> Self {
65 let headers = parts
66 .headers
67 .iter()
68 .filter_map(|(k, v)| v.to_str().ok().map(|v| (k.to_string(), v.to_string())))
69 .collect();
70
71 Self {
72 method: None,
73 uri: None,
74 status: Some(parts.status.as_u16()),
75 headers,
76 }
77 }
78
79 pub fn apply_to_request_parts(&self, parts: &mut http::request::Parts) {
81 if let Some(ref method) = self.method
82 && let Ok(m) = method.parse()
83 {
84 parts.method = m;
85 }
86 if let Some(ref uri) = self.uri
87 && let Ok(u) = uri.parse()
88 {
89 parts.uri = u;
90 }
91 apply_headers(&self.headers, &mut parts.headers);
92 }
93
94 pub fn apply_to_response_parts(&self, parts: &mut http::response::Parts) {
96 if let Some(status) = self.status && let Ok(s) = http::StatusCode::from_u16(status) {
97 parts.status = s;
98 }
99 apply_headers(&self.headers, &mut parts.headers);
100 }
101}
102
103fn apply_headers(wasm_headers: &[(String, String)], header_map: &mut http::HeaderMap) {
105 header_map.clear();
106 for (k, v) in wasm_headers {
107 if let (Ok(name), Ok(value)) = (HeaderName::from_str(k), HeaderValue::from_str(v)) {
108 header_map.insert(name, value);
109 }
110 }
111}
112
113#[derive(Serialize, Deserialize)]
115pub struct WasmOutput {
116 pub head: Option<WasmHead>,
118 pub body: Option<Vec<u8>>,
120}
121
122#[derive(Serialize, Deserialize)]
124pub struct WasmPluginInfo {
125 pub name: String,
126 pub version: String,
127 pub description: String,
128 pub default_config: String,
130 pub readme: Option<String>,
132}