108 lines
5.7 KiB
Python
108 lines
5.7 KiB
Python
"""HTTP/1 持久连接回显:对端使用成熟库,独立 Rust 不依赖 Dever runtime。"""
|
|
|
|
|
|
def source(language, automatic_api=False):
|
|
if language == 'dever':
|
|
if automatic_api:
|
|
return 'echo(value: Text) (out: Text) { out = value }\n'
|
|
return '''setting port: Int
|
|
echo(request: dever.http.Request) (response: dever.http.Response) {
|
|
response = dever.http.Response { status = 200, headers = [], body = request.body }
|
|
}
|
|
flow start() ()
|
|
| step | kind | do |
|
|
| listener | flow | dever.net.listen("127.0.0.1", port) |
|
|
| - | flow | dever.http.serve(echo, listener, dever.http.defaultLimits()) |
|
|
cmd server = start
|
|
'''
|
|
if language == 'rust':
|
|
return '''use bytes::Bytes;
|
|
use futures_util::{TryStreamExt, stream};
|
|
use http_body_util::{BodyExt, Full, Limited};
|
|
use hyper::{body::Incoming, service::service_fn};
|
|
use hyper_util::rt::{TokioIo, TokioTimer};
|
|
use std::{convert::Infallible, time::Duration};
|
|
async fn reply(request: hyper::Request<Incoming>) -> Result<hyper::Response<Full<Bytes>>, Infallible> {
|
|
let (parts, body) = request.into_parts();
|
|
let size = parts.method.as_str().len() + parts.uri.path_and_query().unwrap().as_str().len() + 16
|
|
+ parts.headers.iter().map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 4).sum::<usize>();
|
|
let mut hosts = parts.headers.get_all("host").iter();
|
|
let host = hosts.next().unwrap().to_str().unwrap().parse::<hyper::http::uri::Authority>().unwrap();
|
|
assert!(hosts.next().is_none() && !host.as_str().contains('@'));
|
|
assert!(size <= 8192 && parts.uri.path().starts_with('/') && parts.uri.authority().is_none());
|
|
let body = tokio::time::timeout(Duration::from_secs(5), Limited::new(body, 1048576).collect()).await.unwrap().unwrap().to_bytes();
|
|
/* reply */
|
|
}
|
|
fn main() {
|
|
let port: u16 = std::env::args().nth(1).unwrap().parse().unwrap();
|
|
tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
|
|
let listener = tokio::net::TcpListener::bind(("127.0.0.1", port)).await.unwrap();
|
|
stream::try_unfold((), |()| async { listener.accept().await.map(|(stream, _)| Some((stream, ()))) })
|
|
.try_for_each_concurrent(32, |stream| async move {
|
|
stream.set_nodelay(true)?;
|
|
hyper::server::conn::http1::Builder::new().timer(TokioTimer::new())
|
|
.header_read_timeout(Duration::from_secs(5)).max_buf_size(8192)
|
|
.serve_connection(TokioIo::new(stream), service_fn(reply)).await.map_err(std::io::Error::other)
|
|
}).await.unwrap();
|
|
});
|
|
}
|
|
'''.replace('/* reply */', RUST_API if automatic_api else 'Ok(hyper::Response::new(Full::new(body)))')
|
|
if language != 'go':
|
|
raise ValueError(language)
|
|
return '''package main
|
|
import ("fmt"; "io"; "net/http"; "os"; "strconv"; "time" /* imports */)
|
|
func main() {
|
|
port, err := strconv.Atoi(os.Args[1]); if err != nil { panic(err) }
|
|
server := &http.Server{Addr: fmt.Sprintf("127.0.0.1:%d", port), MaxHeaderBytes: 8192, ReadHeaderTimeout: 5*time.Second, ReadTimeout: 5*time.Second,
|
|
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
data, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1048576)); if err != nil { panic(err) }
|
|
/* reply */
|
|
w.Header()["Date"] = nil
|
|
/* content-type */
|
|
w.WriteHeader(200)
|
|
if _, err := w.Write(data); err != nil { panic(err) }
|
|
})}
|
|
if err := server.ListenAndServe(); err != nil { panic(err) }
|
|
}
|
|
'''.replace('/* imports */', '; "bytes"; "encoding/json"' if automatic_api else '').replace('/* reply */', GO_API if automatic_api else '').replace('/* content-type */', '' if automatic_api else 'w.Header()["Content-Type"] = nil')
|
|
|
|
|
|
# 参考只比较公开 JSON 成功路径,不冒充完整鉴权、任务故障与取消合同。
|
|
RUST_API = '''
|
|
#[derive(serde::Deserialize)]
|
|
#[serde(deny_unknown_fields)]
|
|
struct Input { value: String }
|
|
#[derive(serde::Serialize)]
|
|
struct Reply<'a> { code: u16, message: &'static str, data: Option<&'a str> }
|
|
let input = serde_json::from_slice::<Input>(&body);
|
|
let (status, message, data) = if host.host() != "127.0.0.1" || parts.uri.path() != "/benchmark/echo/front/main/echo" {
|
|
(404, "not found", None)
|
|
} else if parts.method != hyper::Method::POST {
|
|
(405, "method not allowed", None)
|
|
} else {
|
|
match &input {
|
|
Ok(input) => (200, "ok", Some(input.value.as_str())),
|
|
Err(_) => (400, "invalid request", None),
|
|
}
|
|
};
|
|
Ok(hyper::Response::builder().status(status).header("content-type", "application/json; charset=utf-8")
|
|
.body(Full::new(Bytes::from(serde_json::to_vec(&Reply{code:if status==200 {0} else {status},message,data}).unwrap()))).unwrap())
|
|
'''
|
|
|
|
GO_API = '''
|
|
if r.Host != "127.0.0.1:"+strconv.Itoa(port) || r.URL.Path != "/benchmark/echo/front/main/echo" {
|
|
http.Error(w, "not found", 404); return
|
|
}
|
|
if r.Method != "POST" { http.Error(w, "method not allowed", 405); return }
|
|
var input struct { Value *string `json:"value"` }
|
|
decoder := json.NewDecoder(bytes.NewReader(data)); decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(&input); err != nil || input.Value == nil {
|
|
http.Error(w, "invalid request", 400); return
|
|
}
|
|
var extra any
|
|
if err := decoder.Decode(&extra); err != io.EOF { http.Error(w, "invalid request", 400); return }
|
|
data, err = json.Marshal(struct { Code int `json:"code"`; Message string `json:"message"`; Data string `json:"data"` }{0,"ok",*input.Value})
|
|
if err != nil { panic(err) }
|
|
w.Header().Set("content-type", "application/json; charset=utf-8")
|
|
'''
|