Skip to main content

aver/services/
http_server.rs

1use std::collections::HashMap;
2
3use aver_rt::{AverList, Header, HttpRequest, HttpResponse};
4
5use crate::value::{RuntimeError, Value, list_from_vec, list_view};
6
7pub fn register(global: &mut HashMap<String, Value>) {
8    let mut members = HashMap::new();
9    members.insert(
10        "listen".to_string(),
11        Value::Builtin("HttpServer.listen".to_string()),
12    );
13    members.insert(
14        "listenWith".to_string(),
15        Value::Builtin("HttpServer.listenWith".to_string()),
16    );
17    global.insert(
18        "HttpServer".to_string(),
19        Value::Namespace {
20            name: "HttpServer".to_string(),
21            members,
22        },
23    );
24}
25
26pub fn effects(name: &str) -> &'static [&'static str] {
27    match name {
28        "HttpServer.listen" => &["HttpServer.listen"],
29        "HttpServer.listenWith" => &["HttpServer.listenWith"],
30        _ => &[],
31    }
32}
33
34pub fn call(_name: &str, _args: &[Value]) -> Option<Result<Value, RuntimeError>> {
35    None
36}
37
38pub fn call_with_runtime<F>(
39    name: &str,
40    args: &[Value],
41    mut invoke_handler: F,
42    skip_server: bool,
43) -> Option<Result<Value, RuntimeError>>
44where
45    F: FnMut(Value, Vec<Value>, String) -> Result<Value, RuntimeError>,
46{
47    match name {
48        "HttpServer.listen" => Some(listen(args, false, &mut invoke_handler, skip_server)),
49        "HttpServer.listenWith" => Some(listen(args, true, &mut invoke_handler, skip_server)),
50        _ => None,
51    }
52}
53
54fn listen<F>(
55    args: &[Value],
56    with_context: bool,
57    invoke_handler: &mut F,
58    skip_server: bool,
59) -> Result<Value, RuntimeError>
60where
61    F: FnMut(Value, Vec<Value>, String) -> Result<Value, RuntimeError>,
62{
63    let expected = if with_context { 3 } else { 2 };
64    if args.len() != expected {
65        let sig = if with_context {
66            "HttpServer.listenWith(port, context, handler)"
67        } else {
68            "HttpServer.listen(port, handler)"
69        };
70        return Err(RuntimeError::Error(format!(
71            "{} expects {} arguments, got {}",
72            sig,
73            expected,
74            args.len()
75        )));
76    }
77
78    if skip_server {
79        return Ok(Value::Unit);
80    }
81
82    let port = match &args[0] {
83        Value::Int(n) if (0..=65535).contains(n) => *n,
84        Value::Int(n) => {
85            return Err(RuntimeError::Error(format!(
86                "HttpServer.listen: port {} is out of range (0-65535)",
87                n
88            )));
89        }
90        _ => {
91            return Err(RuntimeError::Error(
92                "HttpServer.listen: port must be an Int".to_string(),
93            ));
94        }
95    };
96    let handler = if with_context {
97        args[2].clone()
98    } else {
99        args[1].clone()
100    };
101
102    let result = if with_context {
103        let context = args[1].clone();
104        aver_rt::http_server::listen_with(port, context, |ctx, request| {
105            dispatch_handler(&handler, Some(ctx), request, invoke_handler)
106        })
107    } else {
108        aver_rt::http_server::listen(port, |request| {
109            dispatch_handler(&handler, None, request, invoke_handler)
110        })
111    };
112
113    result.map_err(RuntimeError::Error)?;
114    Ok(Value::Unit)
115}
116
117fn dispatch_handler<F>(
118    handler: &Value,
119    context: Option<Value>,
120    request: HttpRequest,
121    invoke_handler: &mut F,
122) -> HttpResponse
123where
124    F: FnMut(Value, Vec<Value>, String) -> Result<Value, RuntimeError>,
125{
126    let callback_entry = format!("<HttpServer {} {}>", request.method, request.path);
127    let mut callback_args = Vec::new();
128    if let Some(ctx) = context {
129        callback_args.push(ctx);
130    }
131    callback_args.push(http_request_to_value(request));
132
133    let callback_result = invoke_handler(handler.clone(), callback_args, callback_entry);
134    match callback_result {
135        Ok(value) => match http_response_from_value(value) {
136            Ok(resp) => resp,
137            Err(e) => HttpResponse {
138                status: 500,
139                body: format!("HttpServer handler return error: {}", e),
140                headers: AverList::empty(),
141            },
142        },
143        Err(e) => HttpResponse {
144            status: 500,
145            body: format!("HttpServer handler execution error: {}", e),
146            headers: AverList::empty(),
147        },
148    }
149}
150
151fn http_request_to_value(req: HttpRequest) -> Value {
152    let headers = req
153        .headers
154        .into_iter()
155        .map(|header| Value::Record {
156            type_name: "Header".to_string(),
157            fields: vec![
158                ("name".to_string(), Value::Str(header.name)),
159                ("value".to_string(), Value::Str(header.value)),
160            ]
161            .into(),
162        })
163        .collect::<Vec<_>>();
164
165    Value::Record {
166        type_name: "HttpRequest".to_string(),
167        fields: vec![
168            ("method".to_string(), Value::Str(req.method)),
169            ("path".to_string(), Value::Str(req.path)),
170            ("body".to_string(), Value::Str(req.body)),
171            ("headers".to_string(), list_from_vec(headers)),
172        ]
173        .into(),
174    }
175}
176
177fn http_response_from_value(val: Value) -> Result<HttpResponse, RuntimeError> {
178    let (type_name, fields) = match val {
179        Value::Record { type_name, fields } => (type_name, fields),
180        _ => {
181            return Err(RuntimeError::Error(
182                "HttpServer handler must return HttpResponse record".to_string(),
183            ));
184        }
185    };
186
187    if type_name != "HttpResponse" {
188        return Err(RuntimeError::Error(format!(
189            "HttpServer handler must return HttpResponse, got {}",
190            type_name
191        )));
192    }
193
194    let mut status = None;
195    let mut body = None;
196    let mut headers = AverList::empty();
197
198    for (name, value) in fields.iter() {
199        match name.as_str() {
200            "status" => {
201                if let Value::Int(n) = value {
202                    status = Some(*n);
203                } else {
204                    return Err(RuntimeError::Error(
205                        "HttpResponse.status must be Int".to_string(),
206                    ));
207                }
208            }
209            "body" => {
210                if let Value::Str(s) = value {
211                    body = Some(s.clone());
212                } else {
213                    return Err(RuntimeError::Error(
214                        "HttpResponse.body must be String".to_string(),
215                    ));
216                }
217            }
218            "headers" => {
219                headers = parse_http_response_headers(value.clone())?;
220            }
221            _ => {}
222        }
223    }
224
225    Ok(HttpResponse {
226        status: status
227            .ok_or_else(|| RuntimeError::Error("HttpResponse.status is required".to_string()))?,
228        body: body
229            .ok_or_else(|| RuntimeError::Error("HttpResponse.body is required".to_string()))?,
230        headers,
231    })
232}
233
234fn parse_http_response_headers(val: Value) -> Result<AverList<Header>, RuntimeError> {
235    let list = list_view(&val).ok_or_else(|| {
236        RuntimeError::Error("HttpResponse.headers must be List<Header>".to_string())
237    })?;
238
239    let mut out = Vec::new();
240    for item in list.iter() {
241        let fields = match item {
242            Value::Record { fields, .. } => fields,
243            _ => {
244                return Err(RuntimeError::Error(
245                    "HttpResponse.headers entries must be Header records".to_string(),
246                ));
247            }
248        };
249
250        let mut name = None;
251        let mut value = None;
252        for (field_name, field_val) in fields.iter() {
253            match (field_name.as_str(), field_val) {
254                ("name", Value::Str(s)) => name = Some(s.clone()),
255                ("value", Value::Str(s)) => value = Some(s.clone()),
256                _ => {}
257            }
258        }
259
260        let name = name.ok_or_else(|| {
261            RuntimeError::Error("HttpResponse header missing String 'name'".to_string())
262        })?;
263        let value = value.ok_or_else(|| {
264            RuntimeError::Error("HttpResponse header missing String 'value'".to_string())
265        })?;
266        out.push(Header { name, value });
267    }
268
269    Ok(AverList::from_vec(out))
270}