466 lines
17 KiB
Rust
466 lines
17 KiB
Rust
mod auth;
|
|
mod authorization;
|
|
mod checks;
|
|
mod identity;
|
|
mod rest;
|
|
mod session;
|
|
mod tenant;
|
|
mod tls;
|
|
use super::*;
|
|
use std::{
|
|
io::{Read, Write},
|
|
net::TcpStream,
|
|
time::{Duration, Instant},
|
|
};
|
|
|
|
fn project(name: &str, app: &str, api: &str) -> PathBuf {
|
|
let root = directory(name);
|
|
let domain = root.join("module/demo/service");
|
|
fs::create_dir_all(domain.join("api/front")).unwrap();
|
|
write_source(domain.join("app/main.dever"), app).unwrap();
|
|
fs::write(domain.join("api/front/main.dever"), api).unwrap();
|
|
fs::create_dir_all(root.join("config")).unwrap();
|
|
root
|
|
}
|
|
|
|
#[test]
|
|
fn generated_typescript_client_calls_http_without_losing_integer_or_json_precision() {
|
|
let root = project(
|
|
"typescript-client",
|
|
r#"
|
|
type Value { count: Int, ratio: Float, price: Decimal, raw: Json, label: Text? }
|
|
echo(value: Value) (out: Value) { out = value }
|
|
hello(name: Text) (out: Text) { out = name }
|
|
flow reject(accepted: Bool) ()
|
|
| step | kind | do |
|
|
| - | check | accepted else Conflict |
|
|
"#,
|
|
"public post echo = app.echo\npublic get hello = app.hello\npublic post reject = app.reject",
|
|
);
|
|
success(cli(&["fmt", root.to_str().unwrap()]));
|
|
let client = root.join("client.ts");
|
|
success(cli(&[
|
|
"client",
|
|
root.to_str().unwrap(),
|
|
"--output",
|
|
client.to_str().unwrap(),
|
|
]));
|
|
assert!(
|
|
!cli(&[
|
|
"client",
|
|
root.to_str().unwrap(),
|
|
"--output",
|
|
client.to_str().unwrap()
|
|
])
|
|
.status
|
|
.success()
|
|
);
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
let (path, port, mut value) = config(&root);
|
|
value["sites"]["front"]["hosts"] = serde_json::json!(["127.0.0.1"]);
|
|
fs::write(&path, value.to_string()).unwrap();
|
|
let server = Server::start(&artifact.binary, &path, port);
|
|
fs::write(root.join("call.mjs"), r#"
|
|
import assert from 'node:assert/strict';
|
|
import {createClient,rawJson,ApiError} from './client.ts';
|
|
const client=createClient(process.argv[2]);
|
|
const value={count:9223372036854775807n,ratio:1.25,price:'12345678901234567890.12',raw:{number:rawJson('12345678901234567890.123456789')},label:null};
|
|
assert.deepEqual(await client['POST /demo/service/front/main/echo']({value}),value);
|
|
const query="中文 + & = / ?";
|
|
assert.equal(await client['GET /demo/service/front/main/hello']({name:query}),query);
|
|
await assert.rejects(client['POST /demo/service/front/main/reject']({accepted:false}),e=>e instanceof ApiError&&e.status===409&&e.code===409);
|
|
await assert.rejects(client['GET /demo/service/front/main/hello']({name:'stop'},{signal:AbortSignal.abort()}),e=>e.name==='AbortError');
|
|
console.log('client HTTP precision, query, error and abort passed');
|
|
"#).unwrap();
|
|
let output = success(
|
|
Command::new("node")
|
|
.arg(root.join("call.mjs"))
|
|
.arg(format!("http://127.0.0.1:{port}"))
|
|
.output()
|
|
.unwrap(),
|
|
);
|
|
assert!(output.contains("passed"));
|
|
server.stop();
|
|
}
|
|
|
|
#[test]
|
|
fn text_game_example_executes_real_http_and_rejects_unknown_actions() {
|
|
let example = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/next/text_game");
|
|
let (loaded, program) = analyze(&example);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
let root = directory("text-game-http");
|
|
fs::create_dir(root.join("config")).unwrap();
|
|
let (path, port, mut settings) = config(&root);
|
|
settings["sites"] = serde_json::json!({"web":{"path":"web","hosts":["localhost"]}});
|
|
fs::write(&path, settings.to_string()).unwrap();
|
|
let server = Server::start(&artifact.binary, &path, port);
|
|
for (actions, expected) in [
|
|
(serde_json::json!([]), "Locked"),
|
|
(serde_json::json!(["Open"]), "Locked"),
|
|
(serde_json::json!(["Search", "Search"]), "KeyFound"),
|
|
(serde_json::json!(["Look", "Search", "Open", "Quit"]), "Won"),
|
|
(serde_json::json!(["Quit", "Search", "Open"]), "GaveUp"),
|
|
] {
|
|
let (status, response) = server.call(
|
|
"POST",
|
|
"/game/escape/web/game/play",
|
|
&serde_json::json!({"actions":actions}).to_string(),
|
|
"Content-Type: application/json\r\n",
|
|
);
|
|
assert_eq!(status, 200, "{response}");
|
|
assert_eq!(response["data"]["stage"], expected);
|
|
}
|
|
let (status, response) = server.call(
|
|
"POST",
|
|
"/game/escape/web/game/step",
|
|
r#"{"stage":"Won","action":"Quit"}"#,
|
|
"Content-Type: application/json\r\n",
|
|
);
|
|
assert_eq!(status, 200, "{response}");
|
|
assert_eq!(response["data"]["stage"], "Won");
|
|
let (status, _) = server.call(
|
|
"POST",
|
|
"/game/escape/web/game/play",
|
|
r#"{"actions":["Unknown"]}"#,
|
|
"Content-Type: application/json\r\n",
|
|
);
|
|
assert_eq!(status, 400);
|
|
server.stop();
|
|
}
|
|
|
|
#[test]
|
|
fn component_front_is_embedded_with_or_without_api_and_keeps_host_and_route_boundaries() {
|
|
for with_api in [false, true] {
|
|
let root = if with_api {
|
|
project(
|
|
"web-with-api",
|
|
"hello() (out: Text) { out = \"api\" }",
|
|
"public get hello = app.hello",
|
|
)
|
|
} else {
|
|
let root = directory("web-only");
|
|
fs::create_dir_all(root.join("config")).unwrap();
|
|
root
|
|
};
|
|
let front = root.join("module/demo/front");
|
|
let source = front.join("src");
|
|
fs::create_dir_all(source.join("nested")).unwrap();
|
|
fs::write(source.join("index.html"), "<h1>Dever 页面</h1>").unwrap();
|
|
fs::write(source.join("nested/index.html"), "nested page").unwrap();
|
|
fs::write(source.join("app.js"), "console.log('embedded');").unwrap();
|
|
fs::create_dir(front.join("dist")).unwrap();
|
|
fs::write(front.join("dist/stale.txt"), "old build").unwrap();
|
|
let (path, port, mut value) = config(&root);
|
|
value["sites"]["front"]["front"] = serde_json::json!({"component":"demo","path":"/"});
|
|
fs::write(&path, value.to_string()).unwrap();
|
|
success(cli(&["fmt", root.to_str().unwrap()]));
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
assert!(!front.join("dist/stale.txt").exists());
|
|
fs::rename(&front, root.join("removed-front")).unwrap();
|
|
let server = Server::start(&artifact.binary, &path, port);
|
|
let request = |method: &str, target: &str, host: &str| {
|
|
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
.unwrap();
|
|
write!(stream,"{method} {target} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n").unwrap();
|
|
let mut reply = String::new();
|
|
stream.read_to_string(&mut reply).unwrap();
|
|
reply
|
|
};
|
|
let reply = request("GET", "/", "localhost");
|
|
assert!(reply.starts_with("HTTP/1.1 200"), "{reply}");
|
|
assert!(reply.ends_with("<h1>Dever 页面</h1>"));
|
|
assert!(reply.contains("text/html; charset=utf-8"));
|
|
let head = request("HEAD", "/", "localhost");
|
|
assert_eq!(head.split_once("\r\n\r\n").unwrap().1, "");
|
|
assert!(
|
|
head.contains(&format!("content-length: {}", "<h1>Dever 页面</h1>".len())),
|
|
"{head}"
|
|
);
|
|
assert!(request("GET", "/nested/", "localhost").ends_with("nested page"));
|
|
assert!(request("GET", "/app.js?v=1", "localhost").contains("text/javascript"));
|
|
for target in [
|
|
"/missing",
|
|
"/../config/setting.json",
|
|
"/%2e%2e/config/setting.json",
|
|
] {
|
|
assert!(request("GET", target, "localhost").starts_with("HTTP/1.1 404"));
|
|
}
|
|
assert!(request("GET", "/", "unknown.example").starts_with("HTTP/1.1 404"));
|
|
assert!(request("POST", "/", "localhost").starts_with("HTTP/1.1 405"));
|
|
if with_api {
|
|
assert!(
|
|
request("GET", "/demo/service/front/main/hello", "localhost")
|
|
.contains("\"data\":\"api\"")
|
|
);
|
|
}
|
|
server.stop();
|
|
if with_api {
|
|
drop(artifact);
|
|
fs::rename(root.join("removed-front"), &front).unwrap();
|
|
let conflict = source.join("demo/service/front/main");
|
|
fs::create_dir_all(&conflict).unwrap();
|
|
fs::write(conflict.join("hello"), "not an API").unwrap();
|
|
let (loaded, program) = analyze(&root);
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
let output = Command::new(&artifact.binary)
|
|
.arg("--config")
|
|
.arg(&path)
|
|
.arg("api")
|
|
.output()
|
|
.unwrap();
|
|
assert!(!output.status.success());
|
|
assert!(String::from_utf8_lossy(&output.stderr).contains("conflicts with API route"));
|
|
drop(artifact);
|
|
fs::write(source.join(".env"), "private").unwrap();
|
|
assert!(build::build(&loaded, &program, "main", Profile::Dev, None).is_err());
|
|
fs::remove_file(source.join(".env")).unwrap();
|
|
std::os::unix::fs::symlink(root.join("config/setting.json"), source.join("link.json"))
|
|
.unwrap();
|
|
assert!(build::build(&loaded, &program, "main", Profile::Dev, None).is_err());
|
|
}
|
|
}
|
|
}
|
|
pub(super) struct Server {
|
|
child: std::process::Child,
|
|
port: u16,
|
|
}
|
|
impl Server {
|
|
pub(super) fn start(binary: &Path, config: &Path, port: u16) -> Self {
|
|
Self::mode(binary, config, port, "api")
|
|
}
|
|
fn mode(binary: &Path, config: &Path, port: u16, mode: &str) -> Self {
|
|
// 持续负载的预期 409 也会记录;未读取的 stderr 管道会填满并阻塞服务。
|
|
let log = config.with_extension("server.log");
|
|
let errors = fs::OpenOptions::new()
|
|
.create(true)
|
|
.append(true)
|
|
.open(&log)
|
|
.unwrap();
|
|
let mut command = Command::new(binary);
|
|
// 只追踪综合负载的服务进程,保持 PID、退出信号和资源采样指向真实应用。
|
|
if mode == "all"
|
|
&& let Some(preload) = std::env::var_os("DEVER_TEST_HEAPTRACK_PRELOAD")
|
|
{
|
|
command.env("LD_PRELOAD", preload).env(
|
|
"DUMP_HEAPTRACK_OUTPUT",
|
|
config.with_extension("heaptrack.raw"),
|
|
);
|
|
}
|
|
command.arg("--config").arg(config);
|
|
if !mode.is_empty() {
|
|
command.arg(mode);
|
|
}
|
|
let child = command
|
|
.stdout(std::process::Stdio::piped())
|
|
.stderr(errors)
|
|
.spawn()
|
|
.unwrap();
|
|
let mut server = Self { child, port };
|
|
let until = Instant::now() + Duration::from_secs(10);
|
|
loop {
|
|
if let Some(status) = server.child.try_wait().unwrap() {
|
|
let reason = fs::read_to_string(&log).unwrap();
|
|
panic!("API exited {status}: {reason}");
|
|
}
|
|
if TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
|
break;
|
|
}
|
|
assert!(Instant::now() < until, "API did not start");
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
server
|
|
}
|
|
pub(super) fn call(
|
|
&self,
|
|
method: &str,
|
|
path: &str,
|
|
body: &str,
|
|
headers: &str,
|
|
) -> (u16, serde_json::Value) {
|
|
let (status, body, _) = self.response(method, path, body, headers);
|
|
(status, body)
|
|
}
|
|
fn response(
|
|
&self,
|
|
method: &str,
|
|
path: &str,
|
|
body: &str,
|
|
headers: &str,
|
|
) -> (u16, serde_json::Value, String) {
|
|
let (status, body, head) = self.raw_response(method, path, body, headers);
|
|
(
|
|
status,
|
|
serde_json::from_str(&body).expect("API response JSON"),
|
|
head,
|
|
)
|
|
}
|
|
pub(super) fn raw_response(
|
|
&self,
|
|
method: &str,
|
|
path: &str,
|
|
body: &str,
|
|
headers: &str,
|
|
) -> (u16, String, String) {
|
|
let mut stream = TcpStream::connect(("127.0.0.1", self.port)).unwrap();
|
|
stream
|
|
.set_read_timeout(Some(Duration::from_secs(5)))
|
|
.unwrap();
|
|
write!(stream,"{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\nContent-Length: {}\r\n{headers}\r\n{body}",body.len()).unwrap();
|
|
let mut output = String::new();
|
|
stream.read_to_string(&mut output).unwrap();
|
|
let (head, body) = output.split_once("\r\n\r\n").expect("HTTP response");
|
|
(
|
|
head.split_whitespace().nth(1).unwrap().parse().unwrap(),
|
|
body.to_owned(),
|
|
head.to_owned(),
|
|
)
|
|
}
|
|
fn terminate(&self) {
|
|
assert!(
|
|
Command::new("sh")
|
|
.args(["-c", &format!("kill -TERM {}", self.child.id())])
|
|
.status()
|
|
.unwrap()
|
|
.success()
|
|
);
|
|
}
|
|
fn wait_for_exit(&mut self) -> std::process::ExitStatus {
|
|
let until = Instant::now() + Duration::from_secs(5);
|
|
loop {
|
|
if let Some(status) = self.child.try_wait().unwrap() {
|
|
return status;
|
|
}
|
|
assert!(Instant::now() < until, "API failed to drain");
|
|
std::thread::sleep(Duration::from_millis(10));
|
|
}
|
|
}
|
|
pub(super) fn stop(mut self) {
|
|
self.terminate();
|
|
assert!(self.wait_for_exit().success());
|
|
}
|
|
}
|
|
impl Drop for Server {
|
|
fn drop(&mut self) {
|
|
if self.child.try_wait().unwrap().is_none() {
|
|
let _ = self.child.kill();
|
|
let _ = self.child.wait();
|
|
}
|
|
}
|
|
}
|
|
pub(super) fn config(root: &Path) -> (PathBuf, u16, serde_json::Value) {
|
|
let port = std::net::TcpListener::bind("127.0.0.1:0")
|
|
.unwrap()
|
|
.local_addr()
|
|
.unwrap()
|
|
.port();
|
|
let value = serde_json::json!({"http":{"host":"127.0.0.1","port":port},"sites":{"front":{"path":"front","hosts":["localhost"]}}});
|
|
(root.join("config/setting.json"), port, value)
|
|
}
|
|
#[test]
|
|
fn generated_public_http_uses_typed_query_json_errors_and_graceful_shutdown() {
|
|
let root = project(
|
|
"api-public",
|
|
r#"
|
|
type Pair { text: Text, count: Int }
|
|
hello(name: Text, count: Int >= 1 and <= 3, optional: Text?) (out: Text) {
|
|
out = name
|
|
}
|
|
flow reject(accept: Bool) ()
|
|
| step | kind | do |
|
|
| - | check | accept else Conflict |
|
|
pair(value: Pair) (out: Pair) {out = value}
|
|
"#,
|
|
"public get hello = app.hello\npublic post pair = app.pair\npublic post reject = app.reject",
|
|
);
|
|
let (loaded, program) = analyze(&root);
|
|
assert_eq!(program.http[0].path, "/demo/service/front/main/hello");
|
|
let artifact = build::build(&loaded, &program, "main", Profile::Dev, None).unwrap();
|
|
let (path, port, value) = config(&root);
|
|
fs::write(&path, value.to_string()).unwrap();
|
|
let server = Server::mode(&artifact.binary, &path, port, "");
|
|
let (status, body) = server.call(
|
|
"GET",
|
|
"/demo/service/front/main/hello?name=%E4%B8%AD%E6%96%87+ok&count=2",
|
|
"",
|
|
"",
|
|
);
|
|
assert_eq!(status, 200);
|
|
assert_eq!(body["data"], "中文 ok");
|
|
for query in [
|
|
"name=a&count=0",
|
|
"name=a&name=b&count=1",
|
|
"name=a&count=1&extra=2",
|
|
"name=a",
|
|
"name=a&count=no",
|
|
] {
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"GET",
|
|
&format!("/demo/service/front/main/hello?{query}"),
|
|
"",
|
|
""
|
|
)
|
|
.0,
|
|
400
|
|
);
|
|
}
|
|
let json = "Content-Type: application/json\r\n";
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"POST",
|
|
"/demo/service/front/main/pair",
|
|
r#"{"value":{"text":"中文","count":3}}"#,
|
|
json
|
|
)
|
|
.1["data"]["text"],
|
|
"中文"
|
|
);
|
|
for body in [
|
|
r#"{"value":{"text":"a","count":1,"count":2}}"#,
|
|
r#"{"value":{"text":"a","count":1,"extra":2}}"#,
|
|
"[]",
|
|
] {
|
|
assert_eq!(
|
|
server
|
|
.call("POST", "/demo/service/front/main/pair", body, json)
|
|
.0,
|
|
400
|
|
);
|
|
}
|
|
assert_eq!(
|
|
server
|
|
.call(
|
|
"POST",
|
|
"/demo/service/front/main/reject",
|
|
r#"{"accept":false}"#,
|
|
json
|
|
)
|
|
.0,
|
|
409
|
|
);
|
|
assert!(
|
|
server
|
|
.call(
|
|
"POST",
|
|
"/demo/service/front/main/reject",
|
|
r#"{"accept":true}"#,
|
|
json
|
|
)
|
|
.1["data"]
|
|
.is_null()
|
|
);
|
|
assert_eq!(
|
|
server
|
|
.call("GET", "/demo/service/front/main/missing", "", "")
|
|
.0,
|
|
404
|
|
);
|
|
server.stop();
|
|
}
|