Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions crates/anyedge-cli/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -223,4 +223,23 @@ mod tests {

std::env::remove_var("ANYEDGE_TEST_SECRET");
}

#[test]
fn shell_escape_quotes_and_spaces() {
assert_eq!(super::shell_escape("plain"), "plain");
assert_eq!(super::shell_escape("with space"), "'with space'");
assert_eq!(super::shell_escape("needs'quote"), "'needs'\"'\"'quote'");
assert_eq!(super::shell_escape(""), "''");
}

#[test]
fn shell_join_combines_arguments_with_escaping() {
let args = vec![
"plain".to_string(),
"with space".to_string(),
"needs'quote".to_string(),
];
let joined = super::shell_join(&args);
assert_eq!(joined, "plain 'with space' 'needs'\"'\"'quote'");
}
}
48 changes: 48 additions & 0 deletions crates/anyedge-cli/src/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,51 @@ pub struct NewArgs {
#[arg(long)]
pub local_core: bool,
}

#[cfg(test)]
mod tests {
use super::*;
use clap::Parser;

#[test]
fn parses_new_command_with_defaults() {
let args = Args::try_parse_from(["anyedge", "new", "demo-app"]).expect("parse new");
match args.cmd {
Command::New(new_args) => {
assert_eq!(new_args.name, "demo-app");
assert!(new_args.dir.is_none());
assert!(!new_args.local_core);
}
other => panic!("unexpected command: {other:?}"),
}
}

#[test]
fn parses_build_command_with_passthrough_args() {
let args = Args::try_parse_from([
"anyedge",
"build",
"--adapter",
"fastly",
"--",
"--flag",
"value",
])
.expect("parse build");
match args.cmd {
Command::Build {
adapter,
adapter_args,
} => {
assert_eq!(adapter, "fastly");
assert_eq!(adapter_args, vec!["--flag", "value"]);
}
other => panic!("unexpected command: {other:?}"),
}
}

#[test]
fn missing_required_adapter_returns_error() {
assert!(Args::try_parse_from(["anyedge", "build"]).is_err());
}
}
116 changes: 99 additions & 17 deletions crates/anyedge-cli/src/dev_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,14 @@ fn handle_conn(stream: &mut TcpStream, router: RouterService) -> std::io::Result
}
}

let req_text = String::from_utf8_lossy(&buf[..read]);
let mut lines = req_text.split("\r\n");
let request = request_from_buffer(&buf[..read])?;
let response = block_on(router.oneshot(request));
write_response(stream, response)
}

fn request_from_buffer(raw: &[u8]) -> std::io::Result<anyedge_core::http::Request> {
let req_text = String::from_utf8_lossy(raw);
let mut lines = req_text.lines();
let request_line = lines.next().unwrap_or("");
let mut parts = request_line.split_whitespace();
let method_token = parts.next().unwrap_or("GET");
Expand Down Expand Up @@ -84,30 +90,42 @@ fn handle_conn(stream: &mut TcpStream, router: RouterService) -> std::io::Result
}
}

let response = block_on(router.oneshot(req));
write_response(stream, response)
Ok(req)
}

fn write_response(stream: &mut TcpStream, response: CoreResponse) -> std::io::Result<()> {
let (head, body) = serialize_response(response)?;
stream.write_all(&head)?;
stream.write_all(&body)?;
Ok(())
}

fn serialize_response(response: CoreResponse) -> std::io::Result<(Vec<u8>, Vec<u8>)> {
let (parts, body) = response.into_parts();
let status = parts.status;
let reason = status.canonical_reason().unwrap_or("OK");

let mut out = Vec::new();
out.extend_from_slice(format!("HTTP/1.1 {} {}\r\n", status.as_u16(), reason).as_bytes());
let mut head = Vec::new();
head.extend_from_slice(b"HTTP/1.1 ");
let status_code = status.as_u16().to_string();
head.extend_from_slice(status_code.as_bytes());
head.push(b' ');
head.extend_from_slice(reason.as_bytes());
head.extend_from_slice(b"\r\n");

let mut has_content_length = false;
for (name, value) in parts.headers.iter() {
if name.as_str().eq_ignore_ascii_case("content-length") {
has_content_length = true;
}
out.extend_from_slice(
format!("{}: {}\r\n", name.as_str(), value.to_str().unwrap_or("")).as_bytes(),
);
head.extend_from_slice(name.as_str().as_bytes());
head.extend_from_slice(b": ");
head.extend_from_slice(value.to_str().unwrap_or("").as_bytes());
head.extend_from_slice(b"\r\n");
}

let body_bytes = match body {
Body::Once(bytes) => bytes,
let body_bytes: Vec<u8> = match body {
Body::Once(bytes) => bytes.to_vec(),
Body::Stream(stream_body) => {
let collected = block_on(async move {
let mut buf = Vec::new();
Expand All @@ -118,18 +136,19 @@ fn write_response(stream: &mut TcpStream, response: CoreResponse) -> std::io::Re
}
Ok::<Vec<u8>, std::io::Error>(buf)
})?;
collected.into()
collected
}
};

if !has_content_length {
out.extend_from_slice(format!("Content-Length: {}\r\n", body_bytes.len()).as_bytes());
head.extend_from_slice(b"Content-Length: ");
head.extend_from_slice(body_bytes.len().to_string().as_bytes());
head.extend_from_slice(b"\r\n");
}

out.extend_from_slice(b"\r\n");
stream.write_all(&out)?;
stream.write_all(body_bytes.as_ref())?;
Ok(())
head.extend_from_slice(b"\r\n");

Ok((head, body_bytes))
}

fn build_dev_router() -> RouterService {
Expand Down Expand Up @@ -172,3 +191,66 @@ async fn dev_root() -> Text<&'static str> {
async fn dev_echo(Path(params): anyedge_core::extractor::Path<EchoParams>) -> Text<String> {
Text::new(format!("hello {}", params.name))
}

#[cfg(test)]
mod tests {
use super::*;
use anyedge_core::http::{header::HOST, response_builder, Method, StatusCode};
use anyedge_core::response::Text;

#[anyedge_core::action]
async fn hello() -> Text<&'static str> {
Text::new("hello world")
}

#[test]
fn request_from_buffer_parses_basic_get() {
let request = request_from_buffer(
b"GET /demo HTTP/1.1
Host: example

",
)
.expect("request");
assert_eq!(request.method(), Method::GET);
assert_eq!(request.uri().path(), "/demo");
assert_eq!(
request
.headers()
.get(HOST)
.and_then(|value| value.to_str().ok()),
Some("example")
);
}

#[test]
fn serialize_response_includes_headers_and_body() {
let response = response_builder()
.status(StatusCode::OK)
.header("x-test", "value")
.body(Body::text("hi"))
.expect("response");
let (head, body) = serialize_response(response).expect("serialize");
let head_text = String::from_utf8(head).expect("utf8");
assert!(head_text.starts_with("HTTP/1.1 200 OK"));
assert!(head_text.contains("Content-Length: 2"));
assert!(head_text.contains("x-test: value"));
assert!(head_text.contains("\r\n\r\n"));
assert_eq!(body, b"hi");
}

#[test]
fn router_handles_request_via_helpers() {
let router = RouterService::builder().get("/", hello).build();
let request = request_from_buffer(
b"GET / HTTP/1.1
Host: localhost

",
)
.expect("request");
let response = block_on(router.oneshot(request));
let (_head, body) = serialize_response(response).expect("serialize");
assert_eq!(body, b"hello world");
}
}
Loading