122 lines
5.7 KiB
Python
122 lines
5.7 KiB
Python
"""HTTP 单次新连接的真实回环对照;共享 Node HTTP 服务只回显收到的正文。"""
|
|
import atexit
|
|
import json
|
|
import select
|
|
import subprocess
|
|
|
|
|
|
def server(root):
|
|
script = root / 'http-server.cjs'
|
|
script.write_text('''const http = require('node:http');
|
|
const server = http.createServer((request, response) => {
|
|
const chunks = [];
|
|
request.on('data', chunk => chunks.push(chunk));
|
|
request.on('end', () => {
|
|
const body = Buffer.concat(chunks);
|
|
response.sendDate = false;
|
|
response.writeHead(200, { 'content-length': body.length, 'x-echo': 'yes' });
|
|
response.end(body);
|
|
});
|
|
});
|
|
server.listen(0, '127.0.0.1', () => console.log(server.address().port));
|
|
process.on('SIGTERM', () => server.close());
|
|
''')
|
|
error = (root / 'http-server.stderr').open('w')
|
|
process = subprocess.Popen(['node', str(script)], stdout=subprocess.PIPE, stderr=error, text=True)
|
|
def close():
|
|
process.terminate()
|
|
process.wait(timeout=10)
|
|
error.close()
|
|
atexit.register(close)
|
|
if not select.select([process.stdout], [], [], 10)[0]:
|
|
raise RuntimeError('HTTP reference server did not report its address')
|
|
return json.loads(process.stdout.readline())
|
|
|
|
|
|
def source(language):
|
|
if language == 'dever':
|
|
return '''setting port: Int
|
|
flow exchange(value: Int) (out: Int)
|
|
| step | kind | do |
|
|
| body | calc | dever.bytes.fromText(int.toText(value)) |
|
|
| request | calc | dever.http.Request { method = "POST", target = "/echo", headers = [dever.http.header("host", "localhost")], body = body } |
|
|
| response | flow | dever.http.send("127.0.0.1", port, request, dever.http.defaultLimits()) |
|
|
| - | check | response.status == 200 else Invalid |
|
|
| - | check | response.body == body else Invalid |
|
|
| out | calc | 1 |
|
|
loop measure(n: Int) (out: Int)
|
|
| each value in range(0, n) | result |
|
|
| out | sum exchange(value) |
|
|
cmd bench = measure
|
|
'''
|
|
if language == 'rust':
|
|
return '''use bytes::Bytes;
|
|
use http_body_util::{BodyExt, Full, Limited};
|
|
use hyper_util::rt::TokioIo;
|
|
use serde::Deserialize;
|
|
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Root { module: Module }
|
|
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Module { main: Domain }
|
|
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Domain { main: Settings }
|
|
#[derive(Deserialize)] #[serde(deny_unknown_fields)] struct Settings { port: u16 }
|
|
fn main() {
|
|
let n: i64 = std::env::args().nth(1).unwrap().parse().unwrap();
|
|
let data = std::fs::read(std::env::args().nth(2).unwrap()).unwrap();
|
|
let config: Root = serde_json::from_slice(&data).unwrap();
|
|
let port = config.module.main.main.port;
|
|
let total = tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
|
|
let mut total = 0i64;
|
|
for value in 0..n {
|
|
let body = Bytes::from(value.to_string());
|
|
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
|
let stream = tokio::net::TcpStream::connect(("127.0.0.1", port)).await.unwrap();
|
|
stream.set_nodelay(true).unwrap();
|
|
let (mut sender, connection) = hyper::client::conn::http1::Builder::new().max_buf_size(8192)
|
|
.handshake(TokioIo::new(stream)).await.unwrap();
|
|
let request = hyper::Request::builder().method("POST").uri("/echo").header("host", "localhost")
|
|
.body(Full::new(body.clone())).unwrap();
|
|
let response = async {
|
|
let response = sender.send_request(request).await.unwrap();
|
|
assert_eq!(response.status(), 200);
|
|
let header_bytes: usize = 32 + response.headers().iter().map(|(name, value)| name.as_str().len() + value.as_bytes().len() + 4).sum::<usize>();
|
|
assert!(header_bytes <= 8192);
|
|
let response = Limited::new(response.into_body(), 1048576).collect().await.unwrap().to_bytes();
|
|
assert_eq!(response, body);
|
|
};
|
|
tokio::pin!(connection, response);
|
|
tokio::select! { biased; () = &mut response => {}, _ = &mut connection => response.await }
|
|
}).await.unwrap();
|
|
total = total.checked_add(1).unwrap();
|
|
}
|
|
total
|
|
});
|
|
println!("{total}");
|
|
}
|
|
'''
|
|
return '''package main
|
|
import ("bytes"; "encoding/json"; "fmt"; "io"; "net/http"; "os"; "strconv"; "time")
|
|
type Settings struct { Port int }
|
|
type Domain struct { Main Settings }
|
|
type Module struct { Main Domain }
|
|
type Root struct { Module Module }
|
|
func main() {
|
|
n, err := strconv.ParseInt(os.Args[1], 10, 64); if err != nil { panic(err) }
|
|
data, err := os.ReadFile(os.Args[2]); if err != nil { panic(err) }
|
|
var config Root
|
|
decoder := json.NewDecoder(bytes.NewReader(data)); decoder.DisallowUnknownFields()
|
|
if err := decoder.Decode(&config); err != nil { panic(err) }
|
|
client := &http.Client{Timeout: 5*time.Second, Transport: &http.Transport{DisableKeepAlives: true, MaxResponseHeaderBytes: 8192}}
|
|
total := int64(0)
|
|
for value := int64(0); value < n; value++ {
|
|
body := []byte(strconv.FormatInt(value, 10))
|
|
request, err := http.NewRequest("POST", fmt.Sprintf("http://127.0.0.1:%d/echo", config.Module.Main.Main.Port), bytes.NewReader(body)); if err != nil { panic(err) }
|
|
request.Host = "localhost"
|
|
response, err := client.Do(request); if err != nil { panic(err) }
|
|
received, err := io.ReadAll(io.LimitReader(response.Body, 1048577)); if err != nil { panic(err) }
|
|
if err := response.Body.Close(); err != nil { panic(err) }
|
|
if response.StatusCode != 200 || len(received) > 1048576 || !bytes.Equal(received, body) { panic("response mismatch") }
|
|
next := total + 1; if next < total { panic("count overflow") }; total = next
|
|
}
|
|
fmt.Println(total)
|
|
}
|
|
'''
|